# 💰 Admin Fund Contract - Guide

## Masalah
Jika saldo KZD di smart contract habis, user tidak bisa withdraw meskipun balance di database masih ada.

## Solusi: Fund Contract Function

### Fungsi Baru: `fundContract(amount)`

**Smart Contract:**
```solidity
function fundContract(uint256 amount) external onlyOwner {
    require(amount > 0, "Amount must be greater than 0");
    require(kzdToken.transferFrom(msg.sender, address(this), amount), "Transfer failed");
    
    emit ContractFunded(msg.sender, amount, kzdToken.balanceOf(address(this)));
}
```

**Hanya Owner** yang bisa panggil fungsi ini.

---

## 📊 Cara Mengisi Saldo Contract

### Option 1: Via Hardhat Script (Recommended)

**File:** `scripts/fundContract.js`

```javascript
const { ethers } = require("hardhat");

async function main() {
    const [owner] = await ethers.getSigners();
    
    // Get contract addresses
    const TOKEN_ADDRESS = process.env.KZD_TOKEN_ADDRESS;
    const STAKING_ADDRESS = process.env.STAKING_CONTRACT_ADDRESS;
    
    console.log("Funding contract from:", owner.address);
    
    // Attach to contracts
    const Token = await ethers.getContractAt("KUZADESIGNToken", TOKEN_ADDRESS);
    const Staking = await ethers.getContractAt("KZDStaking", STAKING_ADDRESS);
    
    // Amount to fund (example: 10,000 KZD)
    const amount = ethers.parseEther("10000");
    
    console.log("Amount to fund:", ethers.formatEther(amount), "KZD");
    
    // Step 1: Check owner balance
    const ownerBalance = await Token.balanceOf(owner.address);
    console.log("Owner balance:", ethers.formatEther(ownerBalance), "KZD");
    
    if (ownerBalance < amount) {
        console.error("❌ Insufficient balance!");
        return;
    }
    
    // Step 2: Approve
    console.log("Approving...");
    const approveTx = await Token.approve(STAKING_ADDRESS, amount);
    await approveTx.wait();
    console.log("✅ Approved!");
    
    // Step 3: Fund contract
    console.log("Funding contract...");
    const fundTx = await Staking.fundContract(amount);
    await fundTx.wait();
    console.log("✅ Contract funded!");
    
    // Step 4: Check new balance
    const contractBalance = await Staking.getContractBalance();
    console.log("New contract balance:", ethers.formatEther(contractBalance), "KZD");
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });
```

**Run:**
```bash
npx hardhat run scripts/fundContract.js --network bsc_testnet
```

---

### Option 2: Via MetaMask (Manual)

1. **Buka BSCScan Contract:**
   - Testnet: `https://testnet.bscscan.com/address/STAKING_ADDRESS`
   - Mainnet: `https://bscscan.com/address/STAKING_ADDRESS`

2. **Connect Wallet** (Owner wallet)

3. **Approve KZD Token:**
   - Go to KZD Token contract
   - Call `approve(STAKING_ADDRESS, AMOUNT)`

4. **Call fundContract:**
   - Go to Staking contract
   - Call `fundContract(AMOUNT)`

---

## 💡 Best Practices

### 1. Monitor Contract Balance

**Script:** `scripts/checkContractBalance.js`
```javascript
const contractBalance = await Staking.getContractBalance();
const totalPendingWithdrawals = /* from database */;

if (contractBalance < totalPendingWithdrawals) {
    console.warn("⚠️ Low balance! Need to fund contract");
}
```

### 2. Auto Alert

Add ke admin dashboard:
```javascript
if (contractBalance < minThreshold) {
    // Send alert to admin
    // Email, Telegram, etc.
}
```

### 3. Emergency Fund

Keep emergency fund ready:
- 10-20% dari total staked amount
- Top up sebelum habis

---

## 📈 Skenario Penggunaan

### Skenario 1: Initial Setup
```
Total Staked: 100,000 KZD
Daily Rewards: 2,000 KZD/day
Recommendation: Fund 20,000 KZD (10 days buffer)
```

### Skenario 2: Low Balance Warning
```
Current Balance: 5,000 KZD
Pending Withdrawals: 4,500 KZD
Action: Fund 15,000 KZD immediately
```

### Skenario 3: Monthly Top-up
```
Monthly Rewards Distributed: 50,000 KZD
Fee Collected: 2,500 KZD
Net Outflow: 47,500 KZD
Action: Fund 50,000 KZD setiap bulan
```

---

## ⚠️ Important Notes

1. **Owner Only:** Hanya wallet owner yang bisa fund contract
2. **Approval Required:** Harus approve token dulu sebelum fund
3. **Balance Check:** Pastikan owner wallet punya cukup KZD
4. **Gas Fees:** Siapkan BNB untuk gas fees

---

## 🔍 Monitoring

### Check Contract Balance:
```javascript
await Staking.getContractBalance()
```

### Check Total Withdrawable (Database):
```javascript
const totalWithdrawable = dailyRewards + referralBonus + managerBonus
```

### Health Ratio:
```javascript
const healthRatio = contractBalance / totalWithdrawable
// Recommended: > 1.5 (150%)
```

---

## 📞 Emergency Contact

If contract runs out of balance:
1. ✅ **Users can still stake** (deposit to contract)
2. ❌ **Users CANNOT withdraw** until contract refunded
3. 🚨 **Fund immediately** to restore service

---

## Next Steps

1. **Deploy updated contract** (dengan fungsi fundContract)
2. **Create monitoring script**
3. **Setup alert system**
4. **Schedule regular top-ups**

**Contract update required!** Redeploy contract untuk enable fungsi ini.
