Http Agent Example

As suggested by the Grant Committee, what follows is our NodeJS example instantiation of the @dfinity/agent package library that we used for our oracle project. I found few online examples of how to work with the package, but benefitted from GitHub - tarek-eg/entrebot-query: A simple script to query cronics NFT data from entrebot marketplace

As we aren’t able to share our node microservice repo, it was suggested to share just this bit here to help the community. The Motoko oracle code is public, but we also wanted to be able to share an example of how we connected NodeJS to the IC.

const config = require('config');
const fetch = require('node-fetch');
const { Actor, HttpAgent } = require('@dfinity/agent');
const { idlFactory } = require('../candid/price_oracle.did.js');

const canisterId = config.get('canisterId');
const env = process.env.NODE_ENV;

// boilerplate from github.com/tarek-eg/entrebot-query
//(global as any).fetch = fetch;
global.fetch = fetch;

const createActor = (agent) => {
  // fetch root key for certificate validation during development
  if (env === 'test') { agent.fetchRootKey(); };

  return Actor.createActor(
    idlFactory,
    {
      agent,
      canisterId
    }
  );
}

const defaultAgent = new HttpAgent({
  host: (env === 'test') ? "http://localhost:8000" : "https://ic0.app",
});

const oracle = createActor(defaultAgent);

async function getPrincipal() {
  let p = await defaultAgent.getPrincipal();
  console.log(p);
}

async function getIndex() {
  let res = await oracle.getIndex();
  console.log("getting latest index...");
  console.log(res);
}

async function getRecord(_record) {
  let res = await oracle.getRecord(_record);
  console.log("getting record at index 0...");
  console.log(res);
}

async function getPrice(_timestamp) {
  let res = await oracle.getPrice(_timestamp);
  console.log(`getting price closest to ${_timestamp}`);
  console.log(res);
}

async function getLatestPrice() {
  let res = await oracle.getLatest();
  console.log(`getting last price`);
  console.log(res);
  return res.toString();
}

async function query() {
  try {
    await getIndex();
    await getRecord(0);
    await getPrice(1642972282418785000n);
    await getLatestPrice();
  }
  catch (ex) {
    console.log(ex);
  }
}

//query();

module.exports = {
  getPrincipal,
  getLatestPrice
}

We hope the above is informative. Constructive criticism welcome!

4 Likes