Socket
Socket
Sign inDemoInstall

near-api-js

Package Overview
Dependencies
Maintainers
1
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

near-api-js - npm Package Compare versions

Comparing version 0.25.1 to 0.26.0

.github/ISSUE_TEMPLATE/bug_report.md

9

lib/account.js

@@ -17,6 +17,7 @@ 'use strict';

// the originator.
// Default value is set to equal to max_prepaid_gas as discussed here:
// https://github.com/near/near-api-js/pull/191#discussion_r369671912
const DEFAULT_FUNC_CALL_GAS = new bn_js_1.default('10000000000000000');
// Default number of retries before giving up on a transactioin.
// Due to protocol changes that charge upfront for the maximum possible gas price inflation due to
// full blocks, the price of max_prepaid_gas is decreased to `300 * 10**12`.
// For discussion see https://github.com/nearprotocol/NEPs/issues/67
const DEFAULT_FUNC_CALL_GAS = new bn_js_1.default('300000000000000');
// Default number of retries before giving up on a transaction.
const TX_STATUS_RETRY_NUMBER = 10;

@@ -23,0 +24,0 @@ // Default wait until next retry in millis.

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

import * as providers from './providers';
import * as utils from './utils';
import * as keyStores from './key_stores/browser-index';
import * as transactions from './transaction';
import { Account } from './account';
import * as accountCreator from './account_creator';
import { Connection } from './connection';
import { Signer, InMemorySigner } from './signer';
import { Contract } from './contract';
import { KeyPair } from './utils/key_pair';
import { connect } from './near';
import { WalletAccount, WalletConnection } from './wallet-account';
export { accountCreator, keyStores, providers, utils, transactions, Account, Connection, Contract, InMemorySigner, Signer, KeyPair, connect, WalletAccount, WalletConnection };
export * as keyStores from './key_stores/browser-index';
export * from './common-index';

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

'use strict';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -17,34 +17,11 @@ if (k2 === undefined) k2 = k;

var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalletConnection = exports.WalletAccount = exports.connect = exports.KeyPair = exports.Signer = exports.InMemorySigner = exports.Contract = exports.Connection = exports.Account = exports.transactions = exports.utils = exports.providers = exports.keyStores = exports.accountCreator = void 0;
const providers = __importStar(require("./providers"));
exports.providers = providers;
const utils = __importStar(require("./utils"));
exports.utils = utils;
const keyStores = __importStar(require("./key_stores/browser-index"));
exports.keyStores = keyStores;
const transactions = __importStar(require("./transaction"));
exports.transactions = transactions;
const account_1 = require("./account");
Object.defineProperty(exports, "Account", { enumerable: true, get: function () { return account_1.Account; } });
const accountCreator = __importStar(require("./account_creator"));
exports.accountCreator = accountCreator;
const connection_1 = require("./connection");
Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return connection_1.Connection; } });
const signer_1 = require("./signer");
Object.defineProperty(exports, "Signer", { enumerable: true, get: function () { return signer_1.Signer; } });
Object.defineProperty(exports, "InMemorySigner", { enumerable: true, get: function () { return signer_1.InMemorySigner; } });
const contract_1 = require("./contract");
Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return contract_1.Contract; } });
const key_pair_1 = require("./utils/key_pair");
Object.defineProperty(exports, "KeyPair", { enumerable: true, get: function () { return key_pair_1.KeyPair; } });
const near_1 = require("./near");
Object.defineProperty(exports, "connect", { enumerable: true, get: function () { return near_1.connect; } });
// TODO: Deprecate and remove WalletAccount
const wallet_account_1 = require("./wallet-account");
Object.defineProperty(exports, "WalletAccount", { enumerable: true, get: function () { return wallet_account_1.WalletAccount; } });
Object.defineProperty(exports, "WalletConnection", { enumerable: true, get: function () { return wallet_account_1.WalletConnection; } });
exports.keyStores = __importStar(require("./key_stores/browser-index"));
__exportStar(require("./common-index"), exports);

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

