{"id":50496187,"url":"https://github.com/davidweb3-ctrl/rebase-token-demo","last_synced_at":"2026-06-02T07:03:59.884Z","repository":{"id":320988010,"uuid":"1083987208","full_name":"davidweb3-ctrl/rebase-token-demo","owner":"davidweb3-ctrl","description":"Implement a deflationary ERC20 Token to learn the principles and implementation mechanisms of rebase-type deflationary tokens.","archived":false,"fork":false,"pushed_at":"2025-10-27T04:53:01.000Z","size":13,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-27T06:25:05.671Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Solidity","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/davidweb3-ctrl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-27T03:53:39.000Z","updated_at":"2025-10-27T04:53:04.000Z","dependencies_parsed_at":"2025-10-27T06:25:10.293Z","dependency_job_id":null,"html_url":"https://github.com/davidweb3-ctrl/rebase-token-demo","commit_stats":null,"previous_names":["davidweb3-ctrl/rebase-token-demo"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/davidweb3-ctrl/rebase-token-demo","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidweb3-ctrl%2Frebase-token-demo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidweb3-ctrl%2Frebase-token-demo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidweb3-ctrl%2Frebase-token-demo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidweb3-ctrl%2Frebase-token-demo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davidweb3-ctrl","download_url":"https://codeload.github.com/davidweb3-ctrl/rebase-token-demo/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidweb3-ctrl%2Frebase-token-demo/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33810345,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-02T02:00:07.132Z","response_time":109,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-02T07:03:58.624Z","updated_at":"2026-06-02T07:03:59.873Z","avatar_url":"https://github.com/davidweb3-ctrl.png","language":"Solidity","funding_links":[],"categories":[],"sub_categories":[],"readme":"# RebaseToken Demo\n\nA Foundry project implementing a **deflationary ERC20 token** using a **scaling factor design** for rebase mechanics. This token automatically reduces the total supply over time through owner-controlled rebase operations, creating deflationary pressure.\n\n## 🎯 Project Purpose\n\nThis project demonstrates how to implement a rebase-type deflationary token that:\n- Maintains ERC20 compatibility for seamless DeFi integration\n- Uses internal shares and a global scaling factor for efficient rebasing\n- Provides owner-controlled deflationary mechanics\n- Handles rounding and precision correctly\n- Optimizes gas usage through share-based storage\n\n## 🏗️ Design Overview\n\n### Scaling Factor Mechanism\n\nThe RebaseToken uses a **scaling factor design** where:\n\n- **Internal Storage**: Balances are stored as `rawShares` (not direct token amounts)\n- **Global Index**: A scaling factor `index` (starts at `BASE = 1e18`)\n- **Balance Calculation**: `balanceOf(account) = rawShares[account] * index / BASE`\n- **Transfer Logic**: Converts amounts to shares: `shares = amount * BASE / index`\n\n### Rebase Mechanism\n\n- **Owner Control**: Only the contract owner can trigger rebases\n- **Deflationary**: Each rebase reduces the index by 1% (`newIndex = oldIndex * 99 / 100`)\n- **Event Emission**: Emits `Rebase(oldIndex, newIndex, block.timestamp)`\n- **Safety**: Minimum index threshold prevents precision issues\n\n### Key Benefits\n\n1. **Gas Efficient**: Share-based storage minimizes state changes\n2. **Precision Safe**: Proper rounding and minimum threshold protection\n3. **ERC20 Compatible**: Works with all existing DeFi protocols\n4. **Deflationary**: Automatic supply reduction creates scarcity\n5. **Owner Controlled**: Secure rebase mechanism with proper access control\n\n## 🚀 Getting Started\n\n### Prerequisites\n\n- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed\n- Git for version control\n\n### Installation\n\n```bash\n# Clone the repository\ngit clone \u003crepository-url\u003e\ncd rebase-token-demo\n\n# Install dependencies\nforge install\n```\n\n### Build and Test\n\n```bash\n# Build the project\nforge build\n\n# Run all tests\nforge test\n\n# Run tests with gas reporting\nforge test --gas-report\n\n# Run specific test with verbose output\nforge test --match-test \"testSingleRebase\" -vvv\n```\n\n## 📊 Example Results\n\n### Initial State\n\n```solidity\n// Contract deployment with 1,000,000 tokens\nInitial Supply: 1,000,000.000000000000000000 tokens\nInitial Index: 1.000000000000000000 (BASE = 1e18)\nOwner Balance: 1,000,000.000000000000000000 tokens\n```\n\n### After 1 Rebase (1% reduction)\n\n```solidity\n// After calling rebase() once\nNew Index: 0.990000000000000000 (99% of original)\nTotal Supply: 990,000.000000000000000000 tokens\nOwner Balance: 990,000.000000000000000000 tokens\nReduction: 10,000.000000000000000000 tokens (1%)\n```\n\n### After 3 Rebases (3% total reduction)\n\n```solidity\n// After calling rebase() three times\nNew Index: 0.970299000000000000 (99% × 99% × 99%)\nTotal Supply: 970,299.000000000000000000 tokens\nOwner Balance: 970,299.000000000000000000 tokens\nReduction: 29,701.000000000000000000 tokens (2.9701%)\n```\n\n### Transfer + Rebase Example\n\n```solidity\n// Initial state\nOwner Balance: 1,000,000 tokens\nAlice Balance: 0 tokens\n\n// Transfer 100,000 tokens to Alice\ntoken.transfer(alice, 100000 * 1e18);\nOwner Balance: 900,000 tokens\nAlice Balance: 100,000 tokens\n\n// Perform rebase (1% reduction)\ntoken.rebase();\nOwner Balance: 891,000 tokens (900,000 × 0.99)\nAlice Balance: 99,000 tokens (100,000 × 0.99)\nTotal Supply: 990,000 tokens\n```\n\n## 🔧 How to Reproduce Results Locally\n\n### Step 1: Clone and Setup\n\n```bash\ngit clone \u003crepository-url\u003e\ncd rebase-token-demo\nforge install\nforge build\n```\n\n### Step 2: Run Tests to Verify\n\n```bash\n# Run all tests to ensure everything works\nforge test\n\n# Run specific tests for rebase functionality\nforge test --match-test \"testSingleRebase|testMultipleRebase\"\n```\n\n### Step 3: Deploy and Interact (Optional)\n\n```bash\n# Deploy to local testnet\nforge script script/Deploy.s.sol --rpc-url http://localhost:8545 --private-key \u003cPRIVATE_KEY\u003e\n\n# Or deploy to a testnet\nforge script script/Deploy.s.sol --rpc-url \u003cRPC_URL\u003e --private-key \u003cPRIVATE_KEY\u003e --broadcast\n```\n\n### Step 4: Manual Testing\n\nYou can also interact with the contract manually:\n\n```solidity\n// Deploy the contract\nRebaseToken token = new RebaseToken(\"RebaseToken\", \"RBT\", 18, 1000000 * 1e18);\n\n// Check initial state\nconsole.log(\"Initial Supply:\", token.totalSupply());\nconsole.log(\"Initial Index:\", token.getIndex());\n\n// Perform rebase\ntoken.rebase();\n\n// Check after rebase\nconsole.log(\"Supply after rebase:\", token.totalSupply());\nconsole.log(\"Index after rebase:\", token.getIndex());\n```\n\n## 📁 Project Structure\n\n```\n├── foundry.toml           # Foundry configuration\n├── lib/                   # Dependencies (forge-std)\n├── script/                # Deployment scripts\n├── src/                   # Source files\n│   └── RebaseToken.sol   # Main contract implementation\n├── test/                  # Test files\n│   └── RebaseToken.t.sol # Comprehensive test suite\n└── README.md             # This file\n```\n\n## 🧪 Test Coverage\n\nThe test suite includes **18 comprehensive tests** covering:\n\n- ✅ **Initialization**: Constructor parameters and initial state\n- ✅ **Single Rebase**: 1% reduction with event emission\n- ✅ **Transfer + Rebase**: Proper scaling after transfers\n- ✅ **Multiple Rebases**: 3 consecutive rebases with consistency\n- ✅ **Rounding Edge Cases**: 1 wei transfers and precision handling\n- ✅ **Permission Control**: Owner-only rebase functionality\n- ✅ **Supply Consistency**: Total supply vs sum of balances\n\n### Running Specific Tests\n\n```bash\n# Test initialization\nforge test --match-test \"testInitialization\"\n\n# Test rebase functionality\nforge test --match-test \"testSingleRebase|testMultipleRebase\"\n\n# Test rounding edge cases\nforge test --match-test \"testRoundingEdgeCase1Wei\"\n\n# Test permission control\nforge test --match-test \"testRebaseOnlyOwner\"\n```\n\n### Sample Test Output\n\n```bash\n$ forge test --gas-report\n\nRan 18 tests for test/RebaseToken.t.sol:RebaseTokenTest\n[PASS] testIndexMinimumThreshold() (gas: 21306678)\n[PASS] testInitialSupplyConsistency() (gas: 39004)\n[PASS] testInitialization() (gas: 97137)\n[PASS] testMultipleRebase() (gas: 156676)\n[PASS] testMultipleRebaseWithTransfers() (gas: 289838)\n[PASS] testRebaseFromOwner() (gas: 46086)\n[PASS] testRebaseOnlyOwner() (gas: 44444)\n[PASS] testRoundingEdgeCase1Wei() (gas: 186859)\n[PASS] testRoundingPrecision() (gas: 127331)\n[PASS] testRoundingWithSmallAmounts() (gas: 124313)\n[PASS] testSingleRebase() (gas: 111022)\n[PASS] testSingleRebaseSupplyConsistency() (gas: 67682)\n[PASS] testSupplyConsistencyAfterComplexOperations() (gas: 409056)\n[PASS] testTransferAfterRebase() (gas: 160361)\n[PASS] testTransferBeforeRebase() (gas: 119893)\n[PASS] testTransferFromAfterRebase() (gas: 223324)\n[PASS] testTransferOwnership() (gas: 103061)\n[PASS] testTransferOwnershipToZeroAddress() (gas: 32019)\nSuite result: ok. 18 passed; 0 failed; 0 skipped; finished in 8.06ms (13.08ms CPU time)\n\n╭------------------------------------------+-----------------+-------+--------+-------+---------╮\n| src/RebaseToken.sol:RebaseToken Contract |                 |       |        |       |         |\n+===============================================================================================+\n| Deployment Cost                          | Deployment Size |       |        |       |         |\n|------------------------------------------+-----------------+-------+--------+-------+---------|\n| 931370                                   | 4566            |       |        |       |         |\n|------------------------------------------+-----------------+-------+--------+-------+---------|\n| Function Name                            | Min             | Avg   | Median | Max   | # Calls |\n|------------------------------------------+-----------------+-------+--------+-------+---------|\n| rebase                                   | 23544           | 30237 | 30263  | 30263 | 708     |\n| transfer                                 | 54203           | 54264 | 54275  | 54287 | 9       |\n| balanceOf                                | 4848            | 4848  | 4848   | 4848  | 44      |\n| totalSupply                              | 4662            | 4662  | 4662   | 4662  | 23      |\n╰------------------------------------------+-----------------+-------+--------+-------+---------╯\n\nRan 1 test suite in 12.86ms (8.06ms CPU time): 18 tests passed, 0 failed, 0 skipped (18 total tests)\n```\n\n## ⚡ Gas Optimization\n\nThe contract is optimized for gas efficiency:\n\n- **Deployment**: ~931k gas\n- **Rebase Operation**: ~30k gas\n- **Transfer**: ~54k gas\n- **Balance Query**: ~4.8k gas\n\n## 🔒 Security Features\n\n- **Owner Control**: Only contract owner can perform rebases\n- **Minimum Index**: Prevents index from going too low (precision protection)\n- **Zero Address Checks**: All transfer and approval functions\n- **Balance Validation**: Ensures sufficient funds before transfers\n- **Proper Rounding**: Handles division operations correctly\n\n## 📚 Technical Details\n\n### Contract Functions\n\n```solidity\n// Core ERC20 Functions\nfunction balanceOf(address account) external view returns (uint256)\nfunction transfer(address to, uint256 amount) external returns (bool)\nfunction transferFrom(address from, address to, uint256 amount) external returns (bool)\nfunction approve(address spender, uint256 amount) external returns (bool)\nfunction totalSupply() external view returns (uint256)\n\n// Rebase Functions\nfunction rebase() external onlyOwner\nfunction getIndex() external view returns (uint256)\nfunction getRawShares(address account) external view returns (uint256)\n\n// Owner Functions\nfunction transferOwnership(address newOwner) external onlyOwner\n```\n\n### Events\n\n```solidity\nevent Transfer(address indexed from, address indexed to, uint256 value);\nevent Approval(address indexed owner, address indexed spender, uint256 value);\nevent Rebase(uint256 oldIndex, uint256 newIndex, uint256 timestamp);\n```\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests for new functionality\n5. Ensure all tests pass\n6. Submit a pull request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## 🔗 References\n\n- [Foundry Book](https://book.getfoundry.sh/)\n- [ERC20 Standard](https://eips.ethereum.org/EIPS/eip-20)\n- [Rebase Token Patterns](https://github.com/ampleforth/token-geyser)\n\n---\n\n**Note**: This is a demonstration project. For production use, consider additional security audits, access control mechanisms, and economic modeling for the rebase parameters.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidweb3-ctrl%2Frebase-token-demo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavidweb3-ctrl%2Frebase-token-demo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidweb3-ctrl%2Frebase-token-demo/lists"}