How to use the @0x/utils.fetchAsync function in @0x/utils

To help you get started, we’ve selected a few @0x/utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / ohlcv_external / crypto_compare.ts View on Github external
const fetchPromise: Promise = this._promiseLimit(() => {
            // tslint:disable-next-line:no-console
            console.log(`Scraping Crypto Compare at ${url}`);
            return fetchAsync(url);
        });
github 0xProject / 0x-monorepo / packages / website / ts / utils / doc_utils.ts View on Github external
async getJSONDocFileAsync(filePath: string, s3DocJsonRoot: string): Promise {
        const endpoint = `${s3DocJsonRoot}/${filePath}`;
        const response = await fetchAsync(endpoint);
        if (response.status !== 200) {
            // TODO: Show the user an error message when the docs fail to load
            const errMsg = await response.text();
            logUtils.log(`Failed to load Doc JSON: ${response.status} ${errMsg}`);
            throw new Error(errMsg);
        }
        const jsonDocObj = await response.json();
        return jsonDocObj;
    },
};
github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / dex_prices / index.ts View on Github external
public async getEdpsAsync(direction: string, symbol: string, amount: number): Promise {
        const edpsUrl = `${EDPS_BASE_URL}/${direction}?amount=${amount}&symbol=${symbol}&decimals=`;
        const resp = await fetchAsync(edpsUrl);
        const respJson: EdpsResponse = await resp.json();
        const allExchanges: EdpsWrapper = {};
        // The below unwraps the response so we get 1 single EdpsWrapper object
        // instead of a list of singletons
        for (const entry of respJson) {
            for (const key of Object.keys(entry)) {
                allExchanges[key] = entry[key];
            }
        }
        return allExchanges;
    }
}
github 0xProject / 0x-monorepo / packages / pipeline / src / utils / get_ohlcv_trading_pairs.ts View on Github external
const latestTradingPairsIndex: { [fromSym: string]: { [toSym: string]: number } } = {};
    latestTradingPairs.forEach(pair => {
        const latestIndex: { [toSym: string]: number } = latestTradingPairsIndex[pair.from_symbol] || {};
        latestIndex[pair.to_symbol] = parseInt(pair.latest, 10); // tslint:disable-line:custom-no-magic-numbers
        latestTradingPairsIndex[pair.from_symbol] = latestIndex;
    });

    // match time to special cases
    const specialCases: TradingPair[] = SPECIAL_CASES.map(pair => {
        const latestSavedTime =
            R.path([pair.fromSymbol, pair.toSymbol], latestTradingPairsIndex) || earliestBackfillTime;
        return R.assoc('latestSavedTime', latestSavedTime, pair);
    });

    // get token symbols used by Crypto Compare
    const allCoinsResp = await fetchAsync(COINLIST_API);
    if (allCoinsResp.status !== HTTP_OK_STATUS) {
        return [];
    }
    const allCoins: CryptoCompareCoinListResp = await allCoinsResp.json();
    const erc20CoinsIndex: Map = new Map();
    Object.entries(allCoins.Data).forEach(pair => {
        const [symbol, coinData] = pair;
        if (coinData.BuiltOn === ETHEREUM_IDENTIFIER && coinData.SmartContractAddress !== 'N/A') {
            erc20CoinsIndex.set(coinData.SmartContractAddress.toLowerCase(), symbol);
        }
    });

    // fetch all tokens that are traded on 0x
    const rawEventTokenAddresses: Array<{ tokenaddress: string }> = await conn.query(
        `SELECT DISTINCT(maker_token_address) as tokenaddress FROM raw.exchange_fill_events UNION
      SELECT DISTINCT(taker_token_address) as tokenaddress FROM raw.exchange_fill_events`,
github 0xProject / 0x-monorepo / contracts / coordinator / src / client / index.ts View on Github external
private async _executeServerRequestAsync(
        signedTransaction: SignedZeroExTransaction,
        txOrigin: string,
        endpoint: string,
    ): Promise {
        const requestPayload = {
            signedTransaction,
            txOrigin,
        };
        const response = await fetchAsync(`${endpoint}/v2/request_transaction?chainId=${this.chainId}`, {
            body: JSON.stringify(requestPayload),
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
            },
        });

        const isError = response.status !== HttpStatus.OK;
        const isValidationError = response.status === HttpStatus.BAD_REQUEST;
        const json = isError && !isValidationError ? undefined : await response.json();

        const result = {
            isError,
            status: response.status,
            body: isError ? undefined : json,
            error: isError ? json : undefined,
github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / paradex / index.ts View on Github external
public async getTokenInfoAsync(): Promise {
        logUtils.log('Getting token information from Paradex.');
        const resp = await fetchAsync(TOKEN_INFO_ENDPOINT, {
            headers: { 'API-KEY': this._apiKey },
        });
        const tokens: ParadexTokenInfoResponse = await resp.json();
        logUtils.log(`Got information for ${tokens.length} tokens.`);
        return tokens;
    }
github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / ddex / index.ts View on Github external
public async getActiveMarketsAsync(): Promise {
        logUtils.log('Getting all active DDEX markets');
        const resp = await fetchAsync(ACTIVE_MARKETS_URL);
        const respJson: DdexActiveMarketsResponse = await resp.json();
        const markets = respJson.data.markets;
        logUtils.log(`Got ${markets.length} markets.`);
        return markets;
    }
github 0xProject / 0x-monorepo / packages / pipeline / src / data_sources / github / index.ts View on Github external
        const resp = await this._limiter.schedule(() => fetchAsync(url));
        const respJson: GithubRepoResponse = await resp.json();
github 0xProject / 0x-monorepo / packages / connect / src / http_client.ts View on Github external
private async _requestAsync(
        path: string,
        requestType: HttpRequestType,
        requestOptions?: HttpRequestOptions,
    ): Promise {
        const params = _.get(requestOptions, 'params');
        const payload = _.get(requestOptions, 'payload');
        const query = HttpClient._buildQueryStringFromHttpParams(params);
        const url = `${this._apiEndpointUrl}${path}${query}`;
        const headers = new Headers({
            'content-type': 'application/json',
        });
        const response = await fetchAsync(url, {
            method: requestType,
            body: JSON.stringify(payload),
            headers,
        });
        const text = await response.text();
        if (!response.ok) {
            const errorString = `${response.status} - ${response.statusText}\n${requestType} ${url}\n${text}`;
            throw Error(errorString);
        }
        const result = !_.isEmpty(text) ? JSON.parse(text) : undefined;
        return result;
    }
}