All files / src request-data-packages.ts

92.23% Statements 95/103
73.33% Branches 22/30
96% Functions 24/25
92% Lines 92/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306  3x       3x 3x   3x 3x   3x 3x 3x                                         3x                                                         3x                       3x       8x     6x             2x     3x     22x     22x 22x   22x       22x         8x     8x       3x       22x 22x 22x 22x   22x 4x 4x     22x 40x 9x 9x 31x       23x   13x     13x   13x     23x 23x       22x 38x 19x 17x           3x     22x     22x 22x         22x       22x 38x 25x         3x       25x   25x   24x   24x 27x   27x 1x           26x 3x 7x 7x 2x   5x         26x 2x 2x   4x         26x 4x             22x           19x     3x       22x 49x     22x 49x                 38x       38x                     7x 7x   2x               22x 49x           45x     3x     22x 10x   12x    
import { RedstoneOraclesState } from "@redstone-finance/oracles-smartweave-contracts";
import {
  SignedDataPackage,
  SignedDataPackagePlainObj,
} from "@redstone-finance/protocol";
import { MathUtils, RedstoneCommon, SafeNumber } from "@redstone-finance/utils";
import axios from "axios";
import { BigNumber } from "ethers";
import { z } from "zod";
import { resolveDataServiceUrls } from "./data-services-urls";
 
const GET_REQUEST_TIMEOUT = 5_000;
const DEFAULT_WAIT_FOR_ALL_GATEWAYS_TIME = 500;
const MILLISECONDS_IN_ONE_MINUTE = 60 * 1000;
 
export interface DataPackagesRequestParams {
  dataServiceId: string;
  uniqueSignersCount: number;
  waitForAllGatewaysTimeMs?: number;
  maxTimestampDeviationMS?: number;
  authorizedSigners?: string[];
  dataFeeds: string[];
  urls?: string[];
  historicalTimestamp?: number;
}
 
export interface DataPackagesResponse {
  [dataFeedId: string]: SignedDataPackage[] | undefined;
}
 
export interface ValuesForDataFeeds {
  [dataFeedId: string]: BigNumber | undefined;
}
 
const GwResponseSchema = z.record(
  z.string(),
  z.array(
    z.object({
      dataPoints: z
        .array(
          z
            .object({
              dataFeedId: z.string(),
              value: z.number(),
              decimals: z.number().optional(),
            })
            .or(
              z.object({
                dataFeedId: z.string(),
                value: z.string(),
                decimals: z.number().optional(),
              })
            )
        )
        .min(1),
      timestampMilliseconds: z.number(),
      signature: z.string(),
      dataFeedId: z.string(),
    })
  )
);
export type GwResponse = Partial<z.infer<typeof GwResponseSchema>>;
 
export const getDataServiceIdForSigner = (
  oracleState: RedstoneOraclesState,
  signerAddress: string
) => {
  for (const nodeDetails of Object.values(oracleState.nodes)) {
    Iif (nodeDetails.evmAddress.toLowerCase() === signerAddress.toLowerCase()) {
      return nodeDetails.dataServiceId;
    }
  }
  throw new Error(`Data service not found for ${signerAddress}`);
};
 
export const calculateHistoricalPackagesTimestamp = (
  deviationCheckOffsetInMinutes: number,
  baseTimestamp: number = Date.now()
) => {
  if (deviationCheckOffsetInMinutes > 0) {
    // We round the timestamp to full minutes for being compatible with
    // oracle-nodes, which usually work with rounded 10s and 60s intervals
    return (
      Math.floor(
        baseTimestamp / MILLISECONDS_IN_ONE_MINUTE -
          deviationCheckOffsetInMinutes
      ) * MILLISECONDS_IN_ONE_MINUTE
    );
  }
  return undefined;
};
 
export const requestDataPackages = async (
  reqParams: DataPackagesRequestParams
): Promise<DataPackagesResponse> => {
  Iif (reqParams.dataFeeds.length < 1) {
    throw new Error("Please provide at least one dataFeed");
  }
  try {
    const promises = prepareDataPackagePromises(reqParams);
 
    Iif (reqParams.historicalTimestamp) {
      return await Promise.any(promises);
    }
 
    return await getTheMostRecentDataPackages(
      promises,
      reqParams.waitForAllGatewaysTimeMs
    );
  } catch (e) {
    const errMessage = `Request failed ${JSON.stringify({
      reqParams,
    })}, Original error: ${RedstoneCommon.stringifyError(e)}`;
    throw new Error(errMessage);
  }
};
 
const getTheMostRecentDataPackages = (
  promises: Promise<DataPackagesResponse>[],
  waitForAllGatewaysTimeMs = DEFAULT_WAIT_FOR_ALL_GATEWAYS_TIME
): Promise<DataPackagesResponse> => {
  return new Promise((resolve, reject) => {
    const collectedResponses: DataPackagesResponse[] = [];
    const errors: Error[] = [];
    let waitForAll = true;
 
    const timer = setTimeout(() => {
      waitForAll = false;
      checkResults();
    }, waitForAllGatewaysTimeMs);
 
    const checkResults = () => {
      if (errors.length === promises.length) {
        clearTimeout(timer);
        reject(new AggregateError(errors));
      } else if (
        collectedResponses.length + errors.length === promises.length ||
        (!waitForAll && collectedResponses.length !== 0)
      ) {
        const newestPackage = collectedResponses.reduce((a, b) => {
          const aTimestamp =
            Object.values(a).at(0)?.at(0)?.dataPackage.timestampMilliseconds ??
            0;
          const bTimestamp =
            Object.values(b).at(0)?.at(0)?.dataPackage.timestampMilliseconds ??
            0;
          return bTimestamp > aTimestamp ? b : a;
        });
 
        clearTimeout(timer);
        resolve(newestPackage);
      }
    };
 
    for (const promise of promises) {
      promise
        .then((r) => collectedResponses.push(r))
        .catch((e) => errors.push(e as Error))
        .finally(checkResults);
    }
  });
};
 