import * as providers from './providers';
import * as utils from './utils';
import * as keyStores from './key_stores';
import * as transactions from './transaction';
import * as validators from './validators';
import { Account } from './account';
import * as accountCreator from './account_creator';
import { Connection } from './connection';
import { Signer, InMemorySigner } from './signer';
import { Contract } from './contract';
import { KeyPair } from './utils/key_pair';
import { connect, Near } from './near';
import { WalletAccount, WalletConnection } from './wallet-account';
export { accountCreator, keyStores, providers, utils, transactions, validators, Account, Connection, Contract, InMemorySigner, Signer, KeyPair, connect, Near, WalletAccount, WalletConnection };
export * as keyStores from './key_stores/index';
export * from './common-index';

@@ -17,37 +17,11 @@ "use strict";

var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalletConnection = exports.WalletAccount = exports.Near = exports.connect = exports.KeyPair = exports.Signer = exports.InMemorySigner = exports.Contract = exports.Connection = exports.Account = exports.validators = exports.transactions = exports.utils = exports.providers = exports.keyStores = exports.accountCreator = void 0;
const providers = __importStar(require("./providers"));
exports.providers = providers;
const utils = __importStar(require("./utils"));
exports.utils = utils;
const keyStores = __importStar(require("./key_stores"));
exports.keyStores = keyStores;
const transactions = __importStar(require("./transaction"));
exports.transactions = transactions;
const validators = __importStar(require("./validators"));
exports.validators = validators;
const account_1 = require("./account");
Object.defineProperty(exports, "Account", { enumerable: true, get: function () { return account_1.Account; } });
const accountCreator = __importStar(require("./account_creator"));
exports.accountCreator = accountCreator;
const connection_1 = require("./connection");
Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return connection_1.Connection; } });
const signer_1 = require("./signer");
Object.defineProperty(exports, "Signer", { enumerable: true, get: function () { return signer_1.Signer; } });
Object.defineProperty(exports, "InMemorySigner", { enumerable: true, get: function () { return signer_1.InMemorySigner; } });
const contract_1 = require("./contract");
Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return contract_1.Contract; } });
const key_pair_1 = require("./utils/key_pair");
Object.defineProperty(exports, "KeyPair", { enumerable: true, get: function () { return key_pair_1.KeyPair; } });
const near_1 = require("./near");
Object.defineProperty(exports, "connect", { enumerable: true, get: function () { return near_1.connect; } });
Object.defineProperty(exports, "Near", { enumerable: true, get: function () { return near_1.Near; } });
// TODO: Deprecate and remove WalletAccount
const wallet_account_1 = require("./wallet-account");
Object.defineProperty(exports, "WalletAccount", { enumerable: true, get: function () { return wallet_account_1.WalletAccount; } });
Object.defineProperty(exports, "WalletConnection", { enumerable: true, get: function () { return wallet_account_1.WalletConnection; } });
exports.keyStores = __importStar(require("./key_stores/index"));
__exportStar(require("./common-index"), exports);

@@ -63,3 +63,3 @@ "use strict";

await ensureDir(`${this.keyDir}/${networkId}`);
const content = { account_id: accountId, private_key: keyPair.toString() };
const content = { account_id: accountId, public_key: keyPair.getPublicKey().toString(), private_key: keyPair.toString() };
await writeFile(this.getKeyFilePath(networkId, accountId), JSON.stringify(content));

@@ -66,0 +66,0 @@ }

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

import { Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, BlockResult, ChunkId, ChunkResult, EpochValidatorInfo, GenesisConfig } from './provider';
import { Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, Finality, BlockResult, ChunkId, ChunkResult, EpochValidatorInfo, GenesisConfig, LightClientProof, LightClientProofRequest } from './provider';
import { Network } from '../utils/network';

@@ -45,6 +45,8 @@ import { ConnectionInfo } from '../utils/web';

* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
block(blockId: BlockId): Promise<BlockResult>;
block(blockQuery: BlockId | {
blockId: BlockId;
} | {
finality: Finality;
}): Promise<BlockResult>;
/**

@@ -62,3 +64,3 @@ * Queries for details of a specific chunk appending details of receipts and transactions to the same chunk data provided by a block

*/
validators(blockId: BlockId): Promise<EpochValidatorInfo>;
validators(blockId: BlockId | null): Promise<EpochValidatorInfo>;
/**

@@ -70,2 +72,7 @@ * Gets EXPERIMENTAL_genesis_config from RPC

/**
* Gets EXPERIMENTAL_light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
*/
experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
/**
* Directly call the RPC specifying the method and params

@@ -75,3 +82,3 @@ * @param method RPC method

*/
sendJsonRpc(method: string, params: any[]): Promise<any>;
sendJsonRpc(method: string, params: object): Promise<any>;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonRpcProvider = exports.TypedError = void 0;
const depd_1 = __importDefault(require("depd"));
const provider_1 = require("./provider");

@@ -70,7 +74,12 @@ const web_1 = require("../utils/web");

* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
async block(blockId) {
return this.sendJsonRpc('block', [blockId]);
async block(blockQuery) {
const { finality } = blockQuery;
let { blockId } = blockQuery;
if (typeof blockQuery !== 'object') {
const deprecate = depd_1.default('JsonRpcProvider.block(blockId)');
deprecate('use `block({ blockId })` or `block({ finality })` instead');
blockId = blockQuery;
}
return this.sendJsonRpc('block', { block_id: blockId, finality });
}

@@ -102,2 +111,9 @@ /**

/**
* Gets EXPERIMENTAL_light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
*/
async experimental_lightClientProof(request) {
return await this.sendJsonRpc('EXPERIMENTAL_light_client_proof', request);
}
/**
* Directly call the RPC specifying the method and params

@@ -104,0 +120,0 @@ * @param method RPC method

@@ -21,5 +21,6 @@ import { Network } from '../utils/network';

}
export declare type BlockHash = string;
export declare type BlockHeight = number;
declare type BlockHash = string;
declare type BlockHeight = number;
export declare type BlockId = BlockHash | BlockHeight;
export declare type Finality = 'optimistic' | 'near-final' | 'final';
export declare enum ExecutionStatusBasic {

@@ -58,2 +59,8 @@ Unknown = "Unknown",

}
export interface ExecutionOutcomeWithIdView {
proof: MerklePath;
block_hash: string;
id: string;
outcome: ExecutionOutcome;
}
export interface FinalExecutionOutcome {

@@ -153,2 +160,40 @@ status: FinalExecutionStatus | FinalExecutionStatusBasic;

}
export interface MerkleNode {
hash: string;
direction: string;
}
export declare type MerklePath = MerkleNode[];
export interface BlockHeaderInnerLiteView {
height: number;
epoch_id: string;
next_epoch_id: string;
prev_state_root: string;
outcome_root: string;
timestamp: number;
next_bp_hash: string;
block_merkle_root: string;
}
export interface LightClientBlockLiteView {
prev_block_hash: string;
inner_rest_hash: string;
inner_lite: BlockHeaderInnerLiteView;
}
export interface LightClientProof {
outcome_proof: ExecutionOutcomeWithIdView;
outcome_root_proof: MerklePath;
block_header_lite: LightClientBlockLiteView;
block_proof: MerklePath;
}
export declare enum IdType {
Transaction = "transaction",
Receipt = "receipt"
}
export interface LightClientProofRequest {
type: IdType;
light_client_head: string;
transaction_hash?: string;
sender_id?: string;
receipt_id?: string;
receiver_id?: string;
}
export declare abstract class Provider {

@@ -164,2 +209,3 @@ abstract getNetwork(): Promise<Network>;

abstract experimental_genesisConfig(): Promise<GenesisConfig>;
abstract experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
}

@@ -166,0 +212,0 @@ export declare function getTransactionLastResult(txResult: FinalExecutionOutcome): any;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.adaptTransactionResult = exports.getTransactionLastResult = exports.Provider = exports.FinalExecutionStatusBasic = exports.ExecutionStatusBasic = void 0;
exports.adaptTransactionResult = exports.getTransactionLastResult = exports.Provider = exports.IdType = exports.FinalExecutionStatusBasic = exports.ExecutionStatusBasic = void 0;
var ExecutionStatusBasic;

@@ -16,2 +16,7 @@ (function (ExecutionStatusBasic) {

})(FinalExecutionStatusBasic = exports.FinalExecutionStatusBasic || (exports.FinalExecutionStatusBasic = {}));
var IdType;
(function (IdType) {
IdType["Transaction"] = "transaction";
IdType["Receipt"] = "receipt";
})(IdType = exports.IdType || (exports.IdType = {}));
class Provider {

@@ -18,0 +23,0 @@ }

@@ -17,3 +17,3 @@ "use strict";

var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);

@@ -20,0 +20,0 @@ return result;

@@ -17,3 +17,3 @@ "use strict";

var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);

@@ -24,3 +24,3 @@ return result;

for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -27,0 +27,0 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

@@ -23,3 +23,3 @@ "use strict";

var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);

@@ -137,80 +137,77 @@ return result;

}
let BinaryReader = /** @class */ (() => {
class BinaryReader {
constructor(buf) {
this.buf = buf;
this.offset = 0;
class BinaryReader {
constructor(buf) {
this.buf = buf;
this.offset = 0;
}
read_u8() {
const value = this.buf.readUInt8(this.offset);
this.offset += 1;
return value;
}
read_u32() {
const value = this.buf.readUInt32LE(this.offset);
this.offset += 4;
return value;
}
read_u64() {
const buf = this.read_buffer(8);
return new bn_js_1.default(buf, 'le');
}
read_u128() {
const buf = this.read_buffer(16);
return new bn_js_1.default(buf, 'le');
}
read_buffer(len) {
if ((this.offset + len) > this.buf.length) {
throw new BorshError(`Expected buffer length ${len} isn't within bounds`);
}
read_u8() {
const value = this.buf.readUInt8(this.offset);
this.offset += 1;
return value;
const result = this.buf.slice(this.offset, this.offset + len);
this.offset += len;
return result;
}
read_string() {
const len = this.read_u32();
const buf = this.read_buffer(len);
try {
// NOTE: Using TextDecoder to fail on invalid UTF-8
return textDecoder.decode(buf);
}
read_u32() {
const value = this.buf.readUInt32LE(this.offset);
this.offset += 4;
return value;
catch (e) {
throw new BorshError(`Error decoding UTF-8 string: ${e}`);
}
read_u64() {
const buf = this.read_buffer(8);
return new bn_js_1.default(buf, 'le');
}
read_fixed_array(len) {
return new Uint8Array(this.read_buffer(len));
}
read_array(fn) {
const len = this.read_u32();
const result = Array();
for (let i = 0; i < len; ++i) {
result.push(fn());
}
read_u128() {
const buf = this.read_buffer(16);
return new bn_js_1.default(buf, 'le');
}
read_buffer(len) {
if ((this.offset + len) > this.buf.length) {
throw new BorshError(`Expected buffer length ${len} isn't within bounds`);
}
const result = this.buf.slice(this.offset, this.offset + len);
this.offset += len;
return result;
}
read_string() {
const len = this.read_u32();
const buf = this.read_buffer(len);
try {
// NOTE: Using TextDecoder to fail on invalid UTF-8
return textDecoder.decode(buf);
}
catch (e) {
throw new BorshError(`Error decoding UTF-8 string: ${e}`);
}
}
read_fixed_array(len) {
return new Uint8Array(this.read_buffer(len));
}
read_array(fn) {
const len = this.read_u32();
const result = Array();
for (let i = 0; i < len; ++i) {
result.push(fn());
}
return result;
}
return result;
}
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u8", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u32", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u64", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u128", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_string", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_fixed_array", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_array", null);
return BinaryReader;
})();
}
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u8", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u32", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u64", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_u128", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_string", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_fixed_array", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "read_array", null);
exports.BinaryReader = BinaryReader;

@@ -217,0 +214,0 @@ function serializeField(schema, fieldName, value, fieldType, writer) {

{
"name": "near-api-js",
"description": "JavaScript library to interact with NEAR Protocol via RPC API",
"version": "0.25.1",
"version": "0.26.0",
"repository": {

@@ -17,2 +17,3 @@ "type": "git",

"bs58": "^4.0.0",
"depd": "^2.0.0",
"error-polyfill": "^0.1.2",

@@ -50,3 +51,3 @@ "http-errors": "^1.7.2",

"keywords": [],
"license": "MIT",
"license": "(MIT AND Apache-2.0)",
"scripts": {

@@ -53,0 +54,0 @@ "dist": "yarn browserify && yarn doc",

@@ -16,7 +16,8 @@ 'use strict';

// the originator.
// Default value is set to equal to max_prepaid_gas as discussed here:
// https://github.com/near/near-api-js/pull/191#discussion_r369671912
const DEFAULT_FUNC_CALL_GAS = new BN('10000000000000000');
// Due to protocol changes that charge upfront for the maximum possible gas price inflation due to
// full blocks, the price of max_prepaid_gas is decreased to `300 * 10**12`.
// For discussion see https://github.com/nearprotocol/NEPs/issues/67
const DEFAULT_FUNC_CALL_GAS = new BN('300000000000000');
// Default number of retries before giving up on a transactioin.
// Default number of retries before giving up on a transaction.
const TX_STATUS_RETRY_NUMBER = 10;

@@ -343,3 +344,3 @@

const state = await this.state();
const costPerByte = new BN(genesisConfig.runtime_config.storage_amount_per_byte);

@@ -346,0 +347,0 @@ const stateStaked = new BN(state.storage_usage).mul(costPerByte);

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

'use strict';
import * as providers from './providers';
import * as utils from './utils';
import * as keyStores from './key_stores/browser-index';
import * as transactions from './transaction';
import { Account } from './account';
import * as accountCreator from './account_creator';
import { Connection } from './connection';
import { Signer, InMemorySigner } from './signer';
import { Contract } from './contract';
import { KeyPair } from './utils/key_pair';
import { connect } from './near';
// TODO: Deprecate and remove WalletAccount
import { WalletAccount, WalletConnection } from './wallet-account';
export {
accountCreator,
keyStores,
providers,
utils,
transactions,
Account,
Connection,
Contract,
InMemorySigner,
Signer,
KeyPair,
connect,
WalletAccount,
WalletConnection
};
export * as keyStores from './key_stores/browser-index';
export * from './common-index';

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

import * as providers from './providers';
import * as utils from './utils';
import * as keyStores from './key_stores';
import * as transactions from './transaction';
import * as validators from './validators';
import { Account } from './account';
import * as accountCreator from './account_creator';
import { Connection } from './connection';
import { Signer, InMemorySigner } from './signer';
import { Contract } from './contract';
import { KeyPair } from './utils/key_pair';
import { connect, Near } from './near';
// TODO: Deprecate and remove WalletAccount
import { WalletAccount, WalletConnection } from './wallet-account';
export {
accountCreator,
keyStores,
providers,
utils,
transactions,
validators,
Account,
Connection,
Contract,
InMemorySigner,
Signer,
KeyPair,
connect,
Near,
WalletAccount,
WalletConnection
};
export * as keyStores from './key_stores/index';
export * from './common-index';

@@ -28,2 +28,3 @@ import fs from 'fs';

account_id: string;
public_key: string;
private_key: string;

@@ -71,3 +72,3 @@ }

await ensureDir(`${this.keyDir}/${networkId}`);
const content: AccountInfo = { account_id: accountId, private_key: keyPair.toString() };
const content: AccountInfo = { account_id: accountId, public_key: keyPair.getPublicKey().toString(), private_key: keyPair.toString() };
await writeFile(this.getKeyFilePath(networkId, accountId), JSON.stringify(content));

@@ -74,0 +75,0 @@ }

@@ -0,5 +1,6 @@

import depd from 'depd';
import {
Provider, FinalExecutionOutcome, NodeStatusResult, BlockId,
Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, Finality,
BlockResult, ChunkId, ChunkResult, adaptTransactionResult, EpochValidatorInfo,
GenesisConfig
GenesisConfig, LightClientProof, LightClientProofRequest
} from './provider';

@@ -84,7 +85,14 @@ import { Network } from '../utils/network';

* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
async block(blockId: BlockId): Promise<BlockResult> {
return this.sendJsonRpc('block', [blockId]);
async block(blockQuery: BlockId | { blockId: BlockId } | { finality: Finality }): Promise<BlockResult> {
const { finality } = blockQuery as any;
let { blockId } = blockQuery as any;
if (typeof blockQuery !== 'object') {
const deprecate = depd('JsonRpcProvider.block(blockId)');
deprecate('use `block({ blockId })` or `block({ finality })` instead');
blockId = blockQuery;
}
return this.sendJsonRpc('block', { block_id: blockId, finality });
}

@@ -107,3 +115,3 @@

*/
async validators(blockId: BlockId): Promise<EpochValidatorInfo> {
async validators(blockId: BlockId | null): Promise<EpochValidatorInfo> {
return this.sendJsonRpc('validators', [blockId]);

@@ -121,2 +129,10 @@ }

/**
* Gets EXPERIMENTAL_light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
*/
async experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof> {
return await this.sendJsonRpc('EXPERIMENTAL_light_client_proof', request);
}
/**
* Directly call the RPC specifying the method and params

@@ -126,3 +142,3 @@ * @param method RPC method

*/
async sendJsonRpc(method: string, params: any[]): Promise<any> {
async sendJsonRpc(method: string, params: object): Promise<any> {
const request = {

@@ -129,0 +145,0 @@ method,

@@ -25,6 +25,8 @@ import { Network } from '../utils/network';

export type BlockHash = string;
export type BlockHeight = number;
type BlockHash = string;
type BlockHeight = number;
export type BlockId = BlockHash | BlockHeight;
export type Finality = 'optimistic' | 'near-final' | 'final'
export enum ExecutionStatusBasic {

@@ -70,2 +72,9 @@ Unknown = 'Unknown',

export interface ExecutionOutcomeWithIdView {
proof: MerklePath;
block_hash: string;
id: string;
outcome: ExecutionOutcome;
}
export interface FinalExecutionOutcome {

@@ -186,2 +195,47 @@ status: FinalExecutionStatus | FinalExecutionStatusBasic;

export interface MerkleNode {
hash: string;
direction: string;
}
export type MerklePath = MerkleNode[];
export interface BlockHeaderInnerLiteView {
height: number;
epoch_id: string;
next_epoch_id: string;
prev_state_root: string;
outcome_root: string;
timestamp: number;
next_bp_hash: string;
block_merkle_root: string;
}
export interface LightClientBlockLiteView {
prev_block_hash: string;
inner_rest_hash: string;
inner_lite: BlockHeaderInnerLiteView;
}
export interface LightClientProof {
outcome_proof: ExecutionOutcomeWithIdView;
outcome_root_proof: MerklePath;
block_header_lite: LightClientBlockLiteView;
block_proof: MerklePath;
}
export enum IdType {
Transaction = 'transaction',
Receipt = 'receipt',
}
export interface LightClientProofRequest {
type: IdType;
light_client_head: string;
transaction_hash?: string;
sender_id?: string;
receipt_id?: string;
receiver_id?: string;
}
export abstract class Provider {

@@ -198,2 +252,3 @@ abstract async getNetwork(): Promise<Network>;

abstract async experimental_genesisConfig(): Promise<GenesisConfig>;
abstract async experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
}

@@ -200,0 +255,0 @@

@@ -6,3 +6,5 @@

const UnencryptedFileSystemKeyStore = nearApi.keyStores.UnencryptedFileSystemKeyStore;
const KeyPair = nearApi.utils.KeyPairEd25519;
const { ensureDir } = require('../test-utils');
const fs = require('fs');

@@ -21,2 +23,11 @@ const KEYSTORE_PATH = '../test-keys';

require('./keystore_common').shouldStoreAndRetriveKeys(ctx);
it('test public key exists', async () => {
const key1 = KeyPair.fromRandom();
await ctx.keyStore.setKey('network', 'account', key1);
const keyFilePath = ctx.keyStore.getKeyFilePath('network', 'account');
const content = fs.readFileSync(keyFilePath);
const accountInfo = JSON.parse(content.toString());
expect(accountInfo.public_key).toEqual(key1.getPublicKey().toString());
});
});
const nearApi = require('../lib/index');
const testUtils = require('./test-utils');
const BN = require('bn.js');

@@ -18,6 +20,19 @@ const withProvider = (fn) => {

let height = stat.sync_info.latest_block_height - 1;
let response = await provider.block(height);
let response = await provider.block({ blockId: height });
expect(response.header.height).toEqual(height);
let sameBlock = await provider.block(response.header.hash);
let sameBlock = await provider.block({ blockId: response.header.hash });
expect(sameBlock.header.height).toEqual(height);
let optimisticBlock = await provider.block({ finality: 'optimistic' });
expect(optimisticBlock.header.height - height).toBeLessThan(5);
let nearFinalBlock = await provider.block({ finality: 'near-final' });
expect(nearFinalBlock.header.height - height).toBeLessThan(5);
let finalBlock = await provider.block({ finality: 'final' });
expect(finalBlock.header.height - height).toBeLessThan(5);
let deprecatedStyle = await provider.block(height);
expect(deprecatedStyle.header.height).toEqual(height);
}));

@@ -68,1 +83,63 @@

});
test('json rpc light client proof', async() => {
jest.setTimeout(30000);
const nearjs = await testUtils.setUpTestConnection();
const workingAccount = await testUtils.createAccount(await nearjs.account(testUtils.testAccountName), { amount: testUtils.INITIAL_BALANCE.mul(new BN(100)) });
const executionOutcome = await workingAccount.sendMoney(testUtils.testAccountName, new BN(10000));
const provider = nearjs.connection.provider;
async function waitForStatusMatching(isMatching) {
const MAX_ATTEMPTS = 10;
for (let i = 0; i < MAX_ATTEMPTS; i++) {
await testUtils.sleep(500);
const nodeStatus = await provider.status();
if (isMatching(nodeStatus)) {
return nodeStatus;
}
}
throw new Error(`Exceeded ${MAX_ATTEMPTS} attempts waiting for matching node status.`);
}
const comittedStatus = await waitForStatusMatching(status =>
status.sync_info.latest_block_hash !== executionOutcome.transaction_outcome.block_hash);
const BLOCKS_UNTIL_FINAL = 2;
const finalizedStatus = await waitForStatusMatching(status =>
status.sync_info.latest_block_height > comittedStatus.sync_info.latest_block_height + BLOCKS_UNTIL_FINAL);
const block = await provider.block(finalizedStatus.sync_info.latest_block_hash);
const lightClientHead = block.header.last_final_block;
let lightClientRequest = {
type: 'transaction',
light_client_head: lightClientHead,
transaction_hash: executionOutcome.transaction.hash,
sender_id: workingAccount.accountId,
};
const lightClientProof = await provider.experimental_lightClientProof(lightClientRequest);
expect('prev_block_hash' in lightClientProof.block_header_lite).toBe(true);
expect('inner_rest_hash' in lightClientProof.block_header_lite).toBe(true);
expect('inner_lite' in lightClientProof.block_header_lite).toBe(true);
expect(lightClientProof.outcome_proof.id).toEqual(executionOutcome.transaction_outcome.id);
expect('block_hash' in lightClientProof.outcome_proof).toBe(true);
expect(lightClientProof.outcome_root_proof).toEqual([]);
expect(lightClientProof.block_proof.length).toBeGreaterThan(0);
// pass nonexistent hash for light client head will fail
lightClientRequest = {
type: 'transaction',
light_client_head: '11111111111111111111111111111111',
transaction_hash: executionOutcome.transaction.hash,
sender_id: workingAccount.accountId,
};
await expect(provider.experimental_lightClientProof(lightClientRequest)).rejects.toThrow('DB Not Found Error');
// Use old block hash as light client head should fail
lightClientRequest = {
type: 'transaction',
light_client_head: executionOutcome.transaction_outcome.block_hash,
transaction_hash: executionOutcome.transaction.hash,
sender_id: workingAccount.accountId,
};
await expect(provider.experimental_lightClientProof(lightClientRequest)).rejects.toThrow(/.+ block .+ is ahead of head block .+/);
});

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

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