Socket
Socket
Sign inDemoInstall

@near-js/providers

Package Overview
Dependencies
Maintainers
2
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@near-js/providers - npm Package Compare versions

Comparing version 0.2.2 to 0.3.0-next.0

37

lib/exponential-backoff.js

@@ -1,29 +0,14 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exponentialBackoff = void 0;
function exponentialBackoff(startWaitTime, retryNumber, waitBackoff, getResult) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: jitter?
let waitTime = startWaitTime;
for (let i = 0; i < retryNumber; i++) {
const result = yield getResult();
if (result) {
return result;
}
yield sleep(waitTime);
waitTime *= waitBackoff;
export async function exponentialBackoff(startWaitTime, retryNumber, waitBackoff, getResult) {
// TODO: jitter?
let waitTime = startWaitTime;
for (let i = 0; i < retryNumber; i++) {
const result = await getResult();
if (result) {
return result;
}
return null;
});
await sleep(waitTime);
waitTime *= waitBackoff;
}
return null;
}
exports.exponentialBackoff = exponentialBackoff;
// Sleep given number of millis.

@@ -30,0 +15,0 @@ function sleep(millis) {

@@ -1,13 +0,1 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FailoverRpcProvider = void 0;
/**

@@ -20,5 +8,5 @@ * @module

*/
const utils_1 = require("@near-js/utils");
const types_1 = require("@near-js/types");
const provider_1 = require("./provider");
import { Logger } from '@near-js/utils';
import { TypedError, } from '@near-js/types';
import { Provider } from './provider';
/**

@@ -28,3 +16,6 @@ * Client class to interact with the [NEAR RPC API](https://docs.near.org/api/rpc/introduction).

*/
class FailoverRpcProvider extends provider_1.Provider {
export class FailoverRpcProvider extends Provider {
/** @hidden */
providers;
currentProviderIndex;
/**

@@ -50,3 +41,3 @@ * @param providers list of providers

}
utils_1.Logger.debug(`Switched to provider at the index ${this.currentProviderIndex}`);
Logger.debug(`Switched to provider at the index ${this.currentProviderIndex}`);
}

@@ -59,17 +50,15 @@ get currentProvider() {

}
withBackoff(getResult) {
return __awaiter(this, void 0, void 0, function* () {
for (let i = 0; i < this.providers.length; i++) {
try {
// each provider implements own retry logic
const result = yield getResult(this.currentProvider);
if (result)
return result;
}
catch (_a) {
this.switchToNextProvider();
}
async withBackoff(getResult) {
for (let i = 0; i < this.providers.length; i++) {
try {
// each provider implements own retry logic
const result = await getResult(this.currentProvider);
if (result)
return result;
}
throw new types_1.TypedError(`Exceeded ${this.providers.length} providers to execute request`, 'RetriesExceeded');
});
catch {
this.switchToNextProvider();
}
}
throw new TypedError(`Exceeded ${this.providers.length} providers to execute request`, 'RetriesExceeded');
}

@@ -80,11 +69,7 @@ /**

*/
status() {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.status());
});
async status() {
return this.withBackoff((currentProvider) => currentProvider.status());
}
sendTransactionUntil(signedTransaction, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionUntil(signedTransaction, waitUntil));
});
async sendTransactionUntil(signedTransaction, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionUntil(signedTransaction, waitUntil));
}

@@ -97,6 +82,4 @@ /**

*/
sendTransaction(signedTransaction) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.sendTransaction(signedTransaction));
});
async sendTransaction(signedTransaction) {
return this.withBackoff((currentProvider) => currentProvider.sendTransaction(signedTransaction));
}

@@ -109,6 +92,4 @@ /**

*/
sendTransactionAsync(signedTransaction) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionAsync(signedTransaction));
});
async sendTransactionAsync(signedTransaction) {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionAsync(signedTransaction));
}

@@ -122,6 +103,4 @@ /**

*/
txStatus(txHash, accountId, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.txStatus(txHash, accountId, waitUntil));
});
async txStatus(txHash, accountId, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.txStatus(txHash, accountId, waitUntil));
}

