๐ŸงชTesting Your Oracle Program

Now that you've built and understood the PriceFeed Oracle Program, it's time to run the tests to verify that everything is working correctly. Testing ensures that both the execution and tally phases of your Oracle Program are functioning as expected.

The test cases are located in the tests/ folder. Here's an example of a test for the PriceFeed Oracle Program:

import { afterEach, describe, it, expect, mock } from "bun:test";
import { file } from "bun";
import { testOracleProgramExecution, testOracleProgramTally } from "@seda-protocol/dev-tools"
import { BigNumber } from 'bignumber.js'

const WASM_PATH = "build/debug.wasm";

const fetchMock = mock();

afterEach(() => {
  fetchMock.mockRestore();
});

describe("data request execution", () => {
  it("should aggregate the results from the different APIs", async () => {
    fetchMock.mockImplementation((url) => {
      if (url.host === "api.binance.com") {
        return new Response(JSON.stringify({ price: "2452.30000" }));
      }

      return new Response('Unknown request');
    });

    const wasmBinary = await file(WASM_PATH).arrayBuffer();

    const vmResult = await testOracleProgramExecution(
      Buffer.from(wasmBinary),
      Buffer.from("eth-usdc"),
      fetchMock
    );

    expect(vmResult.exitCode).toBe(0);
    // BigNumber.js is big endian
    const hex = Buffer.from(vmResult.result.toReversed()).toString('hex');
    const result = BigNumber(`0x${hex}`);
    expect(result).toEqual(BigNumber('2452300032'));
  });

  it('should tally all results in a single data point', async () => {
    const wasmBinary = await file(WASM_PATH).arrayBuffer();

    // Result from the execution test
    let buffer = Buffer.from([0, 33, 43, 146, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
    const vmResult = await testOracleProgramTally(Buffer.from(wasmBinary), Buffer.from('tally-inputs'), [{
      exitCode: 0,
      gasUsed: 0,
      inConsensus: true,
      result: buffer,
    }]);

    expect(vmResult.exitCode).toBe(0);
    const hex = Buffer.from(vmResult.result).toString('hex');
    const result = BigNumber(`0x${hex}`);
    expect(result).toEqual(BigNumber('2452300032'));
  });
});

To run the tests, use the following command:

bun run test

bun test v1.1.20 (ae194892)

tests/index.test.ts:
โœ“ PriceFeed Oracle Program > should fetch and process the price for a given asset pair [135.00ms]
โœ“ PriceFeed Oracle Program > should correctly calculate the median price in the tally phase [75.00ms]

 2 pass
 0 fail
 4 expect() calls
Ran 2 tests across 1 files. [916.00ms]

Last updated