# 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.