@@ -135,14 +114,10 @@ /**

*/
txStatusReceipts(txHash, accountId, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.txStatusReceipts(txHash, accountId, waitUntil));
});
async txStatusReceipts(txHash, accountId, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.txStatusReceipts(txHash, accountId, waitUntil));
}
query(paramsOrPath, data) {
return __awaiter(this, void 0, void 0, function* () {
if (data) {
return this.withBackoff((currentProvider) => currentProvider.query(paramsOrPath, data));
}
return this.withBackoff((currentProvider) => currentProvider.query(paramsOrPath));
});
async query(paramsOrPath, data) {
if (data) {
return this.withBackoff((currentProvider) => currentProvider.query(paramsOrPath, data));
}
return this.withBackoff((currentProvider) => currentProvider.query(paramsOrPath));
}

@@ -156,6 +131,4 @@ /**

*/
block(blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.block(blockQuery));
});
async block(blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.block(blockQuery));
}

@@ -167,6 +140,4 @@ /**

*/
blockChanges(blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.blockChanges(blockQuery));
});
async blockChanges(blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.blockChanges(blockQuery));
}

@@ -179,6 +150,4 @@ /**

*/
chunk(chunkId) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.chunk(chunkId));
});
async chunk(chunkId) {
return this.withBackoff((currentProvider) => currentProvider.chunk(chunkId));
}

@@ -191,6 +160,4 @@ /**

*/
validators(blockId) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.validators(blockId));
});
async validators(blockId) {
return this.withBackoff((currentProvider) => currentProvider.validators(blockId));
}

@@ -202,6 +169,4 @@ /**

*/
experimental_protocolConfig(blockReference) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.experimental_protocolConfig(blockReference));
});
async experimental_protocolConfig(blockReference) {
return this.withBackoff((currentProvider) => currentProvider.experimental_protocolConfig(blockReference));
}

@@ -212,6 +177,4 @@ /**

*/
lightClientProof(request) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.lightClientProof(request));
});
async lightClientProof(request) {
return this.withBackoff((currentProvider) => currentProvider.lightClientProof(request));
}

@@ -225,6 +188,4 @@ /**

*/
nextLightClientBlock(request) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.nextLightClientBlock(request));
});
async nextLightClientBlock(request) {
return this.withBackoff((currentProvider) => currentProvider.nextLightClientBlock(request));
}

@@ -236,6 +197,4 @@ /**

*/
accessKeyChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.accessKeyChanges(accountIdArray, blockQuery));
});
async accessKeyChanges(accountIdArray, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.accessKeyChanges(accountIdArray, blockQuery));
}

@@ -248,6 +207,4 @@ /**

*/
singleAccessKeyChanges(accessKeyArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.singleAccessKeyChanges(accessKeyArray, blockQuery));
});
async singleAccessKeyChanges(accessKeyArray, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.singleAccessKeyChanges(accessKeyArray, blockQuery));
}

@@ -260,6 +217,4 @@ /**

*/
accountChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.accountChanges(accountIdArray, blockQuery));
});
async accountChanges(accountIdArray, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.accountChanges(accountIdArray, blockQuery));
}

@@ -273,6 +228,4 @@ /**

*/
contractStateChanges(accountIdArray, blockQuery, keyPrefix = '') {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.contractStateChanges(accountIdArray, blockQuery, keyPrefix));
});
async contractStateChanges(accountIdArray, blockQuery, keyPrefix = '') {
return this.withBackoff((currentProvider) => currentProvider.contractStateChanges(accountIdArray, blockQuery, keyPrefix));
}

@@ -286,6 +239,4 @@ /**

*/
contractCodeChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.contractCodeChanges(accountIdArray, blockQuery));
});
async contractCodeChanges(accountIdArray, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.contractCodeChanges(accountIdArray, blockQuery));
}

@@ -298,8 +249,5 @@ /**

*/
gasPrice(blockId) {
return __awaiter(this, void 0, void 0, function* () {
return this.withBackoff((currentProvider) => currentProvider.gasPrice(blockId));
});
async gasPrice(blockId) {
return this.withBackoff((currentProvider) => currentProvider.gasPrice(blockId));
}
}
exports.FailoverRpcProvider = FailoverRpcProvider;
export interface ConnectionInfo {
url: string;
user?: string;
password?: string;
allowInsecure?: boolean;
timeout?: number;
headers?: {

@@ -11,9 +7,17 @@ [key: string]: string | number;

}
interface JsonRpcRequest {
id: number;
jsonrpc: string;
method: string;
params: object;
}
/**
* Performs an HTTP request to a specified URL or connection and returns the parsed JSON response.
* @param connectionInfoOrUrl The connection information or URL for the HTTP request.
* @param json The JSON payload to be included in the request body for POST requests.
* @returns A Promise that resolves to the parsed JSON response from the HTTP request.
* Performs an HTTP request to an RPC endpoint
* @param url URL for the HTTP request
* @param json Request body
* @param headers HTTP headers to include with the request
* @returns Promise<any> }arsed JSON response from the HTTP request.
*/
export declare function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, json?: string): Promise<any>;
export declare function fetchJsonRpc(url: string, json: JsonRpcRequest, headers: object): Promise<any>;
export {};
//# sourceMappingURL=fetch_json.d.ts.map

