New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@generalprotocols/oracle-client

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@generalprotocols/oracle-client

Client to interact with GeneralProtocols Oracle HTTP API

latest
npmnpm
Version
0.0.1
Version published
Maintainers
1
Created
Source

Oracle Client

Overview

The Oracle Client is an all-in-one library for interacting with General Protocol's Oracle Relay API. It provides developers with type-safe methods for fetching data over HTTP and realtime updates with Server-Sent Events (SSE). With built in Zod validation, it ensures the responses can be reliably handled and type-safe.

To simplify message handling and development, all messages that are returned from the API have their signatures validated and the message content is parsed into the appropriate type, and can be readily used without additional validation.

The Oracle Client is designed to make consuming Oracle Messages easier, but lacks some features found in the Price Oracle Library, such as:

  • Serialization and Deserialization of messages for use on the blockchain
  • Converting between Satoshis and BCH
  • Hosting or interfacing with ZeroMQ

Index

Features

  • Signature and content validation of messages
  • Type-safe API for fetching data from the API
  • Real-time price updates via Server-Sent Events (SSE)
  • Zod schema validation
  • Message creation and signing

Installation

npm install @generalprotocols/oracle-client

SSE Usage

// Creating a client that listens for new messages
const client = await OracleClient.from('https://oracles.generalprotocols.com', {
  // Called when any kind of message is received
  onMessage: (message: OracleMessage) => {
    console.log(`Received new Message: ${message.message}`);
  },
  // Called when a price message is received
  onPriceMessage: (priceMessage: OraclePriceMessage) => {
    console.log(`Received new Price Message: ${priceMessage.price}`);
  },
  // Called when a metadata message is received
  onMetadataMessage: (metadataMessage: OracleMetadataMessage) => {
    console.log(`Received new Metadata Message: ${metadataMessage.metadata}`);
  },
});

Basic Usage

import {
  OracleClient,
  type OracleMessage,
  type OraclePriceMessage,
  type OracleMetadataMessage,
} from 'oracle-client';

// Creating a client
const client = await OracleClient.from('https://oracles.generalprotocols.com');

// Fetching the oracles
const oracles = await client.getOracles();
console.log(oracles);

// Fetching messages for an oracle
const BCHUSD =
  '02d09db08af1ff4e8453919cc866a4be427d7bfe18f2c05e5444c196fcf6fd2818';

// Fetching price messages for the BCH/USD oracle
const messages = await client.getOracleMessages({
  publicKey: BCHUSD,
  minDataSequence: 1,
});
console.log(messages);

/**
 * Getting the current price of the BCH/USD oracle
 */
// Fetch the metadata and create a map of the available oracles so we can scale the price accordingly
const metadataMap = await client.getMetadataMap();
console.log(metadataMap);

// Grab the first message
const message = messages[0];

// Make sure the message is a price message
if (!(message instanceof OraclePriceMessage)) {
  throw new Error('Message is not a price message');
}

// Make sure the metadata map contains the BCHUSD oracle
if (!metadataMap[BCHUSD]) {
  throw new Error('Metadata map does not contain BCHUSD');
}

// Make sure the metadata map's ATTESTATION_SCALING value is not undefined
if (typeof metadataMap[BCHUSD].ATTESTATION_SCALING === 'undefined') {
  throw new Error(`Metadata map's ATTESTATION_SCALING value is undefined`);
}

// Divide the priceValue by the metadata map's ATTESTATION_SCALING value
const oracleUnitsPerCommonUnit = metadataMap[BCHUSD].ATTESTATION_SCALING;
const price = message.priceValue / oracleUnitsPerCommonUnit;
console.log(price);

Message Parsing

Messages are returned as either a OraclePriceMessage or a OracleMetadataMessage. To parse a message to a single type, you can use either instanceof or the static isMetadataMessage or isPriceMessage methods.

const message: OraclePriceMessage | OracleMetadataMessage =
  OracleMessage.from(signedMessage);

// Using instanceof
if (message instanceof OracleMetadataMessage) {
  // Use as a metadata message
} else {
  // Use as a price message
}

// Using static methods
const isMetadata = OracleMessage.isMetadataMessage(message);
if (isMetadata) {
  // Use as a metadata message
} else {
  // Use as a price message
}

Updating a MetadataMap

