Buy protection programmatically
Learn how to buy protection programmatically on the Cozy protocol.
Cozy provides a protected borrowing marketplace for investing in decentralized finance protocols that offer protection against a loss of funds. You pay a small premium to purchase protection for funds you deposit and can leverage your investment by borrowing against it. This guide illustrates how you can write a script using TypeScript that you can then use to buy protection from a protection market programmatically,
All code snippets are from the buy-protection.ts script in the Cozy Developer Guides repository. See that repository for more context, definitions of helper methods used, etc.
Everything in this guide assumes that you have experience with JavaScript, ethers.js, and Solidity.

Supply collateral

Before you can buy protection by borrowing protected funds from a Cozy market, you must supply collateral to borrow against.
All markets in Cozy—money markets and protection markets—have a trigger state variable. If the value of the trigger property is the zero address, the money market does not have a trigger contract associated with it. A money market that does not have a trigger contract associated with it cannot be used for protected borrowing, but can be used for ordinary borrowing. If the value of the trigger property is anything except the zero address, the value of the trigger property represents the address of the trigger contract associated with that market. Only assets supplied to Cozy markets that have the zero address for the trigger property, known as money markets, can be used as collateral. Similarly, only Cozy markets with a defined trigger contract, known as protection markets, can be used for protected borrowing.
Therefore, the first step toward protected borrowing is to determine the address of the Cozy money market you intend to use as collateral. To see how to do that, let's assume that you want to buy protection for an ETH investment and you have 2 ETH to use as collateral.

Determine address of the money market

The following code snippet illustrates how to check the trigger property to see if it returns the zero address and how to find the address for the Cozy ETH Money Market where you will deposit your collateral:
buy-protection.ts
1
// STEP 0: ENVIRONMENT SETUP
2
const supplyAmount = '2'; // Supply 2 ETH as collateral
3
const borrowAmount = '500'; // Borrow 500 USDC
4
5
// STEP 1: SUPPLY COLLATERAL
6
// We need the Comptroller, so create an instance of the Comptroller contract
7
const comptrollerAddress = getContractAddress('Comptroller', chainId);
8
const comptroller = new Contract(comptrollerAddress, comptrollerAbi, signer); // connect signer for sending transactions
9
10
// Let's say we have ETH to use as collateral
11
// The first check is to make sure an ETH Money Market exists that we
12
// can supply to. We know that Money Markets have a trigger address
13
// of the zero address, so we use that to query the Comptroller for
14
// the Money Market address
15
const cozyEthAddress = await comptroller.getCToken(ethAddress, AddressZero);
16
17
// If the returned address is the zero address, a money market does
18
// not exist and we cannot supply ETH
19
if (cozyEthAddress === AddressZero) {
20
logFailure('No ETH Money Market exists. Exiting script');
21
return;
22
}
23
logSuccess(`Safe to continue: Found ETH Money Market at ${cozyEthAddress}`);
Copied!
In this example, the ethAddress used as input to the getCToken method is the address 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE that Cozy uses to represent ETH.

Supply the collateral

After verifying that there's a valid Cozy money market available for depositing your collateral, you are ready to supply the collateral to that money market. In this example, you are supplying 2 ETH, and ETH has 18 decimal places, so your script need to account for that. The process is slightly different for ETH than for ERC-20 tokens. The following code and comments describe how supplying collateral using ETH differs from supplying collateral when using ERC-20 tokens.
buy-protection.ts
1
// Create a contract instance of the Cozy ETH money market
2
const cozyEth = new Contract(cozyEthAddress, cozyEthAbi, signer);
3
// To supply ERC-20 tokens as collateral:
4
// const cozyToken = new Contract(cozyTokenAddress, cozyTokenAbi, signer); // for tokens
5
6
// We're now ready to supply the collateral to the market, but there's
7
// some preparation we need to do beforehand. For example, ETH
8
// has 18 decimal places, so we need to take that into account.
9
// `parseUnits` is a method from ethers.js
10
const parsedSupplyAmount = parseUnits(supplyAmount, 18); // scale amount based on number of decimals
11
12
// If using a token, here is where you'd approve the Cozy Money Market
13
// contract to spend your tokens. If you trust the Cozy contract,
14
// approve it to spend the maximum possible amount to avoid future
15
// approvals and save gas. Below we show a sample snippet of an
16
// approval transaction and verifying it was successful:
17
// const approveTx = await token.approve(cozyToken.address, MaxUint256);
18
// await approveTx.wait();
19
// const allowance = await token.allowance(signer.address, cozyToken.address);
20
// if (!allowance.eq(MaxUint256)) {
21
// logFailure('CozyToken does not have sufficient allowance to spend our token. Exiting script');
22
// return;
23
// }
24
// logSuccess('Approval transaction successful. Ready to mint CozyToken with our token');
25
26
// Ready to mint our CozyETH from ETH
27
const mintTx = await cozyEth.mint({ value: parsedSupplyAmount, gasLimit: '5000000' });
28
// const mintTx =await cozyToken.mint(parsedSupplyAmount); // for tokens
29
const { log: mintLog, receipt: mintReceipt } = await findLog(mintTx, cozyEth, 'Mint', provider);
30
logSuccess(`CozyETH successfully minted in transaction ${mintReceipt.transactionHash}`);
Copied!

