smartcontractsnearprotocol

near-api-js: Contract connection with no sender account


Is there a way I can initially connect to a contract without a signer? I want like to create a user flow where the user can explore with view calls, then choose to connect their wallet at a later time.

Most examples I can find of Contract Connection code includes a wallet connected Account. docs github docs


Solution

  • Yes! You can query the state of an account by using the providers in near-api-js.

    Example:

    const { providers } = require("near-api-js");
    const provider = new providers.JsonRpcProvider("https://rpc.testnet.near.org");
    
    getState();
    
    async function getState() {
      const rawResult = await provider.query({
        request_type: "call_function",
        account_id: "guest-book.testnet",
        method_name: "getMessages",
        args_base64: "e30=",
        finality: "optimistic",
      });
    
      const res = JSON.parse(Buffer.from(rawResult.result).toString());
      console.log(res);
    }
    

    https://docs.near.org/docs/api/naj-cookbook#read-state-without-an-account