I wan't to get how long user has staked nft token in days. I recorded staking
time_stamp while staking and un_staking
time_stamp while un_staking. Now I wan't to calculate how many days user has staked for reward distribution based on days. How to do that?
1 Answer
Below is the general calculation for finding the days.
// Calculate the time difference between unstaking and staking timestamps.
let time_difference = unstaking_timestamp
.checked_sub(staking_timestamp)
.ok_or(DispatchError::from("Timestamp overflow"))?; // Modify error accordingly
// Convert the time difference to the number of days.
let days_staked: u64 = time_difference
.as_secs()
.checked_div(86400) // T::SECONDS_PER_DAY = 86400
.unwrap_or(0);
-
@Immanule John can you please check this code either it is correct or not to convert timestamp into days? github.com/Build3rs-Labs/foxies/blob/…– Ganesh11Jul 31 at 11:48
-
Yes it seems so. but it is also recommended to do proper error handling in your code. 1. The checked_sub method returns an Option indicating the result of the subtraction. If the subtraction results in an overflow, it will return None. In such a case, the subsequent operations will not produce meaningful results. 2.The usage of unwrap_or_default() ignores the potential errors or overflow scenarios. In some cases, it may lead to incorrect or unexpected behavior. Jul 31 at 15:46
-
hey @Immanuel John I try to implemented as per you say but when I try to convert time_difference
.as_secs()
as per you suggestion then it givesno method as_secs() found for type u64
. Here is code for just for calculating days, can you please review it once again. github_link– Ganesh11Aug 2 at 11:29