leojail
leojail

Reputation: 359

How can I convert the block number into the Integer type in substrate module?

I'm testing the substrate off-chain worker, what I want to do is receive the current block number, and then do some calculation, just like the below code if (get_block / 10 == 0), and I get some error. How can I convert the block number into the Integer type?

my code

use frame_support::{decl_storage, decl_module, dispatch::DispatchResult, debug};

use frame_system::{ensure_signed, offchain};

use sp_runtime::{
  offchain::http,
  transaction_validity::{
    TransactionValidity, TransactionLongevity, ValidTransaction, InvalidTransaction
  }
};

pub trait Trait: frame_system::Trait {}

decl_storage! {
    trait Store for Module<T: Trait> as Runtime_example {
        SubjectCount: u32;        
    }
}
decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        fn offchain_worker(block: T::BlockNumber){
            let get_block = block;
            if (get_block / 10 == 0) {  
               debug::info!("print !!!!!!!!!!!!!!!!");               
            }            
        }
    }
}

Error logs

error[E0308]: mismatched types
  --> /home/substrate-node-template/runtime/src/runtime_example.rs:32:29
   |
32 |             if (get_block / 10 == 0) {  
   |                             ^ expected associated type, found integer
   |
   = note: expected associated type `<T as frame_system::Trait>::BlockNumber`
                         found type `{integer}`
   = help: consider constraining the associated type `<T as frame_system::Trait>::BlockNumber` to `{integer}` or calling a method that returns `<T as frame_system::Trait>::BlockNumber`

error[E0308]: mismatched types
  --> /home/substrate-node-template/runtime/src/runtime_example.rs:32:34
   |
32 |             if (get_block / 10 == 0) {  
   |                                  ^ expected associated type, found integer
   |
   = note: expected associated type `<T as frame_system::Trait>::BlockNumber`
                         found type `{integer}`
   = help: consider constraining the associated type `<T as frame_system::Trait>::BlockNumber` to `{integer}` or calling a method that returns `<T as frame_system::Trait>::BlockNumber`

Upvotes: 3

Views: 1054

Answers (1)

Shawn Tabrizi
Shawn Tabrizi

Reputation: 12434

@kmdreko is right. You do not want to convert the block number to an integer, but convert the integer into a block number and then do the math.

So replace:

get_block / 10 == 0

With:

(get_block / 10.into()).is_zero()

Upvotes: 3

Related Questions