backendmotokodfinity

Candid UI not showing shared query method in Motoko


I'm building a simple Internet Computer dapp using Motoko and DFX version 0.28.0. My backend canister (dbank_backend) contains a checkBalance function defined as a public shared query:

import Debug "mo:base/Debug";
import Nat "mo:base/Nat";

actor DBank {
  var currentValue: Nat = 300;


  public func topUp(amount: Nat): async Nat {
    currentValue += amount;
    Debug.print("topUp called, currentValue = " #Nat.toText(currentValue));
    return currentValue;
  };

  public func withdraw(amount: Nat): async Nat{
    let tempVal: Int = currentValue - amount;
    if(tempVal>=0){
      currentValue -= amount;
    Debug.print("currentValue = " #Nat.toText(currentValue));
    return currentValue;
    } else {
      Debug.print("Balance too low for withdrawal");
      return currentValue;
    }
  };

  public shared query func checkBalance(): async Nat{
    return currentValue;
  };
}

Even though checkBalance is declared as a public shared query, it does not show up in the Candid UI I also tried calling it manually:

dfx canister call dbank_backend checkBalance --query

And I get:

Error: The replica returned a rejection error:
Canister has no query method 'checkBalance'

What I’ve tried:

dfx canister metadata dbank_backend candid:service

Still, checkBalance doesn't appear in the UI or respond to CLI calls.


Solution

  • The issue with the checkBalance function not appearing in the Candid UI or responding to CLI calls is likely due to its incorrect declaration using async in a shared query function, which isn't necessary and can cause it to be excluded from the generated interface. To fix this, change the method signature to public shared query func checkBalance(): Nat (removing async), then stop the DFX server, delete the .dfx folder, and restart everything cleanly using dfx stop, rm -rf .dfx, dfx start --clean, and dfx deploy. After redeploying, the method should appear in the Candid UI and respond properly to dfx canister call commands.