Here’s code (typescript) that would create the agent and send an update message to a “greet” function. It creates a private key everytime, and will loop through status requests to wait for a reply. To use the Actor factory we use in “normal” DFX you should call didc yourself to create a did.js from a did file.
I didn’t test that code, it’s mostly from our own bootstrap and agent code base.
I highly suggest that you use the Actor class, which can be found here (interface); https://unpkg.com/@dfinity/[email protected]/src/actor.d.ts (see function makeActorFactory
).
import {
Agent,
HttpAgent,
generateKeyPair,
makeAuthTransform,
makeExpiryTransform,
makeNonceTransform,
Principal,
RequestStatusResponseStatus
} from '@dfinity/agent';
const keyPair = generateKeyPair();
const principal = Principal.selfAuthenticating(keyPair.publicKey);
const agent = new HttpAgent({
host: "http://localhost:8000/",
principal,
});
agent.addTransform(makeNonceTransform());
agent.addTransform(makeExpiryTransform(5 * 60 * 1000));
agent.setAuthTransform(makeAuthTransform(keyPair));
async function makeCall(): Promise<Uint8Array> {
let { requestId, response } = await agent.call(CANISTER_ID_GOES_HERE, { methodName: "greet", arg: CANDID_ENCODED_ARGUMENT_GOES_HERE });
if (!response.ok) throw new Error('could not contact the replica. error: ' + response.statusText);
while (true) {
const status = await agent.requestStatus({ requestId });
switch (status) {
case RequestStatusResponseStatus.Replied: {
return new Uint8Array(status.reply.arg || []);
}
case RequestStatusResponseStatus.Unknown:
case RequestStatusResponseStatus.Received:
case RequestStatusResponseStatus.Processing:
continue;
case RequestStatusResponseStatus.Rejected:
throw new Error('call was rejected. reason: ' + status.reject_message);
case RequestStatusResponseStatus.Done:
throw new Error('call was done without a return value. this is an error');
}
}
}
}
Cheers!