RareSkills Solidity Interview Question #31 Answered: What is variable and fixed interest rate?

Faybian Byrd
Coinmonks
4 min readFeb 26, 2024

--

This series will provide answers to the list of Solidity interview questions that were published by RareSkills..

Question #31 (Easy): What is variable and fixed interest rate?

Answer: Variable interest rate is a rate that is variable, or liable to change, throughout the duration of the term. Fixed interest rate is a rate that is constant, or not subject to change, throughout the duration of term. A variable interest rate can increase or decrease depending on variable determining factors.

Demonstration:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

contract TimeBasedVariableRateContract {
// Declare a constant for the fixed interest rate (5%)
uint256 public constant FIXED_RATE = 5;
// Initial variable interest rate set to 10%
uint256 public initialVariableRate = 10;
// Rate of decay for the variable interest rate, 1% per second for
// demonstration
uint256 public rateDecayPerSecond = 1;
// Timestamp of the last time the variable rate was updated
uint256 public lastUpdateTime;
address public owner;

// Structure to hold information about a deposit
struct Deposit {
uint256 amount;
// Timestamp when the deposit was made
uint256 timestamp;
// True if the deposit uses a fixed interest rate, false for variable
// rate
bool isFixedRate;
}

// Mapping from user address to their deposit information
mapping(address user => Deposit) public deposits;

// Constructor sets initial values for state variables
constructor() payable {
owner = msg.sender;
lastUpdateTime = block.timestamp;
}

// Function allowing users to make a deposit and choose their interest rate
// type
function deposit(bool _isFixedRate) external payable {
require(msg.value > 0, "Deposit amount must be greater than 0");

deposits[msg.sender] =
Deposit(msg.value, block.timestamp, _isFixedRate);
}

// Function to calculate the current variable interest rate based on time
// passed since the last update
function getCurrentVariableRate() public view returns (uint256) {
// Calculate the time elapsed since the last update
uint256 timeElapsed = block.timestamp - lastUpdateTime;
// Calculate how much the rate has decayed based on time elapsed
// Decay rate adjustment for demonstration, changing per minute
uint256 decay = rateDecayPerSecond * (timeElapsed / 1 minutes);
// Ensure the rate never goes below 1%
uint256 currentRate = initialVariableRate > decay
? initialVariableRate - decay
: 1;

return currentRate;
}

// Function to calculate the interest earned on a deposit
function calculateInterest(address _user) public view returns (uint256) {
// Retrieve the user's deposit information
Deposit memory userDeposit = deposits[_user];
// Determine the interest rate to use
uint256 rate = userDeposit.isFixedRate
? FIXED_RATE
: getCurrentVariableRate();
// Calculate time elapsed since the deposit was made
uint256 timeElapsed = block.timestamp - userDeposit.timestamp;
// Calculate interest using a simplified formula:
// (amount * rate * time) / (100 * 365 * 24 * 60 * 60)
// for yearly interest
uint256 interest = (userDeposit.amount * rate * timeElapsed)
/ (100 * 365 * 24 * 60 * 60);

return interest;
}

// Function to withdraw the deposit and any earned interest
function withdraw() external {
// Retrieve the caller's deposit information
Deposit storage userDeposit = deposits[msg.sender];
require(userDeposit.amount > 0, "No funds to withdraw");

// Calculate the interest earned
uint256 interest = calculateInterest(msg.sender);
// Total amount includes the initial deposit plus earned interest
uint256 totalAmount = userDeposit.amount + interest;
// Reset the user's deposit amount to prevent re-entrancy attacks
userDeposit.amount = 0;

// Attempt to send the total amount to the user, checking for success
(bool sent, ) = msg.sender.call{value: totalAmount}("");

require(sent, "Failed to withdraw user funds");
}
}

Further Discussion:

When performing math operations in Solidity, such as interest rate calculations, it may be beneficial to use fixed-point mathematics in order to preserve precision and avoid precision loss.

Some popular fixed-point mathematics libraries are PRBMath, ABDKMath64x64 and DSMath.

Connect with me:

Previous articles:

Disclosure: Some content may have been generated with the help of artificial intelligence.

--

--

Faybian Byrd
Coinmonks

Senior Software Engineer, Full Stack/Frontend @Synapse Labs | Graduate - Advanced Solidity Bootcamp @ RareSkills. | Certified Solidity Developer (CSD)