Caught exception while attempting to read state: Network error happened (When using plug wallet to create an agent)

I am getting this error when interacting with my canister while using plug wallet:

AgentReadStateError: Caught exception while attempting to read state: Server returned an error:
  Code: 408 ()
  Body: Network error happened

    at r.readState (inpage.js:31:322)
    at async inpage.js:28:6821
    at async Promise.all (:3005/index 0)
    at async MB (inpage.js:28:8303)
    at async r.fetchSubnetKeys (inpage.js:31:2810)
    at async ee (inpage.js:28:55382)
    at async Promise.all (:3005/index 1)

I am creating an agent using plug wallet, These are the steps I am taking:

  1. Connecting plug wallet
export const connectPlug = async () => {
  try {
    console.log("Connecting to Plug wallet");
    // First check if already connected
    const isConnected = await window.ic.plug.isConnected();
    console.log("isConnected", isConnected);
    if (isConnected) {
      await window.ic.plug.createAgent({
        host: "https://ic0.app"
      });
      return true;
    }

    // Only request connection if not already connected
    console.log("Requesting connection");
    const connected = await window.ic.plug.requestConnect();
    console.log("connected", connected);
    if (connected) {
      console.log("Creating agent");
      await window.ic.plug.createAgent({
        host: "https://ic0.app"
      });
      return true;
    }
    console.log("Failed to connect to Plug wallet");
    return false;
  } catch (error) {
    console.error("Failed to connect to Plug wallet:", error);
    return false;
  }
};
  1. Creating the agent:
export const getConnectedWalletAgent = async () => {
  try {
    const isConnected = await checkConnection();
    if (!isConnected) {
      throw new Error("Wallet not connected");
    }
    return window.ic.plug.agent;
  } catch (error) {
    console.error("Failed to get connected wallet agent:", error);
    throw error;
  }
};
  1. Fetching the NFTs from the backend
const sessionAgent = await getConnectedWalletAgent();
      console.log("sessionAgent at live sale", sessionAgent);
      const actor = createActor(frysBackendCanisterID, sessionAgent);
      console.log("actor at live sale", actor);
      const userActor = createActor(usersCanisterID, sessionAgent);
      console.log("userActor at live sale", userActor);
      const userPrincipalText = await getPrincipalID();
      console.log("userPrincipalText at live sale", userPrincipalText);
      const userPrincipal = Principal.fromText(userPrincipalText);
      console.log("userPrincipal at live sale", userPrincipal); 
      const allUsers = await userActor.get_all_users();
      console.log("allUsers at live sale", allUsers);

      // Get user's owned NFTs using Principal type
      const allOwnedNFTs = new Set(allUsers.flatMap((user) => user.owned_nfts));
      console.log("All owned NFTs:", allOwnedNFTs);

But my code is failing at these lines

const allUsers = await userActor.get_all_users();
      console.log("allUsers at live sale", allUsers);

      // Get user's owned NFTs using Principal type
      const allOwnedNFTs = new Set(allUsers.flatMap((user) => user.owned_nfts));

I still don’t understand where the Bad Network error is coming from

I also have this error from my console that I suspect is related to the bad network error I am getting:

Access to fetch at 'http://localhost:5000/api/v2/canister/nmaac-eyaaa-aaaal-ar4aq-cai/query' from origin 'http://localhost:3005' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
index.tsx:116 

I can guess you’re trying to connect to localhost
but your code include

await window.ic.plug.createAgent({
        host: "https://ic0.app"
      });
1 Like

No, the canister I’m interacting with is on mainnet

The first issue seems to be with the host I think, it should probably be left at it’s default value or set to https://icp-api.io (which is the default in agent-js if I remember correctly).

The error you’re sharing seem to indicate that a localhost frontend at port 3005 can’t access the canister at localhost port 5000. Is perhaps your frontend running on localhost and trying to access canisters on mainnet?

It looks you’re getting this error since the mainnet canister doesn’t exist on localhost, and even though your current configuration intends to communicate with mainnet, in practice it’s making calls to localhost.

I’d recommend to have a look at the browser dev tools network tab and see which URL are being called, to verify this.


On another note, I’d recommend using the signer-js libs instead that follow the signer standards, Plug supports these ICRC standards too nowadays.

Supporting various wallets is a matter of swapping out the transport, currently there’s the web and extension transport that cover most of the Wallets on the IC.

import { Signer } from "@slide-computer/signer";
import { SignerAgent } from "@slide-computer/signer-agent";
import { BrowserExtensionTransport } from "@slide-computer/signer-extension";

const transport = await BrowserExtensionTransport.findTransport({
    // Unique ID of the Plug browser extension
    uuid: '71edc834-bab2-4d59-8860-c36a01fee7b8'
});
const signer = new Signer({transport});
const accounts = await signer.accounts();
const agent = await SignerAgent.create({
    signer,
    account: accounts[0].owner
});

Alternatively there’s also IdentityKit that wraps the standards in a React framework.

You can find the Identity and Wallets Standards WG here: GitHub - dfinity/wg-identity-authentication: Repository of the Identity and Wallet Standards Working Group

1 Like

Hey @Stephen-Kimoi.

We use https://icp0.io as a host for ICP mainnet, probably that mismatch causes the error. You should get no error, when changing your host in createAgent

@sea-snake has correctly pointed that there are also alternatives to integration via window.ic.plug such as signer library or IdentityKit

1 Like