Import backend canister from /declarations

I have a React app and a backend canister that I would like to call using a user logged in via Internet Identity. Until now, I was used to calling a backend canister like so:

import { mySmartContract } from '../../declarations/mySmartContract'
const response = await mySmartContract.myFunction();

As I’ve learned now, these calls are - of course - all anonymous.

I am able to get the identity of a logged in user using the AuthClient but I don’t understand how to make a call to the backend canister and am not able to put the pieces together from the different examples/docs. This is what I’m doing rn:

const identity = await authClient.getIdentity();
const agent = new HttpAgent({ identity });
// How do I use the agent with this now?
const response = await mySmartContract.myFunction(); // anonymous call
const response2 = await mySmartContract.myFunction(identity); // not working

Anybody can help me out or point me to the right example?

import { mySmartContract } from '../../declarations/mySmartContract'

Above works because the automatic generated declarations exposes a variable named mySmartContract - an actor - than can indeed be used to perform anonymous query to the IC.

If you open the file ../../declarations/mySmartContract/index.js you will notice how this variable is set. It uses a function named createActor which takes two options, a canistedId- the canister id you want to call - and some options that can be set to create an http agent - notably the one you are looking for, the identity.

So what you can do, instead of importing mySmartContract in your code, is creating a variable - an actor - by using previous function. Something like following:

import { createActor, canisterId } from '../../declarations/mySmartContract'

const identity = await authClient.getIdentity();
const mySmartContract = createActor(canisterId, {agentOptions: {identity}});
const response = await mySmartContract.myFunction();

Does that work out?

2 Likes

Yes, that worked. Thank you also for your good explanation!

1 Like

Sweet, happy to hear that :+1: