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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 6x 2x 4x 22x 22x 22x 22x 22x 8x 8x 4x 22x 22x 22x 22x 22x 4x 4x 22x 72x 22x 40x 9x 9x 31x 23x 36x 23x 23x 22x 38x 19x 17x 4x 22x 22x 22x 22x 22x 38x 25x 4x 25x 25x 24x 24x 27x 27x 1x 1x 26x 3x 7x 7x 2x 5x 26x 2x 2x 4x 26x 4x 4x 22x 19x 4x 22x 38x 38x 7x 7x 2x 4x | import {
SignedDataPackage,
SignedDataPackagePlainObj,
} from "@redstone-finance/protocol";
import { RedstoneCommon } from "@redstone-finance/utils";
import axios from "axios";
import { BigNumber } from "ethers";
import { z } from "zod";
import { resolveDataServiceUrls } from "./data-services-urls";
import { pickDataFeedPackagesClosestToMedian } from "./pick-closest-to-median";
const GET_REQUEST_TIMEOUT = 5_000;
const DEFAULT_WAIT_FOR_ALL_GATEWAYS_TIME = 500;
const MILLISECONDS_IN_ONE_MINUTE = 60 * 1000;
/**
* defines behavior of {@link requestDataPackages} method
*/
export interface DataPackagesRequestParams {
/**
* for production environment most of the time "redstone-primary-prod" is appropriate
*/
dataServiceId: string;
/**
* array of tokens to fetch
*/
dataPackagesIds: string[];
/**
* ensure minimum number of signers for each token
* - 'uniqueSignersCount' packages closest to median of all fetched packages are returned (value 2 is recommended for prod nodes)
* - throws if there are less signers for any token
*/
uniqueSignersCount: number;
/**
* wait for responses from all the gateways for this time, then wait for at least one response and return the newest fetched packages (does not apply if 'historicalTimestamp' is provided)
*/
waitForAllGatewaysTimeMs?: number;
/**
* filter out old packages
*/
maxTimestampDeviationMS?: number;
/**
* accept packages only from specific signers, by default do not filter by signers
*/
authorizedSigners?: string[];
/**
* fetch from specific gateways, if not provided fetch from all publicly available gateways
*/
urls?: string[];
/**
* fetch packages from specific moment (unix timestamp in milliseconds), most of the time this value should be multiple of 10000 (10 sec)
* in this mode first response is returned to the user
*/
historicalTimestamp?: number;
/**
* do not throw error in case of missing or filtered-out token
*/
ignoreMissingFeed?: boolean;
}
/**
* represents per-feed response from DDL
*/
export interface DataPackagesResponse {
[dataPackageId: string]: SignedDataPackage[] | undefined;
}
export interface ValuesForDataFeeds {
[dataFeedId: string]: BigNumber | undefined;
}
export const SignedDataPackageSchema = 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(),
dataPackageId: z.string(),
});
const GwResponseSchema = z.record(z.string(), z.array(SignedDataPackageSchema));
export type GwResponse = Partial<z.infer<typeof GwResponseSchema>>;
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;
};
/**
* fetch data packages from RedStone DDL
* @param {DataPackagesRequestParams} reqParams fetch config
*/
export const requestDataPackages = async (
reqParams: DataPackagesRequestParams
): Promise<DataPackagesResponse> => {
Iif (reqParams.dataPackagesIds.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 responseTimestamp = (response: DataPackagesResponse) =>
Object.values(response).at(0)?.at(0)?.dataPackage.timestampMilliseconds ??
0;
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) => (responseTimestamp(b) > responseTimestamp(a) ? 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(async (url) => {
const response = await sendRequestToGateway(url, pathComponents, reqParams);
return parseAndValidateDataPackagesResponse(response.data, reqParams);
});
};
const parseAndValidateDataPackagesResponse = (
responseData: unknown,
reqParams: DataPackagesRequestParams
): DataPackagesResponse => {
const parsedResponse: DataPackagesResponse = {};
RedstoneCommon.zodAssert<GwResponse>(GwResponseSchema, responseData);
const requestedDataFeedIds = reqParams.dataPackagesIds;
for (const dataFeedId of requestedDataFeedIds) {
let dataFeedPackages = responseData[dataFeedId];
if (!dataFeedPackages) {
Iif (reqParams.ignoreMissingFeed) {
continue;
}
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) {
Iif (reqParams.ignoreMissingFeed) {
continue;
}
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 getUrlsForDataServiceId = (
reqParams: DataPackagesRequestParams
): string[] => {
return reqParams.urls ?? resolveDataServiceUrls(reqParams.dataServiceId);
};
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.dataPackagesIds,
dataPackagesIds: reqParams.dataPackagesIds,
minimalSignersCount: reqParams.uniqueSignersCount,
},
paramsSerializer: { indexes: null },
});
}
function maybeGetSigner(dp: SignedDataPackagePlainObj) {
try {
return SignedDataPackage.fromObj(dp).recoverSignerAddress();
} catch {
return undefined;
}
}
export const chooseDataPackagesTimestamp = (
dataPackages: DataPackagesResponse,
dataFeedId?: string
) => {
const dataPackageTimestamps = dataFeedId
? dataPackages[dataFeedId]!.flatMap(
(dataPackage) => dataPackage.dataPackage.timestampMilliseconds
)
: Object.values(dataPackages).flatMap((dataPackages) =>
dataPackages!.map(
(dataPackage) => dataPackage.dataPackage.timestampMilliseconds
)
);
return Math.min(...dataPackageTimestamps);
};
|