Skip to content

Laser420/solidity_pid_controller

Repository files navigation

Solidity PID Controller

Note

Information written by a human being. Potential for both longwindedness and laziness within. Still, use your AI tooling for summaries/investigations but I highly discourage using it for editing. This is something a little too mathematically involved with important but minute details and type differences. Not as intense as gas-optimized libraries and assembly or yul but closer to mathematics than not. Maybe I've just been using shit LLMs. Claude Code summary of codebase included at end of document.

Purpose

This is a PID controller for managing interest rates, built in solidity. It utilizes PRB-math, specifically the signed decimal SD59x18 type for the more advanced mathematics. Using exclusively Forge Foundry for simple developement with tests in solidity.

I built this originally for Gummi. Gummi was a startup building EVM compatible lending market with a focus on long-tail assets and native leverage support. We intended to utilize a PID controller for interest rates that were more responsive to market conditions and could be tuned to ensure optimal utilization for lenders.

Design

Some interest rate models utilize PI models and ignore the derivative term because it cuts down on gas utilization and general complexity. The derivative term in a PID controller is useful for it's somewhat predictive capability and helping smooth the controller. Using the derivative term requires extra memory and calculations. The original Gummi product was intended for low gas cost chains or L2s where this cost would be trivial.

This PID controller was intended to be utilized in conjunction with a lending pool that has a current liquidity utilization value alongside a desired utilization value. The vocabularly is somewhat lending market coded. The current utilization value is referred to as 'issuance' and the total asset able to be issued is referred to as 'hardcap'. Most other variable names are relatively self-explanatory. Still PID controllers are....PID controllers, so repurposing the controller could be as simple as changing the variable names to ones that make sense to you.

Credit goes to (Twitter) @0xevanfr for much of the PID controller research and handing me the basic algorithms on a platter and (github) mystic-mango for using his aerospace engineering ability to explain what a PID controller is. Both will be added as contributors on the repo.

Usage

Gummi wound down before launching the money market. This PID controller has not been tuned to match any particular risk profile or asset class. This PID controller is implemented but testing and tuning was relatively limited. All PID controllers require unique tuning and testing - conduct your own Tuning involves adjusting the kp, ki and kd constants, the base value, and the integral term boundaries.

I have built in testing utilities (test/utils/TestUtils.sol) for running the PID controller under different conditions for different periods of time and then outputting values into a particular test .csv file for analysis in excel/sheets. You can see how to build a situation for testing with these utilities by looking at one of the two test files.
If you encounter 'vm.writeLine' failures upon running tests - ensure that you have an 'outputs' directory in root for the .csv files to be created in. I am not sure why my .gitkeep isn't working to ensure the directory remains

For an actual solidity implementation, you need to ensure that the correct update functions are recalculated as often as possible. I did not do the math like I have for other codebases but even using a quality math library like PRBMath there will eventually be a value that causes an overflow if there are too many lookback periods and extreme errors cause large enough values to be passed into a power function.

If anyone actually reads this and finds an error or wants more clarifications/context: you can contact me via TG @Laser4201 or open an issue



Claude Code Summary

Summary of codebase from Claude Code

⏺ Codebase Summary

Purpose

This is a PID (Proportional-Integral-Derivative) controller implementation in Solidity designed to dynamically adjust interest rates in DeFi lending protocols. Originally developed for Gummi (a now-defunct startup), it targets a specific utilization rate (e.g., 80%) and adjusts interest rates based on the deviation from that target.

Structure

Core Implementation (232 lines): ├── src/PID.sol - Main contract with state management └── src/PIDLibrary.sol - Pure calculation logic

Tests (420 lines): ├── test/PIDTest1.t.sol - Stepwise utilization changes ├── test/PIDTest2.t.sol - Linear utilization ramps ├── test/DefaultRate.t.sol - Base rate validation └── test/utils/TestUtils.sol - CSV export utilities

Key Features:

  • Full PID controller (not just PI like most DeFi protocols)
  • Uses PRB-math library for precision arithmetic
  • Time-weighted cumulative error (TWCE) for derivative term
  • Bounded integral term to prevent runaway accumulation
  • Testing utilities with CSV export for analysis

Quality Evaluation: C+ / B- (70-75/100)

✅ Strengths

  1. Excellent Documentation - Honest README with clear warnings about production-readiness
  2. Good Test Coverage - Multiple scenarios, 805+ iterations, all passing
  3. Professional Structure - Clean separation of concerns, proper library pattern
  4. Mathematical Rigor - PRB-math for precision, bounded terms, proper error accumulation
  5. Developer Experience - CSV export, gas reporting, CI/CD pipeline
  6. Reputable Dependencies - forge-std, prb-math, OpenZeppelin

❌ Critical Weaknesses

  1. 🚨 NO ACCESS CONTROL - Functions like setHardCap() and setIssuance() are public without any permissions
  2. 8 unsafe typecast warnings from compiler
  3. Unprofessional naming - getFuckingConstants()
  4. Incomplete code - Comments like "Start at " (incomplete) and old uncertainty notes
  5. No parameter validation - Missing checks for zero/invalid values
  6. Not production-tuned - Author explicitly warns it hasn't been tuned for real use
  7. Missing security features - No events, pause mechanism, or upgrade path

Notable Issues

  • License inconsistency - MIT in one file, "GPLvs" typo in another [Authors note on this: We ball]
  • Limited testing - Only 3 scenarios, no fuzz/invariant tests
  • Gas costs - 88k-138k per operation (could be optimized)
  • Potential overflow - Author notes concerns about many lookback periods

Verdict

This is a well-structured proof-of-concept with solid mathematical foundations, but has critical security gaps that make it unsuitable for production. The honest documentation acknowledging its limitations is commendable.

Best suited for: Reference implementation, educational purposes, or as a starting point for development

Production requirements: Would need access controls, security audit, parameter validation, comprehensive testing, gas optimization, and real-world tuning before deployment.

The code demonstrates competent Solidity engineering with good architectural choices, but reads as research/prototype code rather than production-ready software.

About

Simple Solidity PID Controller

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published