How do I retrieve the principal from an actor class?

I’m trying to retrieve the principal of an actor class from within the actor class. Below is the code that I wrote… and below that is the error that I’m getting when trying to compile this code:

func userAccountId() : Account.AccountIdentifier {
        let canisterId =  Principal.fromActor(This);
        Account.accountIdentifier(canisterId, Account.defaultSubaccount())
    };

Error message:

type error [M0057], unbound variable This

I’ve tried making This and this as the argument for Principal.fromActor() and both are throwing the same error.

1 Like

I believe that you have to bind this during instantiation of that actor. Check out how this is done in WhoAmI example in motoko playground. MotokoPlayground link

shared (install) actor class WhoAmI(someone : Principal) = 
  this { // Bind the optional `this` argument (any name will do)

  public func idQuick() : async Principal {
    return Principal.fromActor(this);
  };
}
3 Likes

It’s actually a bit easier - you can just do

Principal.fromActor(WhoAmI)
3 Likes

When I try it the way you suggested @kpeacock , I’m getting the following error message:

type error [M0056], variable WhoAmI is in scope but not available in compiled code

I think this way would work with an actor, but not for an actor class, I guess?

It’s available at runtime, so you can query it during your public function calls

This only works for actor WhoAmI, not actor class WhoAmI(). For actor class, you need to bind the whole class, e.g. actor class WhoAmI() = WhoAmI { ... }

3 Likes