Calculate Rate per Second
This guide explains how to calculate the rate per second when creating a Flow stream. It is the most important step in setting up a stream since the rate per second is a key parameter in the stream's configuration.
We assume that you have already gone through the Protocol Concepts and the Flow Overview sections.
The code in this guide is not production-ready, and is implemented in a simplistic manner for the purpose of learning.
The rate per second is the amount of tokens streamed in one second. It is represented as a fixed-point number with 18
decimals, specifically as a UD21x18 type from the PRBMath library. The underlying native Solidity type associated
with UD21x18 is uint128.
Depending on how you receive payments, you have to calculate the rate per second and scale its value to 18 decimals format as below:
- Based on a duration, e.g., 3 months
- Between two points in time, e.g., January 1, 2025 to April, 1 2025
The calculation method is the same in either case.
Set up a library
Declare the Solidity version used to compile the library:
loading...
Import the relevant symbols:
loading...
Declare a library that can be used in other contracts:
loading...
Calculate the rate per second on a duration
Define a function called ratePerSecondWithDuration that takes the following parameters and the returned value:
loading...
First, retrieve the token's decimals. Note that not all ERC-20 tokens use the 18-decimal standard.
loading...
If the token uses 18 decimals, simply divide the amount by the duration:
loading...
If the token has less than 18 decimals, calculate the scale factor from the token's decimals:
loading...
Then, multiply the amount by the scale factor and divide it by the duration:
loading...
Calculate the rate per second on timestamps
Here, there are two time parameters, a start and an end time, instead of a duration. Let's define the function:
loading...
The first step is to calculate the duration between the two timestamps:
loading...
The remaining logic is identical to the duration-based calculation:
loading...
Additional utilities
To calculate earnings for specific durations from an existing stream, you can use the following functions:
loading...
Full code
Below you can see the complete FlowUtilities library:
loading...