How to get current timestamp()? Bug, timestamp not accurate

Currently from my test cases, the timestamp() is always the same value:

#[test]
 fn foo() {
     let current_timestamp = timestamp();
     log(current_timestamp);
 }

The output is always the same after running it at different timings.

Decoded log value: 4611686018427387924, log rb: 1515152261580153489

To get the current timestamp, I also tried and deployed the contract to a testnet, but the output value remains the same 4611686020155001000.
Update: It does changes but only after several minutes, it returns the value but only after every 17 minutes. The second call returned 4611686020155002000.

To get the same contract, here is the link to sway playground:

contract;
use std::block::timestamp;
use standards::src5::{AccessError, SRC5, State};
use standards::src20::SRC20;
use standards::src3::SRC3;


 
abi MyContract {
    fn test_function() -> u64;

}   
 
impl MyContract for Contract {
    fn test_function() -> u64 {
        let time = timestamp();
        time
    }
}

hey @eesheng, the behaviour you’re experiencing with the timestamp() function is expected. The timestamp() function returns the block timestamp, which only updates when a new block is mined. This means the timestamp will remain the same until a new block is produced, which can take several minutes depending on the network’s block time. However, if you need more precise timing within the constraints of the blockchain, you can try using an oracle or an off-chain service to fetch the precise time and then send it to your contract.

Or, another approach would be combine the block timestamp with the block height to get a more granular sense of time progression. This won’t give you a more precise timestamp but can help you understand the relative time between blocks i.e. you can do something like this

impl MyContract for Contract {
    fn get_precise_time() -> (u64, u64) {
        let time = timestamp();
        let block_height = height();
        (time, block_height)
    }
}

You can refer to our example for more details

1 Like

How long does it take to mine a block? Every second on the mainnet? If so, why deploying the contract and calling timestamp(), on swayplayground seems to not update but only after 17 minutes?