// Create a client
const client = await OracleClient.from('https://oracles.generalprotocols.com');

// Get the metadata for the available oracles so we can scale the price accordingly
const metadataMap = await client.getMetadataMap();

// Create a callback that updates the metadataMap when a new metadata message is received
client.setOnMetadataMessage((metadataMessage) => {
  // Update the metadata map using the Client's static method
  OracleClient.updateMetadataMap(metadataMap, metadataMessage);
});

OracleClient

Client Options

OptionDescriptionDefault
sseThe SSE options{ method: 'GET', attemptReconnect: true, retryDelay: 1000, persistent: true } & { subscriptionUrl: ${baseURL}/sse/v1/messages }
onMessageCalled when a message is received(message: OracleMessage) => {}
onPriceMessageCalled when a price message is received(priceMessage: OraclePriceMessage) => {}
onMetadataMessageCalled when a metadata message is received(metadataMessage: OracleMetadataMessage) => {}

SSE Options

OptionDescriptionDefault
methodThe HTTP method to useGET
headersThe HTTP headers to send with the request{}
bodyThe body to send with POST requestsnull
onMessageCalled when a Server-Sent Event is received(event: SSEEvent) => {}
onConnectedCalled when the connection is established() => {}
onDisconnectedCalled when the connection is closed() => {}
onErrorCalled when an error occurs(error: unknown) => {}
attemptReconnectWhether to attempt to reconnecttrue
retryDelayThe delay in milliseconds between reconnection attempts1000
persistentWhether to reconnect when the session is terminated by the servertrue

getOracles

Get a list of the available oracles and their metrics.

Oracle's may return without any metrics. Metrics are only provided if the oracle has messages from the last 24 hours.

Signature

client.getOracles(options?: RequestOptions): Promise<GetOraclesResponse>;

Params

RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetOraclesResponse = {
  oracles: {
    publicKey: string;
    messageMetrics?: {
      maxMessageSequence: number;
      minMessageTimestamp: number;
      maxMessageTimestamp: number;
    };
  }[];
};

getPrices

Signature

client.getPrices(params: GetPricesRequest, options?: RequestOptions): Promise<GetPricesResponse>;

Params

GetPricesRequest
OptionDescriptionType
maxPriceSequence(Optional) The maximum price sequence to fetchnumber
limit(Default: 50) The maximum number of prices to fetchnumber
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetPricesResponse = {
  prices: {
    priceSequence: number;
    priceValue: number;
    messageId?: number;
  }[];
};

getMessages

Get a list of messages for an oracle.

You can filter messages by timestamp, sequence, data sequence, and metadata type

Signature

client.getMessages(params: GetMessagesRequest, options?: RequestOptions): Promise<GetMessagesResponse>;

Params

GetMessagesRequest
OptionDescriptionType
publicKeyThe public key of the oracle to fetch messages forstring
minMessageTimestamp(Optional) The minimum message (Unix)timestamp to fetchnumber
maxMessageTimestamp(Optional) The maximum message (Unix) timestamp to fetchnumber
minMessageSequence(Optional) The minimum message sequence to fetchnumber
maxMessageSequence(Optional) The maximum message sequence to fetchnumber
minDataSequence(Optional) The minimum data sequence to fetchnumber
maxDataSequence(Optional) The maximum data sequence to fetchnumber
minMetadataType(Optional) The minimum metadata type to fetchnumber
maxMetadataType(Optional) The maximum metadata type to fetchnumber
count(Default: 50) The maximum number of messages to fetchnumber
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetMessagesResponse = {
  oracleMessages: {
    message: string;
    publicKey: string;
    signature: string;
  }[];
};

getMetadataMessages

Get a list of metadata messages for an oracle.

You can filter messages by publicKey and sequence

Signature

client.getMetadataMessages(params: GetMetadataMessagesRequest, options?: RequestOptions): Promise<GetMetadataMessagesResponse>;

Params

GetMetadataMessagesRequest
OptionDescriptionType
publicKey(Optional) The public key of the oracle to fetch metadata messages forstring
maxMessageSequence(Optional) The maximum message sequence to fetchnumber
count(Default: 50) The maximum number of metadata messages to fetchnumber
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetMetadataMessagesResponse = {
  oracleMetadata: {
    publicKey: string;
    message: string;
    signature: string;
  }[];
};

getPriceGraphImage

