Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions lending-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Lending Protocol on CCF Framework
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An explanation how to use it would be great as it would make the whole example standalone.


## Overview
This is a decentralized lending protocol built on the Microsoft CCF framework. The protocol enables:
- **Collateralized Lending**: Users can deposit BTC or ETH as collateral and borrow USDT.
- **Liquidity Pool Management**: Users can add or remove liquidity from BTC and ETH pools.
- **Interest Distribution**: Liquidity providers earn DEFI tokens as interest rewards.

---

## Features
- **Collateral Management**:
- Deposit BTC or ETH as collateral to borrow USDT.
- Collateral factor applied for safe borrowing limits.

- **Liquidity Pools**:
- BTC and ETH pools for providing liquidity.
- Interest distributed to liquidity providers in DEFI tokens.

- **Wallet Operations**:
- Deposit and withdraw tokens.
- Query wallet balances.

---

## API Endpoints
### Wallet Endpoints
- **Deposit Token**: `/wallet/deposit`
- **Withdraw Token**: `/wallet/withdraw`
- **Get Wallet Balance**: `/wallet/balance`

### Lending Endpoints
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these endpoints correct? lending.ts has only 2 methods exported

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will update the lending.ts as i forgot to add endpt to remove collateral and remove liquidity

- **Add Collateral**: `/lending/collateral/add`
- **Borrow Tokens**: `/lending/borrow`
- **Remove Liquidity**: `/lending/liquidity/remove`

---

## Configuration
- **Collateral Factor**: Default `1.5` (borrow limit = collateral / collateralFactor).
- **Base Interest Rate**: Default `2%` per period.

---

## Example Usage
### Add Collateral
**Request**:
```json
POST /lending/collateral/add
{
"userId": "user1",
"symbol": "BTC",
"amount": 2
}

{
"statusCode": 200,
"body": "Added 2 of token BTC as collateral for user1."
}
```
### Borrow Against Collateral
**Request**:
```json
POST /lending/borrow
{
"userId": "user1",
"borrowAmount": 1000,
"baseTokenSymbol": "USDT"
}

{
"statusCode": 200,
"body": "Borrowed 1000 of token USDT against collateral."
}

```
55 changes: 55 additions & 0 deletions lending-app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions lending-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scripts section is missing, I would expect some basic ones such as build or test

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let me add the build script to generate app.json

"dependencies": {
"@microsoft/ccf-app": "^6.0.0-dev11",
"typescript": "^5.7.3"
},
"devDependencies": {
"@types/node": "^22.10.5"
}
}
154 changes: 154 additions & 0 deletions lending-app/src/endpoints/lending.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import * as ccfapp from "@microsoft/ccf-app";
import { addCollateral, borrow } from "../modules/lending";
import { handleError } from "../utils/errorHandler";


/**
* Handles depositing tokens into the lending protocol for collateral.
*
* This endpoint allows users to directly add tokens to their collateral,
* deducting the specified amount from their wallet balance. The collateral
* is used to increase the user's borrowing capacity.
*
* Input:
* - `userId` (string): The unique identifier for the user making the deposit.
* - `symbol` (string): The token symbol (e.g., "DEFI").
* - `amount` (number): The amount of the token to deposit as collateral.
*
* Output:
* - Success: Returns a success message confirming the collateral addition.
* - Failure: Returns an error message with the appropriate HTTP status code.
*
* Workflow:
* 1. Parse and validate the input parameters (`userId`, `symbol`, `amount`).
* 2. Check that the user exists and has sufficient balance for the token.
* 3. Deduct the specified `amount` of `symbol` tokens from the user's wallet.
* 4. Add the deducted tokens to the user's collateral in the lending protocol.
* 5. Return a success message confirming the operation.
*
* Example Request:
* ```json
* {
* "userId": "user1",
* "symbol": "DEFI",
* "amount": 500
* }
* ```
*
* Example Response (Success):
* ```json
* {
* "statusCode": 200,
* "body": "Added 500 of token DEFI as collateral for user1."
* }
* ```
*
* Example Response (Error: Invalid Input):
* ```json
* {
* "statusCode": 400,
* "body": "Invalid input parameters"
* }
* ```
*
* Example Response (Error: Insufficient Balance):
* ```json
* {
* "statusCode": 400,
* "body": "Insufficient token balance for collateral addition."
* }
* ```
*/
export function addCollateralEndpoint(request: ccfapp.Request): ccfapp.Response {
let body;
try {
body = request.body.json();
} catch {
return { statusCode: 400, body: "Invalid request body" };
}

const { userId, symbol, amount } = body;

// Validate input parameters
if (!userId || !symbol || amount <= 0) {
return { statusCode: 400, body: "Invalid input parameters" };
}

try {
// Add tokens directly to collateral
const collateralResult = addCollateral(userId, symbol, amount);

return { statusCode: 200, body: collateralResult };
} catch (error) {
return handleError(error);
}
}

/**
* Handles borrowing tokens against collateral in the lending protocol.
*
* This endpoint validates the user's collateral and borrowing capacity
* before crediting the borrowed tokens to their wallet. The borrow
* operation deducts the borrowed amount from the protocol's liquidity
* pool and increases the user's debt balance.
*
* Input:
* - `userId` (string): The unique identifier of the user making the request.
* - `borrowAmount` (number): The amount of the token to borrow.
* - `baseTokenSymbol` (string): The symbol of the token to borrow (e.g., "BTC").
*
* Output:
* - Success: Returns a success message confirming the borrowed amount.
* - Failure: Returns an error message with the appropriate HTTP status code.
*
* Workflow:
* 1. Validates input parameters (`userId`, `borrowAmount`, `baseTokenSymbol`).
* 2. Calls the `borrow` method in the lending module to:
* - Verify collateral sufficiency.
* - Deduct the borrowed tokens from the liquidity pool.
* - Increase the user's debt.
* - Credit the borrowed tokens to the user's wallet.
* 3. Returns a response with the result of the borrowing operation.
*
*
* Example Request:
* ```json
* {
* "userId": "user1",
* "borrowAmount": 150,
* "baseTokenSymbol": "BTC"
* }
* ```
*
* Example Response:
* ```json
* {
* "statusCode": 200,
* "body": "Borrowed 150 of token BTC against collateral."
* }
* ```
*/
export function borrowEndpoint(request: ccfapp.Request): ccfapp.Response {
let body;
try {
body = request.body.json();
} catch {
return { statusCode: 400, body: "Invalid request body" };
}

const { userId, borrowAmount, baseTokenSymbol } = body;

// Validate input parameters
if (!userId || !baseTokenSymbol || borrowAmount <= 0) {
return { statusCode: 400, body: "Invalid input parameters" };
}

try {
// Attempt to borrow tokens using the lending logic
const result = borrow(userId, borrowAmount, baseTokenSymbol);

return { statusCode: 200, body: result };
} catch (error) {
return handleError(error);
}
}
Loading