const prepareDataPackagePromises = (
  reqParams: DataPackagesRequestParams
): Promise<DataPackagesResponse>[] => {
  Iif (reqParams.authorizedSigners && reqParams.authorizedSigners.length == 0) {
    throw new Error("authorizer signers array, if provided, cannot be empty");
  }
  const urls = getUrlsForDataServiceId(reqParams);
  const pathComponents = [
    "data-packages",
    reqParams.historicalTimestamp ? "historical" : "latest",
    reqParams.dataServiceId,
  ];
  Iif (reqParams.historicalTimestamp) {
    pathComponents.push(`${reqParams.historicalTimestamp}`);
  }
 
  return urls.map((url) =>
    sendRequestToGateway(url, pathComponents, reqParams).then((response) =>
      parseAndValidateDataPackagesResponse(response.data, reqParams)
    )
  );
};
 
const parseAndValidateDataPackagesResponse = (
  responseData: unknown,
  reqParams: DataPackagesRequestParams
): DataPackagesResponse => {
  const parsedResponse: DataPackagesResponse = {};
 
  RedstoneCommon.zodAssert<GwResponse>(GwResponseSchema, responseData);
 
  const requestedDataFeedIds = reqParams.dataFeeds;
 
  for (const dataFeedId of requestedDataFeedIds) {
    let dataFeedPackages = responseData[dataFeedId];
 
    if (!dataFeedPackages) {
      throw new Error(
        `Requested data feed id is not included in response: ${dataFeedId}`
      );
    }
 
    // filter out packages with not expected signers
    if (reqParams.authorizedSigners) {
      dataFeedPackages = dataFeedPackages.filter((dp) => {
        const signer = maybeGetSigner(dp);
        if (!signer) {
          return false;
        }
        return reqParams.authorizedSigners!.includes(signer);
      });
    }
 
    // filter out package with deviated timestamps
    if (reqParams.maxTimestampDeviationMS) {
      const now = Date.now();
      dataFeedPackages = dataFeedPackages.filter(
        (dp) =>
          Math.abs(now - dp.timestampMilliseconds) <
          reqParams.maxTimestampDeviationMS!
      );
    }
 
    if (dataFeedPackages.length < reqParams.uniqueSignersCount) {
      throw new Error(
        `Too few unique signers for the data feed: ${dataFeedId}. ` +
          `Expected: ${reqParams.uniqueSignersCount}. ` +
          `Received: ${dataFeedPackages.length}`
      );
    }
 
    parsedResponse[dataFeedId] = pickDataFeedPackagesClosestToMedian(
      dataFeedPackages,
      reqParams.uniqueSignersCount
    );
  }
 
  return parsedResponse;
};
 
const pickDataFeedPackagesClosestToMedian = (
  dataFeedPackages: SignedDataPackagePlainObj[],
  count: number
): SignedDataPackage[] => {
  const median = MathUtils.getMedian(
    dataFeedPackages.map((dp) => dp.dataPoints[0].value)
  );
 
  return sortByDistanceFromMedian(dataFeedPackages, median)
    .map((diff) => SignedDataPackage.fromObj(diff.dp))
    .slice(0, count);
};
 
function sendRequestToGateway(
  url: string,
  pathComponents: string[],
  reqParams: DataPackagesRequestParams
) {
  const sanitizedUrl = [url.replace(/\/+$/, "")]
    .concat(pathComponents)
    .join("/");
 
  return axios.get<Record<string, SignedDataPackagePlainObj[]>>(sanitizedUrl, {
    timeout: GET_REQUEST_TIMEOUT,
    params: {
      dataFeedIds: reqParams.dataFeeds,
      minimalSignersCount: reqParams.uniqueSignersCount,
    },
    paramsSerializer: { indexes: null },
  });
}
 
function maybeGetSigner(dp: SignedDataPackagePlainObj) {
  try {
    return SignedDataPackage.fromObj(dp).recoverSignerAddress();
  } catch {
    return undefined;
  }
}
 
function sortByDistanceFromMedian(
  dataFeedPackages: SignedDataPackagePlainObj[],
  median: number
) {
  return dataFeedPackages
    .map((dp) => ({
      dp: dp,
      diff: SafeNumber.createSafeNumber(dp.dataPoints[0].value)
        .sub(median)
        .abs(),
    }))
    .sort((first, second) => first.diff.sub(second.diff).unsafeToNumber());
}
 
const getUrlsForDataServiceId = (
  reqParams: DataPackagesRequestParams
): string[] => {
  if (reqParams.urls) {
    return reqParams.urls;
  }
  return resolveDataServiceUrls(reqParams.dataServiceId);
};