Get an string encoded SVG of the price graph for an oracle.

Signature

client.getPriceGraphImage(params: GetPriceGraphImageRequest, options?: RequestOptions): Promise<GetPriceGraphImageResponse>;

Params

GetPriceGraphImageRequest
OptionDescriptionType
publicKeyThe public key of the oracle to fetch the price graph image forstring
minMessageTimestamp(Optional) The minimum message (Unix) timestamp to fetchnumber
maxMessageTimestamp(Optional) The maximum message (Unix) timestamp to fetchnumber
timePeriodGranularity(Default: 'day') The time period granularity to fetch'minute', 'hour', 'day', 'week', 'month'
chartWidth(Optional) The width of the chartnumber
chartHeight(Optional) The height of the chartnumber
strokeColor(Optional) The color of the strokestring
strokeWidth(Optional) The width of the strokenumber
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetPriceGraphImageResponse = string;

getPriceGraphData

Get the price graph data for an oracle.

Signature

client.getPriceGraphData(params: GetPriceGraphDataRequest, options?: RequestOptions): Promise<GetPriceGraphDataResponse>;

Params

GetPriceGraphDataRequest
OptionDescriptionType
publicKeyThe public key of the oracle to fetch the price graph data forstring
minMessageTimestamp(Optional) The minimum message timestamp to fetchnumber
maxMessageTimestamp(Optional)The maximum message timestamp to fetchnumber
timePeriodGranularity(Default: 'day') The time period granularity to fetch'minute', 'hour', 'day', 'week', 'month'
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetPriceGraphDataResponse = {
  priceGraphPoints: {
    averagePrice: number;
    timePeriod: string;
  }[];
};

getAggregatedPriceGraphData

Get the price graph data for an oracle.

Signature

client.getAggregatedPriceGraphData(params: GetAggregatedPriceGraphDataRequest, options?: RequestOptions): Promise<GetAggregatedPriceGraphDataResponse>;

Params

GetAggregatedPriceGraphDataRequest
OptionDescriptionType
publicKeyThe public key of the oracle to fetch the aggregated price graph data forstring
minMessageTimestampThe minimum message (Unix) timestamp to fetchnumber
maxMessageTimestampThe maximum message (Unix) timestamp to fetchnumber
aggregationPeriodThe aggregation period (in seconds) to fetchnumber
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetAggregatedPriceGraphDataResponse = {
  priceGraphPoints: {
    minimumTimestamp: number;
    maximumTimestamp: number;
    averageTimestamp: number;
    minimumPrice: number;
    maximumPrice: number;
    averagePrice: number;
  }[];
};

getRecoveryProgress

Get the recovery progress for an oracle.

Signature

client.getRecoveryProgress(params: GetRecoveryProgressRequest, options?: RequestOptions): Promise<GetRecoveryProgressResponse>;

Params

GetRecoveryProgressRequest
OptionDescriptionType
publicKeyThe public key of the oracle to fetch the recovery progress forstring
RequestOptions
OptionDescriptionDefault
validateWhether to validate the response with Zodtrue

Response

type GetRecoveryProgressResponse = {
  recoveryProgress: {
    messagesCount: number;
    maxMessageSequence: number;
    maxMessageTimestamp: number;
    recoveryProgressPercent: string;
  };
};

getMetadataMap

Signature

client.getMetadataMap(): Promise<OracleMetadataMap>;

Response

type OracleMetadataMap = Partial<{
  OPERATOR_NAME: string; // -1
  OPERATOR_WEBSITE: string; // -2
  RELAY_SERVER: string; // -3
  STARTING_TIMESTAMP: number; // -4
  ENDING_TIMESTAMP: number; // -5
  ATTESTATION_SCALING: number; // -6
  ATTESTATION_PERIOD: number; // -7
  OPERATOR_HASH: string; // -8
  SOURCE_NAME: string; // -51
  SOURCE_WEBSITE: string; // -52
  SOURCE_NUMERATOR_UNIT_NAME: string; // -53
  SOURCE_NUMERATOR_UNIT_CODE: string; // -54
  SOURCE_HASH: string; // -55
  SOURCE_DENOMINATOR_UNIT_NAME: string; // -56
  SOURCE_DENOMINATOR_UNIT_CODE: string; // -57
}>;

FAQs

Package last updated on 07 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts