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

# Lend and borrow local stablecoins with CapyFi

> Recipe to supply wARS and wBRL to CapyFi and access yield in local currency stablecoins, or borrow wARS and wBRL against USDC, ETH or BTC, on Ethereum, Base and World Chain.

This recipe shows how to add lending of Ripio's [wFiat](https://docs.ripio.com/wfiat/overview.md) stablecoins to your product with [CapyFi](https://docs.capyfi.com), a lending protocol forked from Compound v2. CapyFi lists **wARS** and **wBRL** markets on Ethereum, Base and World Chain, so you can offer two products on the same contracts:

* **Supply wFiat** and access yield: borrowers pay interest, and returns accrue in local currency stablecoins, depending on borrowing demand.
* **Borrow wFiat** against USDC, ETH or BTC: users receive wARS or wBRL without selling their collateral, and can off-ramp them to ARS or BRL with Ripio's [Ramps API](https://docs.ripio.com/ramps-api/overview/introduction.md).

> [!NOTE]
>
> Ripio doesn't operate, administer or guarantee CapyFi. It is a third-party protocol with its own smart contracts, price oracle and risk parameters, which its administrators can change. Read the [risks](#risks-to-disclose-to-your-users) before you offer it to your users.

## How it works

**1. Suppliers deposit into a market**

Each asset has a market, the **caToken** contract. Supplying wARS to the caWARS market mints caWARS to the supplier.

**2. Borrowers post collateral and borrow**

A borrower supplies an asset with a collateral factor, such as USDC, enables it as collateral, and borrows wARS up to their borrow limit. Interest on the debt accrues every block.

**3. Borrower interest accrues to the market**

caTokens don't rebase: each caToken is redeemable for more of the underlying asset over time, as borrowers pay interest. Suppliers redeem their caTokens for the underlying, including accrued interest, subject to the market's available liquidity.

**4. Undercollateralized accounts get liquidated**

If the value of a borrower's debt rises above their borrow limit, liquidators can repay part of it and seize the borrower's collateral at a discount.

> [!NOTE]
>
> wFiat markets have a **collateral factor of 0**: you can supply and borrow wARS and wBRL, but they don't add to a user's borrow limit. To borrow, users post USDC, ETH or BTC.

## Markets

