> For the complete documentation index, see [llms.txt](https://pencil-finance.gitbook.io/pencilfinancedocs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pencil-finance.gitbook.io/pencilfinancedocs/smart-contract-architecture.md).

# Smart Contract Architecture

Pencil Finance is built with modular, secure, and upgradeable smart contracts to manage decentralized investment, token issuance, repayment, and interest distribution within student loan bundles. Below is a breakdown of the core contract system.

### **📦 BundleManager Contract**

**Purpose**: Handles creation and configuration of loan bundles by lending partners.

#### **Functions:**

* createBundle(...): Initializes a new bundle with parameters (loan amount, tranche ratios, interest rates, lock-up period).
* updateBundleMetadata(...): Allows lending company to update documents, announcements.
* setStatus(...): Changes bundle status (e.g., Upcoming → Raising → Sold Out→ Staking → Redemption).
* uploadReport(...): Uploads repayment or performance updates for investors.

### **💰 SeniorPool Contract**

**Purpose**: Manages deposits and redemptions for **Senior Tranche (Grow Token)** investors.

#### **Functions:**

* deposit(amount): Accepts USDC, mints Grow Tokens.
* redeem(tokenAmount): Burns Grow Tokens and returns USDC, subject to withdrawal logic.
* queueWithdrawal(amount): Enters a withdrawal queue if liquidity is locked.
* processWithdrawalQueue(): Automatically fulfills withdrawals when capital is available.
* calculateInterest(...): Computes interest at maturity based on bundle terms.

### **🧩 JuniorPool Contract**

**Purpose**: Manages capital raised through **Junior Tranche (NFT)**.

#### **Functions:**

* mintNFT(investor, amount, rate): Mints an ERC-721 NFT representing ownership in the Junior Pool.
* claimInterest(nftId): Withdraws available interest tied to the NFT.
* redeemNFT(nftId): Withdraws final interest + principal at maturity.
* calculateShare(nftId): Calculates proportional ownership and payouts for NFT holders.

### **🔁 RepaymentVault Contract （MVP: no defaults）**

**Purpose**: Handles fund flows from lending companies and allocates repayments to tranches.

#### **Functions:**

* depositRepayment(bundleId, amount): Lending company repays capital + interest into the vault.
* allocateFunds(): Automatically distributes funds across Senior/Junior pools based on:
  * Repayment ratio
  * Outstanding principal
  * Priority rules (e.g., first pay Senior interest, then Junior)
* markOverdue(bundleId, amount): Tracks overdue loans if repayment is delayed.

### **🧠 Governance Contract - PEN DAO (Pending)**

**Purpose**: Enables decentralized protocol governance using the PEN token.

#### **Functions:**

* propose(change): Create a new governance proposal.
* vote(proposalId, support): Cast votes using PEN tokens.
* execute(proposalId): Executes passed governance changes (e.g., fee updates, emission adjustments).
* delegate(address): Delegate voting power to another wallet.

### **🔒 AccessControl & Security Modules (Pending)**

**Modules & Patterns**:

* **Role-based permissions** for lending companies, DAO, and protocol operators.
* **OpenZeppelin libraries** for ERC-20, ERC-721, SafeMath, Pausable, and Ownable.
* **Upgradable Proxies** via UUPS pattern (if needed for flexibility).
* **Auditing hooks** and **emergency pause** functions to manage platform risk.

### **🛡️ Security & Best Practices (Pending)**

* **External audits** before mainnet deployment.
* **Formal verification** of interest calculations, queue processing.
* **Testnet simulations** for bundle lifecycle and edge cases (e.g., partial repayments, investor overflows).
* **Bug bounty program** planned at mainnet launch to incentivize white-hat contributions.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://pencil-finance.gitbook.io/pencilfinancedocs/smart-contract-architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