Verify transaction results

In some cases, the mint transaction can appear to be successful without the mint operation actually being successful.
Because of how Cozy does error handling, transactions can be successful—and be displayed as successful on Etherscan and other block explorers—but without doing what you expected. For example, if a transaction returns an error code and emits a Failure event instead of reverting, it might appear as if the transaction was successful when it has actually failed. You can read more about error codes and failures in Error codes, and see information about error handling history here.
You should manually ensure the mint transaction succeeded before continuing to the next step. You can use the findLog() helper method to simplify the verification process. For more details about using the findLog() method, see the utils.ts file in the Cozy developer Guides repository.

Enter markets

Supplying assets does not automatically mean you can use them as collateral. To use the supplied assets as collateral, you must explicitly call the enterMarkets function on the Comptroller. The following code snippet illustrates how to add your collateral to the market:
buy-protection.ts
1
// STEP 2: ENTER MARKETS
2
// Supplying assets does not automatically mean we can use them as
3
// collateral. To do that, we need to explicitly call enterMarkets
4
// on the Comptroller for each asset we want to use as collateral. For
5
// now, that's just ETH. (We use `em` as shorthand for `enterMarkets`
6
// in our variable names)
7
const markets = [cozyEth.address]; // array of markets to enter
8
const emTx = await comptroller.enterMarkets(markets);
9
const { log: emLog, receipt: emReceipt } = await findLog(emTx, comptroller, 'MarketEntered', provider);
10
logSuccess(`Markets entered successfully: ETH can now be used as collateral`);
Copied!

Borrow funds

Your account is now ready to borrow protected funds. Let's say there's a Yearn protection market for yUSDC, and you want to borrow protected USDC to invest in that protection market. The steps are very similar to the steps for supplying collateral, so let's jump straight to the code:
buy-protection.ts
1
// STEP 3: BORROW FUNDS
2
// Your account is now ready to borrow funds
3
4
// We want to borrow protected USDC so we can deposit it straight into
5
// Yearn's yUSDC vault, so first let's verify the underlying token
6
// we'd borrow is in fact USDC
7
const usdc = new Contract(getContractAddress('USDC', chainId), erc20Abi, signer);
8
const yearnProtectionMarketAddress = getContractAddress('YearnProtectionMarket', chainId);
9
const yearnProtectionMarket = new Contract(yearnProtectionMarketAddress, cozyTokenAbi, signer);
10
const underlying = await yearnProtectionMarket.underlying();
11
if (usdc.address !== getAddress(underlying)) {
12
// We use ethers' getAddress() method to ensure both addresses are
13
// checksummed before comparing them. If this block executes, the
14
// underlying of the protection market is not the underlying we
15
// want (USDC), so we exit the script
16
logFailure('USDC addresses do not match. Exiting script');
17
return;
18
}
19
20
// Now we execute the borrow
21
const parsedBorrowAmount = parseUnits(borrowAmount, await usdc.decimals()); // scale amount based on number of decimals
22
const borrowTx = await yearnProtectionMarket.borrow(parsedBorrowAmount);
23
const { log: borrowLog, receipt: borrowReceipt } = await findLog(borrowTx, yearnProtectionMarket, 'Borrow', provider);
24
logSuccess(`Protected USDC borrowed in transaction ${borrowReceipt.transactionHash}`);
25
26
// Done! You are now supplying ETH as collateral to borrow protected
27
// USDC. The USDC debt will not need to be paid back if the Yearn
28
// trigger event occurs, so the borrowed USDC can now be safely
29
// supplied to Yearn
Copied!
At this point, your account is now supplying 2 ETH as collateral to borrow 500 USDC. That USDC debt will not need to be paid back if the trigger event occurs, so you can safely deposit the 500 USDC into a Yearn vault.
Last modified 1mo ago