| Market | Network | caToken address | Comptroller (Unitroller) |
| - | - | - | - |
| ![wARS](https://b2b-widget-onramp.ripio.com/wars.png)**wARS** ![](https://flagcdn.com/ar.svg) | Ethereum | `0xf80eeec09f417Fa7FCc4A848Ef03af9dF2658d7B` | `0x0b9af1fd73885aD52680A1aeAa7A3f17AC702afA` |
| ![wARS](https://b2b-widget-onramp.ripio.com/wars.png)**wARS** ![](https://flagcdn.com/ar.svg) | Base | `0x304Cc2588850A59eC1E59a998Ce883De0e884d23` | `0x00dc4965916e03A734190fA382633657c71f867E` |
| ![wARS](https://b2b-widget-onramp.ripio.com/wars.png)**wARS** ![](https://flagcdn.com/ar.svg) | World Chain | `0xF36749472Ad6dA1CcF9eDe8ff321654990635FfA` | `0x589d63300976759a0fc74ea6fA7D951f581252D7` |
| ![wBRL](https://b2b-widget-onramp.ripio.com/wbrl.png)**wBRL** ![](https://flagcdn.com/br.svg) | Ethereum | `0x93d9DdEeBf3B5DBF7D7dFC04D3804Ce5450987C8` | `0x0b9af1fd73885aD52680A1aeAa7A3f17AC702afA` |
| ![wBRL](https://b2b-widget-onramp.ripio.com/wbrl.png)**wBRL** ![](https://flagcdn.com/br.svg) | Base | `0x601222822Dd82c68590A9C4A6B34Df62EF361FC8` | `0x00dc4965916e03A734190fA382633657c71f867E` |
| ![wBRL](https://b2b-widget-onramp.ripio.com/wbrl.png)**wBRL** ![](https://flagcdn.com/br.svg) | World Chain | `0x90208d4Be7F539bd46E0e0847085E672E23b3d9A` | `0x589d63300976759a0fc74ea6fA7D951f581252D7` |

The underlying wARS and wBRL use the same address on every chain (see [Contracts](https://docs.ripio.com/wfiat/contracts.md)), with 18 decimals; caTokens have 8 decimals. The Comptrollers on Ethereum and Base also list wMXN and wCOP markets, and the World Chain wBRL market isn't on CapyFi's Networks page yet: all of them are listed on-chain. Read `getAllMarkets()` on the Comptroller for the live list, and CapyFi's [Networks](https://docs.capyfi.com/networks) page for the other contracts.

| Network | Main collateral assets |
| - | - |
| Ethereum | ETH, WBTC, USDC, USDT |
| Base | ETH, cbBTC, USDC |
| World Chain | ETH, WBTC, USDC |

At the time of writing, collateral factors for these assets range from 80% to 85%. Read each one with `markets(caToken)` on the Comptroller instead of hardcoding it. The Ethereum Comptroller also lists a legacy caETH market (`0xbaA6bc4E24686d710B9318B49b0Bb16ec7C46bFA`) with supply and borrows paused: use `0x37DE57183491Fa9745d8Fa5DCd950f0c3a4645c9`, and don't pick markets from `getAllMarkets()` by symbol alone.

## Choose your integration

> [card] [Link out](https://app.capyfi.com)
>
> Send users to the CapyFi app. No code, but users leave your product.

> [card] Direct contract calls
>
> Call the caToken and Comptroller contracts from your app or backend. Full control; this recipe shows it with viem.

## Recipe

The examples below use [viem](https://viem.sh/) on **Base**, where gas costs are low. The same calls work on Ethereum and World Chain: change the chain, the Comptroller and the caToken addresses.

### 0. Setup, constants and ABI

```bash theme={null}
npm install viem
```

```ts clients.ts theme={null}
import { createPublicClient, createWalletClient, http, type Account } from 'viem';
import { base } from 'viem/chains';

// Use your own RPC endpoint: rates, liquidity and simulations come from it
const transport = http(process.env.BASE_RPC_URL);

export const publicClient = createPublicClient({ chain: base, transport });

// The user's wallet (for example, from your wallet connector) or a custody
// signer such as a KMS. Never hardcode private keys.
declare const account: Account;

export const walletClient = createWalletClient({ account, chain: base, transport });
```

```ts constants.ts theme={null}
// CapyFi on Base (chain id 8453)
export const COMPTROLLER = '0x00dc4965916e03A734190fA382633657c71f867E'; // Unitroller proxy

// caTokens: the CapyFi market for each asset (8 decimals)
export const MARKETS = {
  wARS: '0x304Cc2588850A59eC1E59a998Ce883De0e884d23', // caWARS
  wBRL: '0x601222822Dd82c68590A9C4A6B34Df62EF361FC8', // caWBRL
  USDC: '0x5aDb71adb317CE975A405e90335068F0aF9F26C7', // caUSDC
} as const;

// Underlying tokens
export const TOKENS = {
  wARS: '0x0DC4F92879B7670e5f4e4e6e3c801D229129D90D', // 18 decimals
  wBRL: '0xD76f5Faf6888e24D9F04Bf92a0c8B921FE4390e0', // 18 decimals
  USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // 6 decimals
} as const;
```

```ts abi.ts theme={null}
import { parseAbi } from 'viem';

// caToken (Compound v2 CErc20) subset, plus the custom errors it reverts with
export const CTOKEN_ABI = parseAbi([
  'function mint(uint256 mintAmount) returns (uint256)',
  'function redeem(uint256 redeemTokens) returns (uint256)',
  'function redeemUnderlying(uint256 redeemAmount) returns (uint256)',
  'function borrow(uint256 borrowAmount) returns (uint256)',
  'function repayBorrow(uint256 repayAmount) returns (uint256)',
  'function borrowBalanceCurrent(address account) returns (uint256)',
  'function balanceOf(address owner) view returns (uint256)',
  'function exchangeRateStored() view returns (uint256)',
  'function supplyRatePerBlock() view returns (uint256)',
  'function borrowRatePerBlock() view returns (uint256)',
  'function getCash() view returns (uint256)',
  'function totalBorrows() view returns (uint256)',
  'function interestRateModel() view returns (address)',
  'event Mint(address minter, uint256 mintAmount, uint256 mintTokens)',
  'event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens)',
  'event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows)',
  'event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows)',
  'error MintComptrollerRejection(uint256 errorCode)',
  'error RedeemComptrollerRejection(uint256 errorCode)',
  'error RedeemTransferOutNotPossible()',
  'error BorrowComptrollerRejection(uint256 errorCode)',
  'error BorrowCashNotAvailable()',
  'error RepayBorrowComptrollerRejection(uint256 errorCode)',
  // Raised by the underlying wFiat or USDC when transferFrom fails
  'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
  'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
]);

// Call these on the Unitroller address
export const COMPTROLLER_ABI = parseAbi([
  'function enterMarkets(address[] cTokens) returns (uint256[])',
  'function getAssetsIn(address account) view returns (address[])',
  'function getAccountLiquidity(address account) view returns (uint256, uint256, uint256)',
  'function markets(address cToken) view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped)',
  'function borrowCaps(address cToken) view returns (uint256)',
  'function mintGuardianPaused(address cToken) view returns (bool)',
  'function borrowGuardianPaused(address cToken) view returns (bool)',
  'function oracle() view returns (address)',
]);

export const ORACLE_ABI = parseAbi(['function getUnderlyingPrice(address cToken) view returns (uint256)']);

export const RATE_MODEL_ABI = parseAbi(['function blocksPerYear() view returns (uint256)']);

export const ERC20_ABI = parseAbi([
  'function approve(address spender, uint256 amount) returns (bool)',
  'function allowance(address owner, address spender) view returns (uint256)',
  'function balanceOf(address owner) view returns (uint256)',
  'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
  'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
]);
```

```ts tx.ts theme={null}
import type { Abi, Address } from 'viem';
import { publicClient, walletClient } from './clients';
import { ERC20_ABI } from './abi';

type Call = { address: Address; abi: Abi; functionName: string; args?: readonly unknown[] };

// Simulate, send and wait. caToken calls return 0 on success: any other code is a failure
export async function send(call: Call) {
  const { request, result } = await publicClient.simulateContract({ ...call, account: walletClient.account });
  if (typeof result === 'bigint' && result !== 0n) {
    throw new Error(`${call.functionName} failed with error code ${result}`);
  }
  const hash = await walletClient.writeContract(request);
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  if (receipt.status !== 'success') throw new Error(`${call.functionName} reverted: ${hash}`);
  return receipt;
}

// Approve `spender` for `amount` if the current allowance is lower
export async function ensureAllowance(token: Address, spender: Address, amount: bigint) {
  const allowance = await publicClient.readContract({
    address: token,
    abi: ERC20_ABI,
    functionName: 'allowance',
    args: [walletClient.account.address, spender],
  });
  if (allowance < amount) {
    await send({ address: token, abi: ERC20_ABI, functionName: 'approve', args: [spender, amount] });
  }
}
```

caToken functions either revert with a custom error or return a non-zero error code instead of reverting, depending on the call, so `send` checks both before it sends anything. The snippets in the next steps import from these files.

### 1. Get wFiat on Base

* **Buy it:** deliver wARS or wBRL to the user's wallet on Base with [Ramps](https://docs.ripio.com/ramps-api/overview/introduction.md), if Base is supported for that token (see [Get Withdrawal Networks](https://docs.ripio.com/ramps-api/networks/get-withdrawal-networks.md)) (see the [on/off-ramp recipe for Privy wallets](https://docs.ripio.com/wfiat/recipes/privy-ramps.md)) or [Crypto as a Service](https://docs.ripio.com/crypto-as-a-service/overview/introduction.md).
* **Swap it:** from USDC or any other token, on any chain, with the [LI.FI recipe](https://docs.ripio.com/wfiat/recipes/lifi-swaps.md).
* **Bridge it:** from any other supported chain to Base (chain id `8453`) with the [Ripio Bridge](https://docs.ripio.com/wfiat/bridge.md).

Users also need ETH on Base to pay for gas.

### 2. Show rates and available liquidity

Rates are per block, so convert them with the market's `blocksPerYear`. Block times differ per chain: the rate models report 2,628,000 blocks per year on Ethereum and 15,768,000 on Base and World Chain.

```ts market.ts theme={null}
import { formatUnits, type Address } from 'viem';
import { publicClient } from './clients';
import { COMPTROLLER } from './constants';
import { COMPTROLLER_ABI, CTOKEN_ABI, RATE_MODEL_ABI } from './abi';

// Per-block rate (1e18 mantissa) to APY, compounding daily
function toApy(ratePerBlock: bigint, blocksPerYear: bigint) {
  const blocksPerDay = Number(blocksPerYear) / 365;
  return (1 + (Number(ratePerBlock) / 1e18) * blocksPerDay) ** 365 - 1;
}

export async function getMarket(cToken: Address, decimals = 18) {
  const ctoken = { address: cToken, abi: CTOKEN_ABI } as const;
  const comptroller = { address: COMPTROLLER, abi: COMPTROLLER_ABI } as const;

  const [supplyRate, borrowRate, cash, totalBorrows, rateModel, market, borrowCap, mintPaused, borrowPaused] =
    await publicClient.multicall({
      allowFailure: false,
      contracts: [
        { ...ctoken, functionName: 'supplyRatePerBlock' },
        { ...ctoken, functionName: 'borrowRatePerBlock' },
        { ...ctoken, functionName: 'getCash' },
        { ...ctoken, functionName: 'totalBorrows' },
        { ...ctoken, functionName: 'interestRateModel' },
        { ...comptroller, functionName: 'markets', args: [cToken] },
        { ...comptroller, functionName: 'borrowCaps', args: [cToken] },
        { ...comptroller, functionName: 'mintGuardianPaused', args: [cToken] },
        { ...comptroller, functionName: 'borrowGuardianPaused', args: [cToken] },
      ],
    });

  // Rates are per block, and block times differ per chain: read blocksPerYear, don't hardcode it
  const blocksPerYear = await publicClient.readContract({
    address: rateModel,
    abi: RATE_MODEL_ABI,
    functionName: 'blocksPerYear',
  });

  // What can be borrowed right now: market cash, capped by the borrow cap (0 = no cap)
  const capRoom = borrowCap === 0n ? cash : borrowCap > totalBorrows ? borrowCap - totalBorrows : 0n;
  const borrowable = cash < capRoom ? cash : capRoom;

  return {
    supplyApy: toApy(supplyRate, blocksPerYear),
    borrowApy: toApy(borrowRate, blocksPerYear),
    utilization: cash + totalBorrows === 0n ? 0 : Number(totalBorrows) / Number(cash + totalBorrows),
    cash: formatUnits(cash, decimals),
    borrowable: formatUnits(borrowable, decimals),
    collateralFactor: Number(market[1]) / 1e18,
    mintPaused,
    borrowPaused,
  };
}
```

| Field | Meaning |
| - | - |
| `supplyApy` | What suppliers receive now, from borrower interest after the reserve factor. Variable. |
| `borrowApy` | What borrowers pay now. Variable. |
| `borrowable` | wFiat that can be borrowed right now: the market's cash, limited by its borrow cap. |
| `cash` | wFiat in the market, which also bounds how much suppliers can withdraw at once. |
| `mintPaused`, `borrowPaused` | The protocol's pause guardian can stop new supply or new borrows per market. Hide the action when they're `true`. |

A caToken can also have a [Whitelist](https://docs.capyfi.com/whitelist) contract: while its `isActive()` returns `true`, only whitelisted addresses can supply, borrow or hold that caToken. The wFiat markets don't set one today; read `whitelist()` on the caToken before you show a market.

Values are decimals: `0.05` means 5%. Rates move with utilization, so refresh them before every action and never present them as fixed.

### 3. Supply wFiat

The user approves the caToken on the wFiat token and calls `mint`. caTokens are minted to the caller.

```ts supply.ts theme={null}
import { parseEventLogs, parseUnits } from 'viem';
import { send, ensureAllowance } from './tx';
import { MARKETS, TOKENS } from './constants';
import { CTOKEN_ABI } from './abi';

const amount = parseUnits('100000', 18); // 100,000 wARS

// 1. Let caWARS pull the wARS
await ensureAllowance(TOKENS.wARS, MARKETS.wARS, amount);

// 2. Supply: caWARS mints caTokens to the caller
const receipt = await send({ address: MARKETS.wARS, abi: CTOKEN_ABI, functionName: 'mint', args: [amount] });

// 3. Record the caTokens actually minted, read from the receipt
const [mint] = parseEventLogs({
  abi: CTOKEN_ABI,
  eventName: 'Mint',
  logs: receipt.logs.filter((log) => log.address.toLowerCase() === MARKETS.wARS.toLowerCase()),
});
console.log('caWARS minted:', mint.args.mintTokens);
```

If you credit users from an internal ledger, record `mintTokens` from the receipt, not an amount computed from the exchange rate before sending.

### 4. Borrow wFiat against USDC

The user supplies USDC, enables it as collateral with `enterMarkets`, and borrows wARS. The borrow limit is the sum of each collateral's USD value times its collateral factor, and `getAccountLiquidity` returns what's left of it in USD.

```ts borrow.ts theme={null}
import { parseUnits } from 'viem';
import { publicClient, walletClient } from './clients';
import { send, ensureAllowance } from './tx';
import { COMPTROLLER, MARKETS, TOKENS } from './constants';
import { COMPTROLLER_ABI, CTOKEN_ABI, ORACLE_ABI } from './abi';

const account = walletClient.account;

// 1. Supply USDC as collateral
const collateral = parseUnits('1000', 6); // 1,000 USDC
await ensureAllowance(TOKENS.USDC, MARKETS.USDC, collateral);
await send({ address: MARKETS.USDC, abi: CTOKEN_ABI, functionName: 'mint', args: [collateral] });

// 2. Enable it as collateral. enterMarkets returns one error code per market
const { result: codes } = await publicClient.simulateContract({
  account,
  address: COMPTROLLER,
  abi: COMPTROLLER_ABI,
  functionName: 'enterMarkets',
  args: [[MARKETS.USDC]],
});
if (codes.some((code) => code !== 0n)) throw new Error(`enterMarkets failed: ${codes}`);
await send({ address: COMPTROLLER, abi: COMPTROLLER_ABI, functionName: 'enterMarkets', args: [[MARKETS.USDC]] });

// 3. Size the borrow from the account's liquidity (USD, 1e18 mantissa)
const [, liquidity, shortfall] = await publicClient.readContract({
  address: COMPTROLLER,
  abi: COMPTROLLER_ABI,
  functionName: 'getAccountLiquidity',
  args: [account.address],
});
if (shortfall > 0n) throw new Error('Account is under water');

const oracle = await publicClient.readContract({ address: COMPTROLLER, abi: COMPTROLLER_ABI, functionName: 'oracle' });
// USD price of 1 wARS, scaled by 1e(36 - 18) = 1e18
const price = await publicClient.readContract({
  address: oracle,
  abi: ORACLE_ABI,
  functionName: 'getUnderlyingPrice',
  args: [MARKETS.wARS],
});
const maxBorrow = (liquidity * 10n ** 18n) / price; // in wARS (18 decimals)

// Keep a buffer: borrowing the maximum gets the account liquidated on the next price move
const amount = parseUnits('500000', 18); // 500,000 wARS
if (amount > (maxBorrow * 70n) / 100n) throw new Error('Borrow above 70% of the borrow limit');

// 4. Borrow: caWARS sends wARS to the caller and records the debt
await send({ address: MARKETS.wARS, abi: CTOKEN_ABI, functionName: 'borrow', args: [amount] });
```

> [!WARNING]
>
> The debt is in wARS, but the collateral is in USD terms. If the local currency appreciates against the dollar or the collateral price drops, the debt's value rises against the borrow limit and the account can be liquidated. Show the borrow limit used and warn users well before it reaches 100%.

To post ETH instead, call the payable `mint()` on the caETH market with `value` set, and enter that market. For BTC, use the caCBBTC market on Base or caWBTC on Ethereum and World Chain.

**Cash out the loan.** To turn the borrowed wARS into pesos in a bank account, send them to Ripio with an [off-ramp](https://docs.ripio.com/ramps-api/guides/off-ramp-integration.md). Check that the token is rampable from Base with [Get Deposit Networks](https://docs.ripio.com/ramps-api/networks/get-deposit-networks.md), or [bridge](https://docs.ripio.com/wfiat/bridge.md) it to a chain that is.

### 5. Track the position

```ts position.ts theme={null}
import { publicClient, walletClient } from './clients';
import { COMPTROLLER, MARKETS } from './constants';
import { COMPTROLLER_ABI, CTOKEN_ABI, ORACLE_ABI } from './abi';

const account = walletClient.account;

// Debt including the interest accrued up to this block (a state-changing call, run as eth_call)
const { result: debt } = await publicClient.simulateContract({
  account,
  address: MARKETS.wARS,
  abi: CTOKEN_ABI,
  functionName: 'borrowBalanceCurrent',
  args: [account.address],
});

// Liquidity = borrow limit - borrows, in USD (1e18). Shortfall > 0 means the account can be liquidated
const [, liquidity, shortfall] = await publicClient.readContract({
  address: COMPTROLLER,
  abi: COMPTROLLER_ABI,
  functionName: 'getAccountLiquidity',
  args: [account.address],
});

// Value the debt in USD (1e18) with the oracle price, then the share of the borrow limit in use
const oracle = await publicClient.readContract({ address: COMPTROLLER, abi: COMPTROLLER_ABI, functionName: 'oracle' });
const price = await publicClient.readContract({
  address: oracle,
  abi: ORACLE_ABI,
  functionName: 'getUnderlyingPrice',
  args: [MARKETS.wARS],
});
const debtUsd = (debt * price) / 10n ** 18n;
const borrowLimitUsed = shortfall > 0n ? 1 : debtUsd === 0n ? 0 : Number(debtUsd) / Number(debtUsd + liquidity);

console.log({ debt, debtUsd, liquidity, shortfall, borrowLimitUsed });
```

`borrowLimitUsed` assumes wARS is the account's only debt: with several borrowed assets, add the USD value of each. A non-zero `shortfall` means the account can be liquidated now. Liquidators can repay up to the close factor of a debt (50% at the time of writing) and seize collateral worth that amount plus the liquidation incentive (8% at the time of writing). Read both from the Comptroller with `closeFactorMantissa()` and `liquidationIncentiveMantissa()`.

> [!NOTE]
>
> A user who supplies wFiat and borrows in the same account puts that wFiat at risk too: a collateral factor of 0 means it doesn't add to the borrow limit, but liquidators can still seize it once the account is in shortfall.

### 6. Repay

```ts repay.ts theme={null}
import { maxUint256 } from 'viem';
import { publicClient, walletClient } from './clients';
import { send, ensureAllowance } from './tx';
import { MARKETS, TOKENS } from './constants';
import { CTOKEN_ABI, ERC20_ABI } from './abi';

const account = walletClient.account;

// Current debt, with interest accrued up to this block
const { result: debt } = await publicClient.simulateContract({
  account,
  address: MARKETS.wARS,
  abi: CTOKEN_ABI,
  functionName: 'borrowBalanceCurrent',
  args: [account.address],
});

// Interest keeps accruing every block: the user needs a small buffer above the debt
const needed = (debt * 1001n) / 1000n;
const balance = await publicClient.readContract({
  address: TOKENS.wARS,
  abi: ERC20_ABI,
  functionName: 'balanceOf',
  args: [account.address],
});

if (balance >= needed) {
  // maxUint256 repays the full debt at execution time, leaving no dust
  await ensureAllowance(TOKENS.wARS, MARKETS.wARS, needed);
  await send({ address: MARKETS.wARS, abi: CTOKEN_ABI, functionName: 'repayBorrow', args: [maxUint256] });
} else {
  // Not enough wARS for a full repayment: repay what the user holds, or ask for the rest
  await ensureAllowance(TOKENS.wARS, MARKETS.wARS, balance);
  await send({ address: MARKETS.wARS, abi: CTOKEN_ABI, functionName: 'repayBorrow', args: [balance] });
}
```

Use `repayBorrowBehalf(borrower, amount)` on the caToken to repay a debt from another address, for example from your treasury.

### 7. Withdraw

```ts withdraw.ts theme={null}
import { publicClient, walletClient } from './clients';
import { send } from './tx';
import { MARKETS } from './constants';
import { CTOKEN_ABI } from './abi';

const account = walletClient.account;

// Full exit: redeem every caWARS for wARS
const caTokens = await publicClient.readContract({
  address: MARKETS.wARS,
  abi: CTOKEN_ABI,
  functionName: 'balanceOf',
  args: [account.address],
});
await send({ address: MARKETS.wARS, abi: CTOKEN_ABI, functionName: 'redeem', args: [caTokens] });
```

Use `redeemUnderlying(amount)` to withdraw an exact amount of wFiat instead. A withdrawal fails when:

* **The market doesn't have enough cash.** Suppliers can only withdraw what isn't lent out. When utilization is high, they wait for borrowers to repay or for rates to attract new supply.
* **It would leave a debt undercollateralized.** Collateral can only be withdrawn down to what the outstanding debt needs: repay first.

Supply also reverts with `WhitelistAccess: not whitelisted` if the market's whitelist is active and the address isn't on it.

## Rewards

CapyFi runs incentive campaigns through Merkle-based distributions: entitlements are computed off-chain per campaign for the address that supplies or borrows, and claimed separately from the market contracts with a Merkle proof served by CapyFi. Today the RewardsDistributor is deployed only on Ethereum. See CapyFi's [Rewards](https://docs.capyfi.com/rewards) page for how to claim. Label rewards as a temporary incentive, separate from the market's supply rate.

## Risks to disclose to your users

* **Issuer and peg risk.** wARS and wBRL are issued by Ripio and depend on its reserves backing them. The protocol values them with its price oracle, which may not reflect their market price. A depeg can affect liquidations and the value of positions.
* **Smart contract risk.** Bugs in the caTokens, the Comptroller or the oracle can cause losses. CapyFi reports audits by OpenZeppelin and Coinspect, but audits don't remove the risk.
* **Bad debt risk.** If collateral prices drop faster than liquidations execute, a market can accrue bad debt that its suppliers absorb, and they may not get back everything they supplied.
* **Liquidation risk.** Borrowers lose part of their collateral if their account goes into shortfall, for example because the collateral price drops or the local currency appreciates against the dollar.
* **Oracle risk.** Collateral and debt are valued with CapyFi's price oracle, which the protocol's administrators can replace. An incorrect price can trigger liquidations or let accounts borrow more than they should.
* **Currency risk.** wARS and wBRL track the ARS and BRL. Supply returns accrue in local currency stablecoins, so their value in USD moves with the exchange rate, and so does the value of a wFiat debt.
* **Withdrawal liquidity.** Suppliers can withdraw only the cash in the market. At high utilization, a withdrawal can have to wait until borrowers repay.
* **Governance and pause risk.** Administrators can change collateral factors, borrow caps, interest rate models and the oracle, can pause supply or borrows on a market, and can restrict a market to whitelisted addresses.
* **Variable rates.** Supply and borrow rates depend on utilization and can change every block. Incentive rewards are temporary.

Confirm the product is available in your users' jurisdictions before you offer it.

## Resources

* [CapyFi docs](https://docs.capyfi.com): [caTokens](https://docs.capyfi.com/ctokens), [Comptroller](https://docs.capyfi.com/comptroller), [Price Feed](https://docs.capyfi.com/price-feed) and [Networks](https://docs.capyfi.com/networks)
* [CompoundLens](https://docs.capyfi.com/compound-lens), to read every market or an account's limits in one call
* [wFiat contracts and networks](https://docs.ripio.com/wfiat/contracts.md)
* [Ripio Bridge developer guide](https://docs.ripio.com/wfiat/bridge.md)
* [Off-ramp integration guide](https://docs.ripio.com/ramps-api/guides/off-ramp-integration.md)

Questions about wFiat? Write to [b2b@ripio.com](mailto:b2b@ripio.com).


## Related topics

- [wFiat stablecoins](https://docs.ripio.com/wfiat/overview.md)
- [Swap and route local stablecoins with LI.FI](https://docs.ripio.com/wfiat/recipes/lifi-swaps.md)
- [Get started with Ripio's crypto infrastructure and local stablecoins](https://docs.ripio.com/index.md)
- [Access yield on wFiat with Morpho and KPK vaults](https://docs.ripio.com/wfiat/recipes/morpho-kpk-yield.md)
- [Ripio on/off-ramp for Privy wallets with 1:1 local stablecoins](https://docs.ripio.com/wfiat/recipes/privy-ramps.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.