4. Creating the index.js Script

Open your favorite code editor (e.g., VSCode) and open the index.js file. We’ll break down the code in chunks to clarify each step.


4.1 Import Libraries & Load Environment Variables

index.js

require('dotenv').config();
const { ethers } = require('ethers');

// Load RPC URL and private key from .env
const RPC_URL = process.env.SEPOLIA_RPC_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;

// Create a provider & signer for Sepolia
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);

Explanation:

• require('dotenv').config() loads environment variables from your .env file.

• ethers.providers.JsonRpcProvider connects to the Ethereum network (Sepolia in this case).

• new ethers.Wallet(...) creates a signer capable of sending transactions, referencing your private key and the given provider.

4.2 Define Contract Addresses & ABIs

Explanation:

• Addresses are specific to the Sepolia USDC market.

• We only include the smart contract functions needed for this tutorial (supply, withdraw, borrowBalanceOf, approve, balanceOf, decimals).

• If you need additional functionality, add the relevant pieces of ABI or use the full ABI from the Comet documentation.

4.3 Create Contract Instances

Explanation:

• Each ethers.Contract instance requires an address, ABI, and signer.

• comet: The main Compound V3 (Comet) contract for USDC base.

• weth: The WETH contract. We’ll deposit this as collateral.

• usdc: The base asset contract (USDC), which we’ll borrow.

4.4 Approve & Supply WETH as Collateral

Explanation:

• First, you approve comet to move your WETH.

• Then you call supply(...) on the comet contract, which effectively deposits WETH as your collateral.

• amount should be in the correct decimal format (we’ll handle that soon).

4.5 Borrow USDC (Base Asset)

Explanation:

• In Compound V3, “borrowing” is done by withdrawing the base asset from the contract.

• This adds to your negative “base” balance, meaning you owe that amount plus interest over time.

4.6 Putting It All Together

Finally, we wrap these functions in a main execution block:

Explanation:

  • We get WETH’s decimals and parse 0.2 WETH into the correct big integer format.

  • Supply that WETH to Comet, thereby increasing our borrowing capacity.

  • Get USDC’s decimals, parse 50 USDC, then borrow it.

  • Check your current USDC debt with borrowBalanceOf(...).

  • Log everything out for clarity.

Last updated