Skip to content
by Unity Nodes
Development

UntypedError when running methods in a Javascript FT smart contract

5 posts344 views9 likesLast activity Apr 2025

  1. iamenochchirimaOP 2

    I am a new to developing on NEAR and trying to create a FT smart contract, I haven’t learned Rust yet so I am using Javascript-Typescript but I am having this bug when I try to run some fucntion, the contract is deploying well, I can run init function well, but when I try to run other function that’s when I am getting the error below.

    Here is the code:

    import {
      NearBindgen,
      near,
      call,
      view,
      initialize,
      assert,
      AccountId,
    } from "near-sdk-js";
    
    
    interface TokenMetadata {
      name: string;
      symbol: string;
      decimals: number;
    }
    
    @NearBindgen({})
    class FungibleTokenContract {
      owner_id: string;
      total_supply: number;
      metadata:TokenMetadata;
      balances: Map<string, number>;
    
      constructor(owner_id: string, total_supply: number, metadata: TokenMetadata) {
        this.owner_id = owner_id;
        this.total_supply = total_supply;
        this.metadata = metadata;
        this.balances = new Map<string, number>();
      }
    
      @initialize({ privateFunction: true })
      init(owner_id: string, total_supply: number, metadata: TokenMetadata): void {
        this.owner_id = owner_id;
        this.total_supply = total_supply;
        this.metadata = metadata;
      }
    
      // Method to issue new tokens to a recipient
      @call({})
      issueTokens(recipient: string, amount: number): void {
        let caller_id = near.predecessorAccountId();
        assert(
          caller_id === this.owner_id,
          "Only the contract owner can issue tokens."
        );
    
        let recipientBalance = this.balances.get(recipient);
        this.balances.set(recipient, recipientBalance + amount);
        this.total_supply -= amount;
    
        near.log(
          `Issued ${amount} tokens to account: ${recipient}. Total supply: ${this.total_supply}`
        );
      }
    
      // Method to retrieve token metadata
      @view({})
      tokenMetadata(): any {
        return this.metadata;
      }
    
      // Method to transfer tokens from sender to recipient
      @call({})
      transferTokens(sender: string, recipient: string, amount: number): void {
        let senderBalance = this.balances.get(sender);
        assert(senderBalance >= amount, "Insufficient balance.");
    
        this.balances.set(sender, senderBalance - amount);
    
        let recipientBalance = this.balances.get(recipient);
        this.balances.set(recipient, recipientBalance + amount);
    
        near.log(`Transferred ${amount} tokens from ${sender} to ${recipient}.`);
      }
    
      // Method to distribute tokens as incentives/rewards
      @call({})
      distributeIncentives(account: string, amount: number): void {
        let caller_id = near.predecessorAccountId();
        assert(
          caller_id === this.owner_id,
          "Only the contract owner can distribute incentives."
        );
    
        let accountBalance = this.balances.get(account);
        this.balances.set(account, accountBalance + amount);
        this.total_supply -= amount;
    
        near.log(
          `Distributed ${amount} tokens to account: ${account}. Total supply: ${this.total_supply}`
        );
      }
    
      // Method to get token balance for an account
      @view({})
      getTokenBalance(account: string): number {
        return this.balances.get(account);
      }
    }
    
    

    And this this is the full error message, when I run the getTokenBalance for exapmle, or the tokenMetadata :

    near view $ID getTokenBalance '{"account": "'$ID'"}'
    View call: dev-1685171425396-11051470732136.getTokenBalance({"account": "dev-1685171425396-11051470732136"})
    An error occured
    Error: Querying [object Object] failed: wasm execution failed with error: HostError(GuestPanic { panic_msg: "cannot read property 'constructor' of undefined\n    at _reconstruct (build/hello_near.js:601)\n    at getTokenBalance (build/hello_near.js:674)\n" }).
    {
      "block_hash": "Cz9sV5Vf9oy8d9gv2epNyKhZzvpd4PmXWmp4kYFahDqi",
      "block_height": 127569024,
      "error": "wasm execution failed with error: HostError(GuestPanic { panic_msg: \"cannot read property 'constructor' of undefined\\n    at _reconstruct (build/hello_near.js:601)\\n    at getTokenBalance (build/hello_near.js:674)\\n\" })",
      "logs": []
    }
        at JsonRpcProvider.query (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:123:19)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async Account.viewFunction (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:366:24)
        at async exports.callViewFunction (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/index.js:103:48)
        at async Object.handler (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)
    TypedError: Querying [object Object] failed: wasm execution failed with error: HostError(GuestPanic { panic_msg: "cannot read property 'constructor' of undefined\n    at _reconstruct (build/hello_near.js:601)\n    at getTokenBalance (build/hello_near.js:674)\n" }).
    {
      "block_hash": "Cz9sV5Vf9oy8d9gv2epNyKhZzvpd4PmXWmp4kYFahDqi",
      "block_height": 127569024,
      "error": "wasm execution failed with error: HostError(GuestPanic { panic_msg: \"cannot read property 'constructor' of undefined\\n    at _reconstruct (build/hello_near.js:601)\\n    at getTokenBalance (build/hello_near.js:674)\\n\" })",
      "logs": []
    }
        at JsonRpcProvider.query (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/node_modules/near-api-js/lib/providers/json-rpc-provider.js:123:19)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async Account.viewFunction (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:366:24)
        at async exports.callViewFunction (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/index.js:103:48)
        at async Object.handler (/home/enoch/.nvm/versions/node/v18.12.1/lib/node_modules/near-cli/utils/exit-on-error.js:52:9) {
      type: 'UntypedError',
      context: undefined
    }
    
  2. fiatisabubble 1

    Hey @iamenochchirima Whilst you are more than welcome to troubleshoot your JS errors on the governance forum you might get better community support on our Discord server. We have a number of technical channels and everyone seems very helpful :slightly_smiling_face:

  3. tonni6030 2

    You’re definitely not alone—many blockchain developers starting out on NEAR face similar issues when using JavaScript/TypeScript SDKs. From your error and code, it looks like the problem comes down to how you’re using the Map object for balances.

    In JavaScript, a Map.get() will return undefined if the key doesn’t exist, and doing arithmetic with undefined causes the kind of error you’re seeing (cannot read property 'constructor' of undefined).

    Quick Fix:

    Update all your Map.get() lines to provide a default value when the account doesn’t exist yet. For example, if you try to get the balance for a recipient or sender and the key doesn’t exist, you should set it to 0 instead of undefined. This ensures that when you try to do arithmetic (like adding or subtracting tokens), you don’t run into errors because undefined isn’t a valid number.

    Also, make sure your init function is actually initializing balances to a new Map object if you’re not using the constructor (because in your code you have a constructor but NEAR calls init instead). So, initialize the balances map inside the init function as well.

    Updated Example:

    For each place in your code where you are fetching the balance of a user, be sure to default the value to 0 if the account doesn’t exist yet. For example, before doing any arithmetic with balances, check if the balance exists; if not, initialize it to 0.

  4. frado 1

    Today have a Near Aí tool for dev. Maybe people of Orizon can save them and @frol @Near-Dev can support your issues.

  5. frol 3

    Hi @iamenochchirima, please, join one of the devs support channels: https://dev.near.org/communities

    There are several problems in your code:

    1. SDK collections require exactly one parameter - the unique storage prefix. See the docs: Collections | NEAR Documentation
    2. The functions must accept exactly one argument which you can deconstruct inline if you want: myFunc({ param1, param2 }: myFuncParams), but you cannot use myFunc(param1: TParam, param2: TParam) - think about it as React props. See the docs above for examples