Skip to content

Getting Started

Kyle Peacock edited this page Oct 28, 2021 · 2 revisions

Installing the JavaScript Agent

The JavaScript agent is built for Node version 12+, and we recommend using a bundler. The dfx new template sets you up with Webpack, but neither DFX nor Webpack are required to use @dfinity/agent in your project.

npm install --save @dfinity/agent @dfinity/principal @dfinity/candid

This will install the agent, as well as Principal and Candid, which are peer dependencies.

In your code, import the agent. Here is a minimal setup assuming you are working in a browser context.

// index.js
import { Actor, HttpAgent } from "@dfinity/agent";

const canisterId = "rrkah-fqaaa-aaaaa-aaaaq-cai";

// Candid interface for a canister with one 'greet' method
const idlFactory = ({ IDL }) => {
  return IDL.Service({ "greet" : IDL.Func([IDL.Text], [IDL.Text], []) });
};

// Initialize a HttpAgent, which handles low-level calls to the IC API
const agent = new HttpAgent();

// Initialize an actor interface, which will make calls to methods defined in the idlFactory
const actor = Actor.createActor(idlFactory, {
  agent,
  canisterId
});

This minimal setup assumes that you are hosting your application on the Internet Computer, and that your domain will be either localhost or ic0.app. If you are hosting the application on your own domain, or you are running your script in Node.js, you will need to specify a host when you initialize the HttpAgent.

const agent = new HttpAgent({ host: "https://ic0.app" });

Requirements for Node.js

In addition to requiring a host, you will need to do a little additional setup to use the agent in a Node.js application, based on some global utilities that need to be polyfilled.

First, install some additional packages:

npm install --save-dev @trust/webcrypto text-encoding node-fetch

Then, in the entrypoint of your service:

// index.js
global.crypto = require('@trust/webcrypto');
global.TextEncoder = require('text-encoding').TextEncoder;
global.TextDecoder = require('text-encoding').TextDecoder;
global.fetch = require('node-fetch');

...

const agent = new HttpAgent({ host: "https://ic0.app" });

...

Calling a Canister

With the setup above, you have a variable actor that is configured to mirror the interface of the actor running in your canister. For more on the Actor model, see this writeup: https://sdk.dfinity.org/docs/language-guide/actors-async.html.

To interact with your canister, call methods on your actor instance. In this example, that would look like:

actor.greet("New Dev"); // -> "Hello, New Dev!"

The greet method will return a promise. Behind the scenes, the HttpAgent creates an asyncronous request, POSTs it to the IC, and then polls for a result.

Clone this wiki locally