@@ -1,96 +0,55 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
import { TypedError } from '@near-js/types';
import { backOff } from 'exponential-backoff';
import unfetch from 'isomorphic-unfetch';
const BACKOFF_MULTIPLIER = 1.5;
const RETRY_NUMBER = 10;
const retryConfig = {
numOfAttempts: RETRY_NUMBER,
timeMultiple: BACKOFF_MULTIPLIER,
retry: (e) => {
if ([503, 408].includes(e.cause)) {
return true;
}
if (['FetchError', 'Failed to fetch'].includes(e.toString())) {
return true;
}
return false;
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchJson = void 0;
const types_1 = require("@near-js/types");
const utils_1 = require("@near-js/utils");
const http_errors_1 = __importDefault(require("http-errors"));
const exponential_backoff_1 = require("./exponential-backoff");
const START_WAIT_TIME_MS = 1000;
const BACKOFF_MULTIPLIER = 1.5;
const RETRY_NUMBER = 10;
class ProviderError extends Error {
cause;
constructor(message, options) {
super(message, options);
}
}
/**
* Performs an HTTP request to a specified URL or connection and returns the parsed JSON response.
* @param connectionInfoOrUrl The connection information or URL for the HTTP request.
* @param json The JSON payload to be included in the request body for POST requests.
* @returns A Promise that resolves to the parsed JSON response from the HTTP request.
* Performs an HTTP request to an RPC endpoint
* @param url URL for the HTTP request
* @param json Request body
* @param headers HTTP headers to include with the request
* @returns Promise<any> }arsed JSON response from the HTTP request.
*/
function fetchJson(connectionInfoOrUrl, json) {
return __awaiter(this, void 0, void 0, function* () {
let connectionInfo = { url: null };
if (typeof (connectionInfoOrUrl) === 'string') {
connectionInfo.url = connectionInfoOrUrl;
export async function fetchJsonRpc(url, json, headers) {
const response = await backOff(async () => {
const res = await unfetch(url, {
method: 'POST',
body: JSON.stringify(json),
headers: { ...headers, 'Content-Type': 'application/json' }
});
const { ok, status } = res;
if (!ok) {
throw new ProviderError(await res.text(), { cause: status });
}
else {
connectionInfo = connectionInfoOrUrl;
if (status === 503) {
throw new ProviderError(`${url} unavailable`, { cause: status });
}
const response = yield (0, exponential_backoff_1.exponentialBackoff)(START_WAIT_TIME_MS, RETRY_NUMBER, BACKOFF_MULTIPLIER, () => __awaiter(this, void 0, void 0, function* () {
var _a;
try {
const response = yield ((_a = global.fetch) !== null && _a !== void 0 ? _a : (yield Promise.resolve().then(() => __importStar(require('./fetch')))).default)(connectionInfo.url, {
method: json ? 'POST' : 'GET',
body: json ? json : undefined,
headers: Object.assign(Object.assign({}, connectionInfo.headers), { 'Content-Type': 'application/json' })
});
if (!response.ok) {
if (response.status === 503) {
utils_1.Logger.warn(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`);
return null;
}
else if (response.status === 408) {
utils_1.Logger.warn(`Retrying HTTP request for ${connectionInfo.url} as the previous connection was unused for some time`);
return null;
}
throw (0, http_errors_1.default)(response.status, yield response.text());
}
return response;
}
catch (error) {
if (error.toString().includes('FetchError') || error.toString().includes('Failed to fetch')) {
utils_1.Logger.warn(`Retrying HTTP request for ${connectionInfo.url} because of error: ${error}`);
return null;
}
throw error;
}
}));
if (!response) {
throw new types_1.TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${connectionInfo.url}.`, 'RetriesExceeded');
else if (status === 408) {
throw new ProviderError('Unused connection', { cause: status });
}
return yield response.json();
});
return res;
}, retryConfig);
if (!response) {
throw new TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${url}.`, 'RetriesExceeded');
}
return await response.json();
}
exports.fetchJson = fetchJson;

@@ -5,3 +5,2 @@ export { exponentialBackoff } from './exponential-backoff';

export { Provider } from './provider';
export { fetchJson } from './fetch_json';
//# sourceMappingURL=index.d.ts.map

@@ -1,13 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchJson = exports.Provider = exports.FailoverRpcProvider = exports.JsonRpcProvider = exports.exponentialBackoff = void 0;
var exponential_backoff_1 = require("./exponential-backoff");
Object.defineProperty(exports, "exponentialBackoff", { enumerable: true, get: function () { return exponential_backoff_1.exponentialBackoff; } });
var json_rpc_provider_1 = require("./json-rpc-provider");
Object.defineProperty(exports, "JsonRpcProvider", { enumerable: true, get: function () { return json_rpc_provider_1.JsonRpcProvider; } });
var failover_rpc_provider_1 = require("./failover-rpc-provider");
Object.defineProperty(exports, "FailoverRpcProvider", { enumerable: true, get: function () { return failover_rpc_provider_1.FailoverRpcProvider; } });
var provider_1 = require("./provider");
Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return provider_1.Provider; } });
var fetch_json_1 = require("./fetch_json");
Object.defineProperty(exports, "fetchJson", { enumerable: true, get: function () { return fetch_json_1.fetchJson; } });
export { exponentialBackoff } from './exponential-backoff';
export { JsonRpcProvider } from './json-rpc-provider';
export { FailoverRpcProvider } from './failover-rpc-provider';
export { Provider } from './provider';

@@ -1,24 +0,1 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonRpcProvider = void 0;
/**

@@ -31,8 +8,8 @@ * @module

*/
const utils_1 = require("@near-js/utils");
const types_1 = require("@near-js/types");
const transactions_1 = require("@near-js/transactions");
const exponential_backoff_1 = require("./exponential-backoff");
const provider_1 = require("./provider");
const fetch_json_1 = require("./fetch_json");
import { baseEncode, formatError, getErrorTypeFromErrorMessage, Logger, parseRpcError, ServerError, } from '@near-js/utils';
import { TypedError, } from '@near-js/types';
import { encodeTransaction, } from '@near-js/transactions';
import { exponentialBackoff } from './exponential-backoff';
import { Provider } from './provider';
import { fetchJsonRpc } from './fetch_json';
/** @hidden */

@@ -51,3 +28,7 @@ // Default number of retries before giving up on a request.

*/
class JsonRpcProvider extends provider_1.Provider {
export class JsonRpcProvider extends Provider {
/** @hidden */
connection;
/** @hidden */
options;
/**

@@ -70,6 +51,4 @@ * @param connectionInfo Connection info

*/
status() {
return __awaiter(this, void 0, void 0, function* () {
return this.sendJsonRpc('status', []);
});
async status() {
return this.sendJsonRpc('status', []);
}

@@ -82,7 +61,5 @@ /**

*/
sendTransactionUntil(signedTransaction, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
const bytes = (0, transactions_1.encodeTransaction)(signedTransaction);
return this.sendJsonRpc('send_tx', { signed_tx_base64: Buffer.from(bytes).toString('base64'), wait_until: waitUntil });
});
async sendTransactionUntil(signedTransaction, waitUntil) {
const bytes = encodeTransaction(signedTransaction);
return this.sendJsonRpc('send_tx', { signed_tx_base64: Buffer.from(bytes).toString('base64'), wait_until: waitUntil });
}

@@ -95,6 +72,4 @@ /**

*/
sendTransaction(signedTransaction) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendTransactionUntil(signedTransaction, 'EXECUTED_OPTIMISTIC');
});
async sendTransaction(signedTransaction) {
return this.sendTransactionUntil(signedTransaction, 'EXECUTED_OPTIMISTIC');
}

@@ -107,6 +82,4 @@ /**

*/
sendTransactionAsync(signedTransaction) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendTransactionUntil(signedTransaction, 'NONE');
});
async sendTransactionAsync(signedTransaction) {
return this.sendTransactionUntil(signedTransaction, 'NONE');
}

@@ -121,21 +94,15 @@ /**

*/
txStatus(txHash, accountId, waitUntil = 'EXECUTED_OPTIMISTIC') {
return __awaiter(this, void 0, void 0, function* () {
if (typeof txHash === 'string') {
return this.txStatusString(txHash, accountId, waitUntil);
}
else {
return this.txStatusUint8Array(txHash, accountId, waitUntil);
}
});
async txStatus(txHash, accountId, waitUntil = 'EXECUTED_OPTIMISTIC') {
if (typeof txHash === 'string') {
return this.txStatusString(txHash, accountId, waitUntil);
}
else {
return this.txStatusUint8Array(txHash, accountId, waitUntil);
}
}
txStatusUint8Array(txHash, accountId, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendJsonRpc('tx', { tx_hash: (0, utils_1.baseEncode)(txHash), sender_account_id: accountId, wait_until: waitUntil });
});
async txStatusUint8Array(txHash, accountId, waitUntil) {
return this.sendJsonRpc('tx', { tx_hash: baseEncode(txHash), sender_account_id: accountId, wait_until: waitUntil });
}
txStatusString(txHash, accountId, waitUntil) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendJsonRpc('tx', { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
});
async txStatusString(txHash, accountId, waitUntil) {
return this.sendJsonRpc('tx', { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
}

@@ -150,11 +117,9 @@ /**

*/
txStatusReceipts(txHash, accountId, waitUntil = 'EXECUTED_OPTIMISTIC') {
return __awaiter(this, void 0, void 0, function* () {
if (typeof txHash === 'string') {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
}
else {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', { tx_hash: (0, utils_1.baseEncode)(txHash), sender_account_id: accountId, wait_until: waitUntil });
}
});
async txStatusReceipts(txHash, accountId, waitUntil = 'EXECUTED_OPTIMISTIC') {
if (typeof txHash === 'string') {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
}
else {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', { tx_hash: baseEncode(txHash), sender_account_id: accountId, wait_until: waitUntil });
}
}

@@ -167,18 +132,16 @@ /**

*/
query(...args) {
return __awaiter(this, void 0, void 0, function* () {
let result;
if (args.length === 1) {
const _a = args[0], { block_id, blockId } = _a, otherParams = __rest(_a, ["block_id", "blockId"]);
result = yield this.sendJsonRpc('query', Object.assign(Object.assign({}, otherParams), { block_id: block_id || blockId }));
}
else {
const [path, data] = args;
result = yield this.sendJsonRpc('query', [path, data]);
}
if (result && result.error) {
throw new types_1.TypedError(`Querying failed: ${result.error}.\n${JSON.stringify(result, null, 2)}`, (0, utils_1.getErrorTypeFromErrorMessage)(result.error, result.error.name));
}
return result;
});
async query(...args) {
let result;
if (args.length === 1) {
const { block_id, blockId, ...otherParams } = args[0];
result = await this.sendJsonRpc('query', { ...otherParams, block_id: block_id || blockId });
}
else {
const [path, data] = args;
result = await this.sendJsonRpc('query', [path, data]);
}
if (result && result.error) {
throw new TypedError(`Querying failed: ${result.error}.\n${JSON.stringify(result, null, 2)}`, getErrorTypeFromErrorMessage(result.error, result.error.name));
}
return result;
}

@@ -192,8 +155,6 @@ /**

*/
block(blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('block', { block_id: blockId, finality });
});
async block(blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('block', { block_id: blockId, finality });
}

@@ -205,8 +166,6 @@ /**

*/
blockChanges(blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes_in_block', { block_id: blockId, finality });
});
async blockChanges(blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes_in_block', { block_id: blockId, finality });
}

@@ -219,6 +178,4 @@ /**

*/
chunk(chunkId) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendJsonRpc('chunk', [chunkId]);
});
async chunk(chunkId) {
return this.sendJsonRpc('chunk', [chunkId]);
}

@@ -231,6 +188,4 @@ /**

*/
validators(blockId) {
return __awaiter(this, void 0, void 0, function* () {
return this.sendJsonRpc('validators', [blockId]);
});
async validators(blockId) {
return this.sendJsonRpc('validators', [blockId]);
}

@@ -242,7 +197,5 @@ /**

*/
experimental_protocolConfig(blockReference) {
return __awaiter(this, void 0, void 0, function* () {
const _a = blockReference, { blockId } = _a, otherParams = __rest(_a, ["blockId"]);
return yield this.sendJsonRpc('EXPERIMENTAL_protocol_config', Object.assign(Object.assign({}, otherParams), { block_id: blockId }));
});
async experimental_protocolConfig(blockReference) {
const { blockId, ...otherParams } = blockReference;
return await this.sendJsonRpc('EXPERIMENTAL_protocol_config', { ...otherParams, block_id: blockId });
}

@@ -253,6 +206,4 @@ /**

*/
lightClientProof(request) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.sendJsonRpc('EXPERIMENTAL_light_client_proof', request);
});
async lightClientProof(request) {
return await this.sendJsonRpc('EXPERIMENTAL_light_client_proof', request);
}

@@ -266,6 +217,4 @@ /**

*/
nextLightClientBlock(request) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.sendJsonRpc('next_light_client_block', request);
});
async nextLightClientBlock(request) {
return await this.sendJsonRpc('next_light_client_block', request);
}

@@ -277,12 +226,10 @@ /**

*/
accessKeyChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'all_access_key_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
async accessKeyChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'all_access_key_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});

@@ -296,12 +243,10 @@ }

*/
singleAccessKeyChanges(accessKeyArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'single_access_key_changes',
keys: accessKeyArray,
block_id: blockId,
finality
});
async singleAccessKeyChanges(accessKeyArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'single_access_key_changes',
keys: accessKeyArray,
block_id: blockId,
finality
});

@@ -315,12 +260,10 @@ }

*/
accountChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'account_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
async accountChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'account_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});

@@ -335,13 +278,11 @@ }

*/
contractStateChanges(accountIdArray, blockQuery, keyPrefix = '') {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'data_changes',
account_ids: accountIdArray,
key_prefix_base64: keyPrefix,
block_id: blockId,
finality
});
async contractStateChanges(accountIdArray, blockQuery, keyPrefix = '') {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'data_changes',
account_ids: accountIdArray,
key_prefix_base64: keyPrefix,
block_id: blockId,
finality
});

@@ -356,12 +297,10 @@ }

*/
contractCodeChanges(accountIdArray, blockQuery) {
return __awaiter(this, void 0, void 0, function* () {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'contract_code_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
async contractCodeChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'contract_code_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});

@@ -375,6 +314,4 @@ }

*/
gasPrice(blockId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.sendJsonRpc('gas_price', [blockId]);
});
async gasPrice(blockId) {
return await this.sendJsonRpc('gas_price', [blockId]);
}

@@ -387,66 +324,62 @@ /**

*/
sendJsonRpc(method, params) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield (0, exponential_backoff_1.exponentialBackoff)(this.options.wait, this.options.retries, this.options.backoff, () => __awaiter(this, void 0, void 0, function* () {
var _a;
try {
const request = {
method,
params,
id: (_nextId++),
jsonrpc: '2.0'
};
const response = yield (0, fetch_json_1.fetchJson)(this.connection, JSON.stringify(request));
if (response.error) {
if (typeof response.error.data === 'object') {
if (typeof response.error.data.error_message === 'string' && typeof response.error.data.error_type === 'string') {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
throw new types_1.TypedError(response.error.data.error_message, response.error.data.error_type);
}
throw (0, utils_1.parseRpcError)(response.error.data);
async sendJsonRpc(method, params) {
const response = await exponentialBackoff(this.options.wait, this.options.retries, this.options.backoff, async () => {
try {
const request = {
method,
params,
id: (_nextId++),
jsonrpc: '2.0'
};
const response = await fetchJsonRpc(this.connection.url, request, this.connection.headers);
if (response.error) {
if (typeof response.error.data === 'object') {
if (typeof response.error.data.error_message === 'string' && typeof response.error.data.error_type === 'string') {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
throw new TypedError(response.error.data.error_message, response.error.data.error_type);
}
else {
const errorMessage = `[${response.error.code}] ${response.error.message}: ${response.error.data}`;
// NOTE: All this hackery is happening because structured errors not implemented
// TODO: Fix when https://github.com/nearprotocol/nearcore/issues/1839 gets resolved
if (response.error.data === 'Timeout' || errorMessage.includes('Timeout error')
|| errorMessage.includes('query has timed out')) {
throw new types_1.TypedError(errorMessage, 'TimeoutError');
}
const errorType = (0, utils_1.getErrorTypeFromErrorMessage)(response.error.data, '');
if (errorType) {
throw new types_1.TypedError((0, utils_1.formatError)(errorType, params), errorType);
}
throw new types_1.TypedError(errorMessage, response.error.name);
throw parseRpcError(response.error.data);
}
else {
const errorMessage = `[${response.error.code}] ${response.error.message}: ${response.error.data}`;
// NOTE: All this hackery is happening because structured errors not implemented
// TODO: Fix when https://github.com/nearprotocol/nearcore/issues/1839 gets resolved
if (response.error.data === 'Timeout' || errorMessage.includes('Timeout error')
|| errorMessage.includes('query has timed out')) {
throw new TypedError(errorMessage, 'TimeoutError');
}
}
else if (typeof ((_a = response.result) === null || _a === void 0 ? void 0 : _a.error) === 'string') {
const errorType = (0, utils_1.getErrorTypeFromErrorMessage)(response.result.error, '');
const errorType = getErrorTypeFromErrorMessage(response.error.data, '');
if (errorType) {
throw new utils_1.ServerError((0, utils_1.formatError)(errorType, params), errorType);
throw new TypedError(formatError(errorType, params), errorType);
}
throw new TypedError(errorMessage, response.error.name);
}
// Success when response.error is not exist
return response;
}
catch (error) {
if (error.type === 'TimeoutError') {
utils_1.Logger.warn(`Retrying request to ${method} as it has timed out`, params);
return null;
else if (typeof response.result?.error === 'string') {
const errorType = getErrorTypeFromErrorMessage(response.result.error, '');
if (errorType) {
throw new ServerError(formatError(errorType, params), errorType);
}
throw error;
}
}));
const { result } = response;
// From jsonrpc spec:
// result
// This member is REQUIRED on success.
// This member MUST NOT exist if there was an error invoking the method.
if (typeof result === 'undefined') {
throw new types_1.TypedError(`Exceeded ${this.options.retries} attempts for request to ${method}.`, 'RetriesExceeded');
// Success when response.error is not exist
return response;
}
return result;
catch (error) {
if (error.type === 'TimeoutError') {
Logger.warn(`Retrying request to ${method} as it has timed out`, params);
return null;
}
throw error;
}
});
const { result } = response;
// From jsonrpc spec:
// result
// This member is REQUIRED on success.
// This member MUST NOT exist if there was an error invoking the method.
if (typeof result === 'undefined') {
throw new TypedError(`Exceeded ${this.options.retries} attempts for request to ${method}.`, 'RetriesExceeded');
}
return result;
}
}
exports.JsonRpcProvider = JsonRpcProvider;

@@ -1,2 +0,1 @@

"use strict";
/**

@@ -6,7 +5,4 @@ * NEAR RPC API request types and responses

*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Provider = void 0;
/** @hidden */
class Provider {
export class Provider {
}
exports.Provider = Provider;
{
"name": "@near-js/providers",
"version": "0.2.2",
"version": "0.3.0-next.0",
"description": "Library of implementations for interfacing with the NEAR blockchain",
"main": "lib/index.js",
"type": "module",
"keywords": [],

@@ -11,13 +12,16 @@ "author": "",

"borsh": "1.0.0",
"http-errors": "1.7.2",
"@near-js/transactions": "1.2.2",
"@near-js/types": "0.2.1",
"@near-js/utils": "0.2.2"
"exponential-backoff": "^3.1.1",
"isomorphic-unfetch": "^3.1.0",
"@near-js/transactions": "1.3.0-next.0",
"@near-js/types": "0.3.0-next.0",
"@near-js/utils": "0.3.0-next.0"
},
"devDependencies": {
"@types/node": "18.11.18",
"jest": "26.0.1",
"@jest/globals": "^29.7.0",
"@types/node": "20.0.0",
"jest": "29.7.0",
"near-workspaces": "3.5.0",
"ts-jest": "26.5.6",
"typescript": "4.9.4"
"ts-jest": "29.1.5",
"typescript": "5.4.5",
"tsconfig": "0.0.0"
},

@@ -37,8 +41,6 @@ "optionalDependencies": {

"compile": "tsc -p tsconfig.json",
"lint:js": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc",
"lint:js:fix": "eslint -c ../../.eslintrc.js.yml test/**/*.js --no-eslintrc --fix",
"lint:ts": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc",
"lint:ts:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts --no-eslintrc --fix",
"test": "jest test"
"lint": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts test/**/*.ts --no-eslintrc",
"lint:fix": "eslint -c ../../.eslintrc.ts.yml src/**/*.ts test/**/*.ts --no-eslintrc --fix",
"test": "jest"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc