How get module hash in motoko?

I’d like to know how we get module hash in motoko. I tried to get module hash using management canister “aaaaa-aa”, but it always returned null.
This is my code.

import Principal "mo:base/Principal";
import Canister "./Canister";
import Cycles "mo:base/ExperimentalCycles";


actor class ModuleHash() = this {
    let IC0 = actor("aaaaa-aa") : 
      actor {
        canister_status : shared { canister_id : Principal } -> 
          async {
            module_hash : ?[Nat];
            status : { #stopped; #stopping; #running };
            cycles : Nat;
          };
      };
    stable var principal : Principal = Principal.fromText("aaaaa-aa");
    
    public func init() : async Principal {
      Cycles.add(200_000_000_000);
      let canister = await Canister.Canister();
      let amountAccepted = await canister.wallet_receive();
      principal := Principal.fromActor(canister);
      principal;
    };
    
    public func get(principal : Principal) : async (?[Nat], Nat, Principal) {
      let r = await IC0.canister_status({canister_id = principal});
      (r.module_hash,r.cycles, principal);
    };

    public func peek() : async Principal {
      principal;
    };
};
import Cycles "mo:base/ExperimentalCycles";
import Nat64 "mo:base/Nat64";

actor class Canister() = this {
  stable var capacity = 1000000000000000000;
  stable var balance = Cycles.balance();


  // Returns the cycles received up to the capacity allowed
  public func wallet_receive() : async { accepted: Nat64 } {
      let amount = Cycles.available();
      let limit : Nat = capacity - balance;
      let accepted = 
          if (amount <= limit) amount
          else limit;
      let deposit = Cycles.accept(accepted);
      assert (deposit == accepted);
      balance += accepted;
      { accepted = Nat64.fromNat(accepted) };
  };   
}

The caller has to be one of the controllers of the target canister in order to call canister_status. For simplicity, you can always add blackhole canster to the controller list of your target canister, and then call blackhole’s canister_status method instead.

Introduce the black hole to help with canister status lookup + make them immutable

4 Likes

yes, so the main canister create child canister and call it as controller.
The other fields return correctly(cycles, status…), but only the module hash is null.

You should have module_hash: ?[Nat8] instead of Nat.

2 Likes

Thank you!
It’s solved!

1 Like