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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 5x 5x 1x 17x 17x 17x 17x 17x 4x 4x 17x 35x 6x 6x 29x 21x 13x 13x 13x 21x 21x 17x 33x 17x 14x 1x 17x 17x 17x 17x 33x 20x 1x 20x 20x 19x 19x 22x 22x 1x 21x 1x 20x 17x 1x 20x 47x 20x 47x 45x 47x 1x 1x 1x 1x 1x 1x 17x 10x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {
redstoneOraclesInitialState,
RedstoneOraclesState,
} from "@redstone-finance/oracles-smartweave-contracts";
import {
consts,
INumericDataPoint,
RedstonePayload,
SignedDataPackage,
SignedDataPackagePlainObj,
} from "@redstone-finance/protocol";
import axios from "axios";
import { BigNumber } from "ethers";
import { resolveDataServiceUrls } from "./data-services-urls";
import { MathUtils, RedstoneCommon, SafeNumber } from "@redstone-finance/utils";
import { z } from "zod";
const GET_REQUEST_TIMEOUT = 10_000;
const WAIT_FOR_ALL_GATEWAYS_TIME = 600;
export interface DataPackagesRequestParams {
dataServiceId: string;
uniqueSignersCount: number;
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(),
}).or(z.object({
dataFeedId: z.string(),
value: z.string()
}))
)
.min(1),
timestampMilliseconds: z.number(),
signature: z.string(),
dataFeedId: z.string(),
})
)
);
export type GwResponse = z.infer<typeof GwResponseSchema>;
export const getOracleRegistryState =
async (): Promise<RedstoneOraclesState> => {
return await Promise.resolve(redstoneOraclesInitialState);
};
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 requestDataPackages = async (
reqParams: DataPackagesRequestParams
): Promise<DataPackagesResponse> => {
try {
const promises = prepareDataPackagePromises(reqParams);
Iif (reqParams.historicalTimestamp) {
return await Promise.any(promises);
}
return await getTheMostRecentDataPackages(promises);
} catch (e) {
const errMessage = `Request failed ${JSON.stringify({
reqParams,
})}, Original error: ${RedstoneCommon.stringifyError(e)}`;
throw new Error(errMessage);
}
};
const getTheMostRecentDataPackages = (
promises: Promise<DataPackagesResponse>[]
): Promise<DataPackagesResponse> => {
return new Promise((resolve, reject) => {
const collectedResponses: DataPackagesResponse[] = [];
const errors: Error[] = [];
let waitForAll = true;
const timer = setTimeout(() => {
waitForAll = false;
onResult();
}, WAIT_FOR_ALL_GATEWAYS_TIME);
const onResult = () => {
if (errors.length === promises.length) {
clearTimeout(timer);
reject(new AggregateError(errors));
} else if (
collectedResponses.length + errors.length === promises.length || !waitForAll && collectedResponses.length !== 0
) {
// assumption: all data packages from one url have same timestamp
collectedResponses.sort((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;
});
clearTimeout(timer);
resolve(collectedResponses[0]!);
}
};
for (const promise of promises) {
promise
.then((r) => collectedResponses.push(r))
.catch((e) => errors.push(e as Error))
.finally(onResult)
}
});
};
const prepareDataPackagePromises = (
reqParams: DataPackagesRequestParams
): Promise<DataPackagesResponse>[] => {
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) =>
axios
.get<Record<string, SignedDataPackagePlainObj[]>>(
[url.replace(/\/+$/, "")].concat(pathComponents).join("/"),
{ timeout: GET_REQUEST_TIMEOUT }
)
.then((response) => parseDataPackagesResponse(response.data, reqParams))
);
};
export const parseDataPackagesResponse = (
responseData: unknown,
reqParams: DataPackagesRequestParams
): DataPackagesResponse => {
const parsedResponse: DataPackagesResponse = {};
const dpResponse = GwResponseSchema.parse(responseData) as Partial<GwResponse>;
const requestedDataFeedIds = reqParams.dataFeeds ?? [consts.ALL_FEEDS_KEY];
for (const dataFeedId of requestedDataFeedIds) {
const dataFeedPackages = dpResponse[dataFeedId];
if (!dataFeedPackages) {
throw new Error(
`Requested data feed id is not included in response: ${dataFeedId}`
);
}
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 dataFeedPackages
.map((dp) => ({
dp: dp,
diff: SafeNumber.createSafeNumber(dp.dataPoints[0].value)
.sub(median)
.abs(),
}))
.sort((first, second) => first.diff.sub(second.diff).unsafeToNumber())
.map((diff) => SignedDataPackage.fromObj(diff.dp))
.slice(0, count);
};
export const getDecimalsForDataFeedId = (
dataPackages: SignedDataPackagePlainObj[]
) => {
const firstDecimal = (dataPackages[0].dataPoints[0] as INumericDataPoint)
.decimals;
const areAllDecimalsEqual = dataPackages.every((dataPackage) =>
dataPackage.dataPoints.every(
(dataPoint) => (dataPoint as INumericDataPoint).decimals === firstDecimal
)
);
Iif (!areAllDecimalsEqual) {
throw new Error("Decimals from data points in data packages are not equal");
}
return firstDecimal;
};
export const requestRedstonePayload = async (
reqParams: DataPackagesRequestParams,
unsignedMetadataMsg?: string
): Promise<string> => {
const signedDataPackagesResponse = await requestDataPackages(reqParams);
const signedDataPackages = Object.values(
signedDataPackagesResponse
).flat() as SignedDataPackage[];
return RedstonePayload.prepare(signedDataPackages, unsignedMetadataMsg || "");
};
export const getUrlsForDataServiceId = (
reqParams: DataPackagesRequestParams
): string[] => {
if (reqParams.urls) {
return reqParams.urls;
}
return resolveDataServiceUrls(reqParams.dataServiceId);
};
export default {
getOracleRegistryState,
requestDataPackages,
getDataServiceIdForSigner,
requestRedstonePayload,
resolveDataServiceUrls,
getDecimalsForDataFeedId,
};
export * from "./contracts/ContractParamsProvider";
export * from "./contracts/ContractParamsProviderMock";
export * from "./contracts/IContractConnector";
export * from "./contracts/prices/IPricesContractAdapter";
export * from "./data-feed-values";
export * from "./data-services-urls";
export * from "./fetch-data-packages";
export * from "./simple-relayer/IPriceFeedContractAdapter";
export * from "./simple-relayer/IPriceManagerContractAdapter";
export * from "./simple-relayer/start-simple-relayer";
|