Socket
Socket
Sign inDemoInstall

near-api-js

Package Overview
Dependencies
Maintainers
8
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.39.0 to 0.40.0

.github/workflows/stale.yml

4

lib/account_multisig.d.ts

@@ -31,5 +31,5 @@ import BN from 'bn.js';

deleteUnconfirmedRequests(): Promise<void>;
getRequestNonce(): Promise<Number>;
getRequestNonce(): Promise<number>;
getRequestIds(): Promise<string>;
isDeleteAction(actions: any): Boolean;
isDeleteAction(actions: any): boolean;
getRequest(): any;

@@ -36,0 +36,0 @@ setRequest(data: any): any;

@@ -21,5 +21,4 @@ 'use strict';

exports.MULTISIG_CONFIRM_METHODS = ['confirm'];
;
// in memory request cache for node w/o localStorage
let storageFallback = {
const storageFallback = {
[exports.MULTISIG_STORAGE_KEY]: null

@@ -67,3 +66,3 @@ };

catch (e) {
console.warn("Attempt to delete an earlier request before 15 minutes failed. Will try again.");
console.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.');
}

@@ -84,3 +83,3 @@ }

if (this.storage) {
return JSON.parse(this.storage.getItem(exports.MULTISIG_STORAGE_KEY) || `{}`);
return JSON.parse(this.storage.getItem(exports.MULTISIG_STORAGE_KEY) || '{}');
}

@@ -146,7 +145,10 @@ return storageFallback[exports.MULTISIG_STORAGE_KEY];

const accessKeys = await this.getAccessKeys();
const lak2fak = accessKeys.filter(({ access_key }) => access_key && access_key.permission && access_key.permission.FunctionCall &&
access_key.permission.FunctionCall.receiver_id === accountId &&
access_key.permission.FunctionCall.method_names &&
access_key.permission.FunctionCall.method_names.length === 4 &&
access_key.permission.FunctionCall.method_names.includes('add_request_and_confirm'));
const lak2fak = accessKeys
.filter(({ access_key }) => access_key.permission !== 'FullAccess')
.filter(({ access_key }) => {
const perm = access_key.permission.FunctionCall;
return perm.receiver_id === accountId &&
perm.method_names.length === 4 &&
perm.method_names.includes('add_request_and_confirm');
});
const confirmOnlyKey = key_pair_1.PublicKey.from((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);

@@ -153,0 +155,0 @@ const actions = [

/// <reference types="node" />
import BN from 'bn.js';
import { AccessKey, Action, SignedTransaction } from './transaction';
import { Action, SignedTransaction } from './transaction';
import { FinalExecutionOutcome } from './providers';
import { Finality, BlockId } from './providers/provider';
import { Finality, BlockId, AccountView, AccessKeyView, AccessKeyInfoView } from './providers/provider';
import { Connection } from './connection';
import { PublicKey } from './utils/key_pair';
export interface AccountState {
amount: string;
code_hash: string;
storage_usage: number;
locked: string;
}
export interface AccountBalance {

@@ -20,5 +14,14 @@ total: string;

}
export interface AccountAuthorizedApp {
contractId: string;
amount: string;
publicKey: PublicKey;
}
declare function parseJsonFromRawResponse(response: Uint8Array): any;
/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
* This class provides common account related RPC calls including signing transactions with a {@link KeyPair}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
* @hint Use {@link WalletConnection} in the browser to redirect to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for Account/key management using the {@link BrowserLocalStorageKeyStore}.
* @see {@link https://nomicon.io/DataStructures/Account.html | Account Spec}
*/

@@ -28,2 +31,3 @@ export declare class Account {

readonly accountId: string;
/** @hidden */
protected get ready(): Promise<void>;

@@ -33,27 +37,48 @@ constructor(connection: Connection, accountId: string);

/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
* Returns basic NEAR account information via the `view_account` RPC query method
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-account}
*/
state(): Promise<AccountState>;
state(): Promise<AccountView>;
/** @hidden */
private printLogsAndFailures;
/** @hidden */
private printLogs;
/**
* Create a signed transaction which can be broadcast to the network
* @param receiverId NEAR account receiving the transaction
* @param actions list of actions to perform as part of the transaction
* @see {@link JsonRpcProvider.sendTransaction}
*/
protected signTransaction(receiverId: string, actions: Action[]): Promise<[Uint8Array, SignedTransaction]>;
/**
* Sign a transaction to preform a list of actions and broadcast it using the RPC API.
* @see {@link JsonRpcProvider.sendTransaction}
*
* @param receiverId NEAR account receiving the transaction
* @param actions The transaction [Action as described in the spec](https://nomicon.io/RuntimeSpec/Actions.html).
* @returns {Promise<FinalExecutionOutcome>}
* @param actions list of actions to perform as part of the transaction
*/
protected signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome>;
/** @hidden */
accessKeyByPublicKeyCache: {
[key: string]: AccessKey;
[key: string]: AccessKeyView;
};
/**
* Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link KeyStore}.
*
* @todo Find matching access key based on transaction (i.e. receiverId and actions)
*
* @param receiverId currently unused (see todo)
* @param actions currently unused (see todo)
* @returns `{ publicKey PublicKey; accessKey: AccessKeyView }`
*/
findAccessKey(receiverId: string, actions: Action[]): Promise<{
publicKey: PublicKey;
accessKey: AccessKey;
accessKey: AccessKeyView;
}>;
/**
* Create a new account and deploy a contract to it
*
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param publicKey The public key to add to the created contract account
* @param data The compiled contract code
* @returns {Promise<Account>}
*/

@@ -64,3 +89,2 @@ createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: BN): Promise<Account>;

* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -71,3 +95,2 @@ sendMoney(receiverId: string, amount: BN): Promise<FinalExecutionOutcome>;

* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -77,3 +100,2 @@ createAccount(newAccountId: string, publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome>;

* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
* @returns void
*/

@@ -83,3 +105,2 @@ deleteAccount(beneficiaryId: string): Promise<FinalExecutionOutcome>;

* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -94,6 +115,7 @@ deployContract(data: Uint8Array): Promise<FinalExecutionOutcome>;

* @param deposit amount of NEAR (in yoctoNEAR) to send together with the call
* @returns {Promise<FinalExecutionOutcome>}
*/
functionCall(contractId: string, methodName: string, args: any, gas?: BN, amount?: BN): Promise<FinalExecutionOutcome>;
/**
* @see {@link https://docs.near.org/docs/concepts/account#access-keys}
* @todo expand this API to support more options.
* @param publicKey A public key to be associated with the contract

@@ -103,4 +125,2 @@ * @param contractId NEAR account where the contract is deployed

* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
* TODO: expand this API to support more options.
*/

@@ -114,9 +134,14 @@ addKey(publicKey: string | PublicKey, contractId?: string, methodNames?: string | string[], amount?: BN): Promise<FinalExecutionOutcome>;

/**
* @see {@link https://docs.near.org/docs/validator/staking-overview}
*
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
stake(publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome>;
/** @hidden */
private validateArgs;
/**
* Invoke a contract view function using the RPC API.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#call-a-contract-function}
*
* @param contractId NEAR account where the contract is deployed

@@ -127,10 +152,9 @@ * @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code

*/
viewFunction(contractId: string, methodName: string, args: any, { parse }?: {
viewFunction(contractId: string, methodName: string, args?: any, { parse }?: {
parse?: typeof parseJsonFromRawResponse;
}): Promise<any>;
/**
* See https://docs.near.org/docs/develop/front-end/rpc#view-contract-state
*
* Returns the state (key value pairs) of this account's contract based on the key prefix.
* Pass an empty string for prefix if you would like to return the entire state.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-contract-state}
*

@@ -140,3 +164,3 @@ * @param prefix allows to filter which keys should be returned. Empty prefix means all keys. String prefix is utf-8 encoded.

*/
viewState(prefix: string | Uint8Array, blockQuery: {
viewState(prefix: string | Uint8Array, blockQuery?: {
blockId: BlockId;

@@ -150,13 +174,15 @@ } | {

/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
* Get all access keys for the account
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-access-key-list}
*/
getAccessKeys(): Promise<any>;
getAccessKeys(): Promise<AccessKeyInfoView[]>;
/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
* Returns a list of authorized apps
* @todo update the response value to return all the different keys, not just app keys.
*/
getAccountDetails(): Promise<any>;
getAccountDetails(): Promise<{
authorizedApps: AccountAuthorizedApp[];
}>;
/**
* Returns calculated account balance
* @returns {Promise<AccountBalance>}
*/

@@ -163,0 +189,0 @@ getAccountBalance(): Promise<AccountBalance>;

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

'use strict';
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -33,6 +33,11 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
* This class provides common account related RPC calls including signing transactions with a {@link KeyPair}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
* @hint Use {@link WalletConnection} in the browser to redirect to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for Account/key management using the {@link BrowserLocalStorageKeyStore}.
* @see {@link https://nomicon.io/DataStructures/Account.html | Account Spec}
*/
class Account {
constructor(connection, accountId) {
/** @hidden */
this.accessKeyByPublicKeyCache = {};

@@ -42,2 +47,3 @@ this.connection = connection;

}
/** @hidden */
get ready() {

@@ -53,8 +59,13 @@ const deprecate = depd_1.default('Account.ready()');

/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
* Returns basic NEAR account information via the `view_account` RPC query method
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-account}
*/
async state() {
return await this.connection.provider.query(`account/${this.accountId}`, '');
return this.connection.provider.query({
request_type: 'view_account',
account_id: this.accountId,
finality: 'optimistic'
});
}
/** @hidden */
printLogsAndFailures(contractId, results) {

@@ -69,2 +80,3 @@ for (const result of results) {

}
/** @hidden */
printLogs(contractId, logs, prefix = '') {

@@ -75,2 +87,8 @@ for (const log of logs) {

}
/**
* Create a signed transaction which can be broadcast to the network
* @param receiverId NEAR account receiving the transaction
* @param actions list of actions to perform as part of the transaction
* @see {@link JsonRpcProvider.sendTransaction}
*/
async signTransaction(receiverId, actions) {

@@ -88,5 +106,7 @@ const accessKeyInfo = await this.findAccessKey(receiverId, actions);

/**
* Sign a transaction to preform a list of actions and broadcast it using the RPC API.
* @see {@link JsonRpcProvider.sendTransaction}
*
* @param receiverId NEAR account receiving the transaction
* @param actions The transaction [Action as described in the spec](https://nomicon.io/RuntimeSpec/Actions.html).
* @returns {Promise<FinalExecutionOutcome>}
* @param actions list of actions to perform as part of the transaction
*/

@@ -141,2 +161,11 @@ async signAndSendTransaction(receiverId, actions) {

}
/**
* Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link KeyStore}.
*
* @todo Find matching access key based on transaction (i.e. receiverId and actions)
*
* @param receiverId currently unused (see todo)
* @param actions currently unused (see todo)
* @returns `{ publicKey PublicKey; accessKey: AccessKeyView }`
*/
async findAccessKey(receiverId, actions) {

@@ -153,3 +182,15 @@ // TODO: Find matching access key based on transaction (i.e. receiverId and actions)

try {
const accessKey = await this.connection.provider.query(`access_key/${this.accountId}/${publicKey.toString()}`, '');
const accessKey = await this.connection.provider.query({
request_type: 'view_access_key',
account_id: this.accountId,
public_key: publicKey.toString(),
finality: 'optimistic'
});
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if (this.accessKeyByPublicKeyCache[publicKey.toString()]) {
return { publicKey, accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()] };
}
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;

@@ -166,6 +207,7 @@ return { publicKey, accessKey };

/**
* Create a new account and deploy a contract to it
*
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param publicKey The public key to add to the created contract account
* @param data The compiled contract code
* @returns {Promise<Account>}
*/

@@ -181,3 +223,2 @@ async createAndDeployContract(contractId, publicKey, data, amount) {

* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -190,3 +231,2 @@ async sendMoney(receiverId, amount) {

* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -199,3 +239,2 @@ async createAccount(newAccountId, publicKey, amount) {

* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
* @returns void
*/

@@ -207,3 +246,2 @@ async deleteAccount(beneficiaryId) {

* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -220,3 +258,2 @@ async deployContract(data) {

* @param deposit amount of NEAR (in yoctoNEAR) to send together with the call
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -229,2 +266,4 @@ async functionCall(contractId, methodName, args, gas, amount) {

/**
* @see {@link https://docs.near.org/docs/concepts/account#access-keys}
* @todo expand this API to support more options.
* @param publicKey A public key to be associated with the contract

@@ -234,4 +273,2 @@ * @param contractId NEAR account where the contract is deployed

* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
* TODO: expand this API to support more options.
*/

@@ -262,5 +299,6 @@ async addKey(publicKey, contractId, methodNames, amount) {

/**
* @see {@link https://docs.near.org/docs/validator/staking-overview}
*
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -270,2 +308,3 @@ async stake(publicKey, amount) {

}
/** @hidden */
validateArgs(args) {

@@ -281,2 +320,5 @@ const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length;

/**
* Invoke a contract view function using the RPC API.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#call-a-contract-function}
*
* @param contractId NEAR account where the contract is deployed

@@ -287,6 +329,11 @@ * @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code

*/
async viewFunction(contractId, methodName, args, { parse = parseJsonFromRawResponse } = {}) {
args = args || {};
async viewFunction(contractId, methodName, args = {}, { parse = parseJsonFromRawResponse } = {}) {
this.validateArgs(args);
const result = await this.connection.provider.query(`call/${contractId}/${methodName}`, borsh_1.baseEncode(JSON.stringify(args)));
const result = await this.connection.provider.query({
request_type: 'call_function',
account_id: contractId,
method_name: methodName,
args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),
finality: 'optimistic'
});
if (result.logs) {

@@ -298,6 +345,5 @@ this.printLogs(contractId, result.logs);

/**
* See https://docs.near.org/docs/develop/front-end/rpc#view-contract-state
*
* Returns the state (key value pairs) of this account's contract based on the key prefix.
* Pass an empty string for prefix if you would like to return the entire state.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-contract-state}
*

@@ -307,8 +353,6 @@ * @param prefix allows to filter which keys should be returned. Empty prefix means all keys. String prefix is utf-8 encoded.

*/
async viewState(prefix, blockQuery) {
const { blockId, finality } = blockQuery || {};
async viewState(prefix, blockQuery = { finality: 'optimistic' }) {
const { values } = await this.connection.provider.query({
request_type: 'view_state',
block_id: blockId,
finality: blockId ? undefined : finality || 'optimistic',
...blockQuery,
account_id: this.accountId,

@@ -323,6 +367,11 @@ prefix_base64: Buffer.from(prefix).toString('base64')

/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
* Get all access keys for the account
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-access-key-list}
*/
async getAccessKeys() {
const response = await this.connection.provider.query(`access_key/${this.accountId}`, '');
const response = await this.connection.provider.query({
request_type: 'view_access_key_list',
account_id: this.accountId,
finality: 'optimistic'
});
// A breaking API change introduced extra information into the

@@ -337,4 +386,4 @@ // response, so it now returns an object with a `keys` field instead

/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
* Returns a list of authorized apps
* @todo update the response value to return all the different keys, not just app keys.
*/

@@ -345,18 +394,16 @@ async getAccountDetails() {

const accessKeys = await this.getAccessKeys();
const result = { authorizedApps: [], transactions: [] };
accessKeys.map((item) => {
if (item.access_key.permission.FunctionCall !== undefined) {
const perm = item.access_key.permission.FunctionCall;
result.authorizedApps.push({
contractId: perm.receiver_id,
amount: perm.allowance,
publicKey: item.public_key,
});
}
const authorizedApps = accessKeys
.filter(item => item.access_key.permission !== 'FullAccess')
.map(item => {
const perm = item.access_key.permission;
return {
contractId: perm.FunctionCall.receiver_id,
amount: perm.FunctionCall.allowance,
publicKey: item.public_key,
};
});
return result;
return { authorizedApps };
}
/**
* Returns calculated account balance
* @returns {Promise<AccountBalance>}
*/

@@ -363,0 +410,0 @@ async getAccountBalance() {

@@ -1,5 +0,28 @@

import { Near, NearConfig } from './near';
export declare type ConnectConfig = NearConfig & {
/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass: {@link ConnectConfig.keyStore}
*
* Both are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
*
* @module browserConnect
*/
import { Near, NearConfig } from "./near";
export interface ConnectConfig extends NearConfig {
/** @hidden */
keyPath?: string;
};
}
/**

@@ -6,0 +29,0 @@ * Initialize connection to Near network.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.connect = void 0;
/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass: {@link ConnectConfig.keyStore}
*
* Both are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
*
* @module browserConnect
*/
const near_1 = require("./near");

@@ -5,0 +27,0 @@ /**

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

/** @hidden @module */
export * as keyStores from './key_stores/browser-index';

@@ -2,0 +3,0 @@ export * from './common-index';

@@ -25,2 +25,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/** @hidden @module */
exports.keyStores = __importStar(require("./key_stores/browser-index"));

@@ -27,0 +28,0 @@ __exportStar(require("./common-index"), exports);

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

/** @hidden @module */
import * as providers from './providers';

@@ -2,0 +3,0 @@ import * as utils from './utils';

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

exports.WalletConnection = exports.WalletAccount = exports.ConnectedWalletAccount = exports.Near = exports.KeyPair = exports.Signer = exports.InMemorySigner = exports.Contract = exports.Connection = exports.Account = exports.multisig = exports.validators = exports.transactions = exports.utils = exports.providers = exports.accountCreator = void 0;
/** @hidden @module */
const providers = __importStar(require("./providers"));

@@ -25,0 +26,0 @@ exports.providers = providers;

import { Near, NearConfig } from './near';
export declare type ConnectConfig = NearConfig & {
export interface ConnectConfig extends NearConfig {
/**
* Initialize an {@link InMemoryKeyStore} by reading the file at keyPath.
*
* @important {@link ConnectConfig.keyStore | keyStore} and {@link ConnectConfig.deps | deps.keyStore} take priority over keyPath.
*/
keyPath?: string;
};
}
/**

@@ -6,0 +11,0 @@ * Initialize connection to Near network.

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.connect = void 0;
/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass:
* 1. {@link ConnectConfig.keyStore}
* 2. {@link ConnectConfig.keyPath}
*
* If all three are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
* @module connect
*/
const unencrypted_file_system_keystore_1 = require("./key_stores/unencrypted_file_system_keystore");
const key_stores_1 = require("./key_stores");
const near_1 = require("./near");
const setup_node_fetch_1 = __importDefault(require("./utils/setup-node-fetch"));
global.fetch = setup_node_fetch_1.default;
/**

@@ -8,0 +36,0 @@ * Initialize connection to Near network.

import { Account } from './account';
export interface ContractMethods {
/**
* Methods that change state. These methods cost gas and require a signed transaction.
*
* @see {@link Account.functionCall}
*/
changeMethods: string[];
/**
* View methods do not require a signed transaction.
*
* @@see {@link Account.viewFunction}
*/
viewMethods: string[];
}
/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
* Defines a smart contract on NEAR including the change (mutable) and view (non-mutable) methods
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#contract}
* @example
* ```js
* import { Contract } from 'near-api-js';
*
* async function contractExample() {
* const methodOptions = {
* viewMethods: ['getMessageByAccountId'],
* changeMethods: ['addMessage']
* };
* const contract = new Contract(
* wallet.account(),
* 'contract-id.testnet',
* methodOptions
* );
*
* // use a contract view method
* const messages = await contract.getMessages({
* accountId: 'example-account.testnet'
* });
*
* // use a contract change method
* await contract.addMessage({ text: 'My new message' })
* }
* ```
*/

@@ -8,6 +48,8 @@ export declare class Contract {

readonly contractId: string;
constructor(account: Account, contractId: string, options: {
viewMethods: string[];
changeMethods: string[];
});
/**
* @param account NEAR account to sign change method transactions
* @param contractId NEAR account id where the contract is deployed
* @param options NEAR smart contract methods that your application will use. These will be available as `contract.methodName`
*/
constructor(account: Account, contractId: string, options: ContractMethods);
}

@@ -21,5 +21,36 @@ "use strict";

/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
* Defines a smart contract on NEAR including the change (mutable) and view (non-mutable) methods
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#contract}
* @example
* ```js
* import { Contract } from 'near-api-js';
*
* async function contractExample() {
* const methodOptions = {
* viewMethods: ['getMessageByAccountId'],
* changeMethods: ['addMessage']
* };
* const contract = new Contract(
* wallet.account(),
* 'contract-id.testnet',
* methodOptions
* );
*
* // use a contract view method
* const messages = await contract.getMessages({
* accountId: 'example-account.testnet'
* });
*
* // use a contract change method
* await contract.addMessage({ text: 'My new message' })
* }
* ```
*/
class Contract {
/**
* @param account NEAR account to sign change method transactions
* @param contractId NEAR account id where the contract is deployed
* @param options NEAR smart contract methods that your application will use. These will be available as `contract.methodName`
*/
constructor(account, contractId, options) {

@@ -26,0 +57,0 @@ this.account = account;

@@ -0,3 +1,4 @@

/** @ignore @module */
export * as keyStores from './key_stores/index';
export * from './common-index';
export * from './connect';

@@ -25,4 +25,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/** @ignore @module */
exports.keyStores = __importStar(require("./key_stores/index"));
__exportStar(require("./common-index"), exports);
__exportStar(require("./connect"), exports);
import { KeyStore } from './keystore';
import { KeyPair } from '../utils/key_pair';
/**
* This class is used to store keys in the browsers local storage.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores } from 'near-api-js';
*
* const keyStore = new keyStores.BrowserLocalStorageKeyStore();
* const config = {
* keyStore, // instance of BrowserLocalStorageKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export declare class BrowserLocalStorageKeyStore extends KeyStore {
/** @hidden */
private localStorage;
/** @hidden */
private prefix;
/**
* @param localStorage defaults to window.localStorage
* @param prefix defaults to `near-api-js:keystore:`
*/
constructor(localStorage?: any, prefix?: string);
/**
* Sets a local storage item
* Stores a {@link KeyPair} in local storage.
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -15,3 +43,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -23,3 +51,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Removes a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -30,3 +58,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Removes all items that start with `prefix` from local storage
*/

@@ -46,2 +74,3 @@ clear(): Promise<void>;

/**
* @hidden
* Helper function to retrieve a local storage key

@@ -53,3 +82,4 @@ * @param networkId The targeted network. (ex. default, betanet, etc…)

private storageKeyForSecretKey;
/** @hidden */
private storageKeys;
}

@@ -7,3 +7,29 @@ "use strict";

const LOCAL_STORAGE_KEY_PREFIX = 'near-api-js:keystore:';
/**
* This class is used to store keys in the browsers local storage.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores } from 'near-api-js';
*
* const keyStore = new keyStores.BrowserLocalStorageKeyStore();
* const config = {
* keyStore, // instance of BrowserLocalStorageKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
class BrowserLocalStorageKeyStore extends keystore_1.KeyStore {
/**
* @param localStorage defaults to window.localStorage
* @param prefix defaults to `near-api-js:keystore:`
*/
constructor(localStorage = window.localStorage, prefix = LOCAL_STORAGE_KEY_PREFIX) {

@@ -15,3 +41,3 @@ super();

/**
* Sets a local storage item
* Stores a {@link KeyPair} in local storage.
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -25,3 +51,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -39,3 +65,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Removes a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -48,3 +74,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Removes all items that start with `prefix` from local storage
*/

@@ -90,2 +116,3 @@ async clear() {

/**
* @hidden
* Helper function to retrieve a local storage key

@@ -99,2 +126,3 @@ * @param networkId The targeted network. (ex. default, betanet, etc…)

}
/** @hidden */
*storageKeys() {

@@ -101,0 +129,0 @@ for (let i = 0; i < this.localStorage.length; i++) {

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

/** @hidden @module */
import { KeyStore } from './keystore';

@@ -2,0 +3,0 @@ import { InMemoryKeyStore } from './in_memory_key_store';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MergeKeyStore = exports.BrowserLocalStorageKeyStore = exports.InMemoryKeyStore = exports.KeyStore = void 0;
/** @hidden @module */
const keystore_1 = require("./keystore");

@@ -5,0 +6,0 @@ Object.defineProperty(exports, "KeyStore", { enumerable: true, get: function () { return keystore_1.KeyStore; } });

import { KeyStore } from './keystore';
import { KeyPair } from '../utils/key_pair';
/**
* Simple in-memory keystore for testing purposes.
* Simple in-memory keystore for mainly for testing purposes.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const keyStore = new keyStores.InMemoryKeyStore();
* keyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const config = {
* keyStore, // instance of InMemoryKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export declare class InMemoryKeyStore extends KeyStore {
/** @hidden */
private keys;
constructor();
/**
* Sets an in-memory storage item
* Stores a {@KeyPair} in in-memory storage item
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -17,3 +42,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from in-memory storage
* Gets a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -25,3 +50,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from in-memory storage
* Removes a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -32,3 +57,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Sets all in-memory keys to empty objects
* Removes all {@link KeyPairs} from in-memory storage
*/

@@ -47,3 +72,4 @@ clear(): Promise<void>;

getAccounts(networkId: string): Promise<string[]>;
/** @hidden */
toString(): string;
}

@@ -7,3 +7,27 @@ "use strict";

/**
* Simple in-memory keystore for testing purposes.
* Simple in-memory keystore for mainly for testing purposes.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const keyStore = new keyStores.InMemoryKeyStore();
* keyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const config = {
* keyStore, // instance of InMemoryKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/

@@ -16,3 +40,3 @@ class InMemoryKeyStore extends keystore_1.KeyStore {

/**
* Sets an in-memory storage item
* Stores a {@KeyPair} in in-memory storage item
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -26,3 +50,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from in-memory storage
* Gets a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -40,3 +64,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from in-memory storage
* Removes a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -49,3 +73,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Sets all in-memory keys to empty objects
* Removes all {@link KeyPairs} from in-memory storage
*/

@@ -82,2 +106,3 @@ async clear() {

}
/** @hidden */
toString() {

@@ -84,0 +109,0 @@ return 'InMemoryKeyStore';

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

/** @ignore @module */
import { KeyStore } from './keystore';

@@ -2,0 +3,0 @@ import { InMemoryKeyStore } from './in_memory_key_store';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MergeKeyStore = exports.UnencryptedFileSystemKeyStore = exports.BrowserLocalStorageKeyStore = exports.InMemoryKeyStore = exports.KeyStore = void 0;
/** @ignore @module */
const keystore_1 = require("./keystore");

@@ -5,0 +6,0 @@ Object.defineProperty(exports, "KeyStore", { enumerable: true, get: function () { return keystore_1.KeyStore; } });

import { KeyPair } from '../utils/key_pair';
/**
* Key store interface for `InMemorySigner`.
* KeyStores are passed to {@link Near} via {@link NearConfig}
* and are used by the {@link InMemorySigner} to sign transactions.
*
* @example {@link connect}
*/

@@ -5,0 +8,0 @@ export declare abstract class KeyStore {

@@ -5,3 +5,6 @@ "use strict";

/**
* Key store interface for `InMemorySigner`.
* KeyStores are passed to {@link Near} via {@link NearConfig}
* and are used by the {@link InMemorySigner} to sign transactions.
*
* @example {@link connect}
*/

@@ -8,0 +11,0 @@ class KeyStore {

@@ -5,2 +5,32 @@ import { KeyStore } from './keystore';

* Keystore which can be used to merge multiple key stores into one virtual key store.
*
* @example
* ```js
* const { homedir } = require('os');
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const inMemoryKeyStore = new keyStores.InMemoryKeyStore();
* inMemoryKeyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const fileSystemKeyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
*
* const keyStore = new MergeKeyStore([
* inMemoryKeyStore,
* fileSystemKeyStore
* ]);
* const config = {
* keyStore, // instance of MergeKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/

@@ -14,3 +44,3 @@ export declare class MergeKeyStore extends KeyStore {

/**
* Sets a storage item to the first index of a key store array
* Store a {@link KeyPain} to the first index of a key store array
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -22,3 +52,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from the array of key stores
* Gets a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -30,3 +60,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from the array of key stores
* Removes a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -51,3 +81,4 @@ * @param accountId The NEAR account tied to the key pair

getAccounts(networkId: string): Promise<string[]>;
/** @hidden */
toString(): string;
}

@@ -7,2 +7,32 @@ "use strict";

* Keystore which can be used to merge multiple key stores into one virtual key store.
*
* @example
* ```js
* const { homedir } = require('os');
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const inMemoryKeyStore = new keyStores.InMemoryKeyStore();
* inMemoryKeyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const fileSystemKeyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
*
* const keyStore = new MergeKeyStore([
* inMemoryKeyStore,
* fileSystemKeyStore
* ]);
* const config = {
* keyStore, // instance of MergeKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/

@@ -18,3 +48,3 @@ class MergeKeyStore extends keystore_1.KeyStore {

/**
* Sets a storage item to the first index of a key store array
* Store a {@link KeyPain} to the first index of a key store array
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -28,3 +58,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from the array of key stores
* Gets a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -44,3 +74,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from the array of key stores
* Removes a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -89,2 +119,3 @@ * @param accountId The NEAR account tied to the key pair

}
/** @hidden */
toString() {

@@ -91,0 +122,0 @@ return `MergeKeyStore(${this.keyStores.join(', ')})`;

import { KeyPair } from '../utils/key_pair';
import { KeyStore } from './keystore';
/** @hidden */
export declare function loadJsonFile(filename: string): Promise<any>;
/** @hidden */
export declare function readKeyFile(filename: string): Promise<[string, KeyPair]>;
/**
* This module contains the {@link UnencryptedFileSystemKeyStore} class which is used to store keys on the file system.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* const { homedir } = require('os');
* const { connect, keyStores } = require('near-api-js');
*
* const keyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
* const config = {
* keyStore, // instance of UnencryptedFileSystemKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export declare class UnencryptedFileSystemKeyStore extends KeyStore {
/** @hidden */
readonly keyDir: string;
/**
* @param keyDir base directory for key storage. Keys will be stored in `keyDir/networkId/accountId.json`
*/
constructor(keyDir: string);
/**
* Sets a storage item in a file, unencrypted
* Store a {@link KeyPair} in an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -16,3 +45,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -24,3 +53,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Deletes an unencrypted file holding a {@link KeyPair}
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -31,8 +60,9 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Deletes all unencrypted files from the `keyDir` path.
*/
clear(): Promise<void>;
/** @hidden */
private getKeyFilePath;
/**
* Get the network(s) from local storage
* Get the network(s) from files in `keyDir`
* @returns {Promise<string[]>}

@@ -42,3 +72,3 @@ */

/**
* Gets the account(s) from local storage
* Gets the account(s) files in `keyDir/networkId`
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -48,3 +78,4 @@ * @returns{Promise<string[]>}

getAccounts(networkId: string): Promise<string[]>;
/** @hidden */
toString(): string;
}

@@ -26,2 +26,3 @@ "use strict";

const mkdir = promisify(fs_1.default.mkdir);
/** @hidden */
async function loadJsonFile(filename) {

@@ -42,2 +43,3 @@ const content = await readFile(filename);

}
/** @hidden */
async function readKeyFile(filename) {

@@ -53,3 +55,29 @@ const accountInfo = await loadJsonFile(filename);

exports.readKeyFile = readKeyFile;
/**
* This module contains the {@link UnencryptedFileSystemKeyStore} class which is used to store keys on the file system.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* const { homedir } = require('os');
* const { connect, keyStores } = require('near-api-js');
*
* const keyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
* const config = {
* keyStore, // instance of UnencryptedFileSystemKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
class UnencryptedFileSystemKeyStore extends keystore_1.KeyStore {
/**
* @param keyDir base directory for key storage. Keys will be stored in `keyDir/networkId/accountId.json`
*/
constructor(keyDir) {

@@ -60,3 +88,3 @@ super();

/**
* Sets a storage item in a file, unencrypted
* Store a {@link KeyPair} in an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -72,3 +100,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -87,3 +115,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Deletes an unencrypted file holding a {@link KeyPair}
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -98,3 +126,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Deletes all unencrypted files from the `keyDir` path.
*/

@@ -108,2 +136,3 @@ async clear() {

}
/** @hidden */
getKeyFilePath(networkId, accountId) {

@@ -113,3 +142,3 @@ return `${this.keyDir}/${networkId}/${accountId}.json`;

/**
* Get the network(s) from local storage
* Get the network(s) from files in `keyDir`
* @returns {Promise<string[]>}

@@ -126,3 +155,3 @@ */

/**
* Gets the account(s) from local storage
* Gets the account(s) files in `keyDir/networkId`
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -140,2 +169,3 @@ * @returns{Promise<string[]>}

}
/** @hidden */
toString() {

@@ -142,0 +172,0 @@ return `UnencryptedFileSystemKeyStore(${this.keyDir})`;

@@ -0,1 +1,10 @@

/**
* This module contains the main class developers will use to interact with NEAR.
* The {@link Near} class is used to interact with {@link Account | Accounts} through the {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}.
* It is configured via the {@link NearConfig}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
*
* @module near
*/
import BN from 'bn.js';

@@ -9,15 +18,48 @@ import { Account } from './account';

import { KeyStore } from './key_stores';
export declare type NearConfig = {
export interface NearConfig {
/** Holds {@link KeyPair | KeyPairs} for signing transactions */
keyStore?: KeyStore;
/** @hidden */
signer?: Signer;
/** @deprecated use {@link NearConfig.keyStore} */
deps?: {
keyStore: KeyStore;
};
/**
* {@link https://github.com/near/near-contract-helper | NEAR Contract Helper} url used to create accounts if no master account is provided
* @see {@link UrlAccountCreator}
*/
helperUrl?: string;
/**
* The balance transferred from the {@link NearConfig.masterAccount | masterAccount} to a created account
* @see {@link LocalAccountCreator}
*/
initialBalance?: string;
/**
* The account to use when creating new accounts
* @see {@link LocalAccountCreator}
*/
masterAccount?: string;
/**
* {@link KeyPair | KeyPairs} are stored in a {@link KeyStore} under the `networkId` namespace.
*/
networkId: string;
/**
* NEAR RPC API url. used to make JSON RPC calls to interact with NEAR.
* @see {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}
*/
nodeUrl: string;
/**
* NEAR wallet url used to redirect users to their wallet in browser applications.
* @see {@link https://docs.near.org/docs/tools/near-wallet}
*/
walletUrl?: string;
};
}
/**
* This is the main class developers should use to interact with NEAR.
* @example
* ```js
* const near = new Near(config);
* ```
*/
export declare class Near {

@@ -29,3 +71,2 @@ readonly config: any;

/**
*
* @param accountId near accountId used to interact with the network.

@@ -35,2 +76,6 @@ */

/**
* Create an account using the {@link AccountCreator}. Either:
* * using a masterAccount with {@link LocalAccountCreator}
* * using the helperUrl with {@link UrlAccountCreator}
* @see {@link NearConfig.masterAccount} and {@link NearConfig.helperUrl}-
*

@@ -42,3 +87,3 @@ * @param accountId

/**
* @deprecated Use `new nearApi.Contract(yourAccount, contractId, { viewMethods, changeMethods })` instead.
* @deprecated Use {@link Contract} instead.
* @param contractId

@@ -53,3 +98,3 @@ * @param options

/**
* @deprecated Use `yourAccount.sendMoney` instead.
* @deprecated Use {@link Account.sendMoney} instead.
* @param amount

@@ -56,0 +101,0 @@ * @param originator

@@ -7,2 +7,11 @@ "use strict";

exports.Near = void 0;
/**
* This module contains the main class developers will use to interact with NEAR.
* The {@link Near} class is used to interact with {@link Account | Accounts} through the {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}.
* It is configured via the {@link NearConfig}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
*
* @module near
*/
const bn_js_1 = __importDefault(require("bn.js"));

@@ -13,2 +22,9 @@ const account_1 = require("./account");

const account_creator_1 = require("./account_creator");
/**
* This is the main class developers should use to interact with NEAR.
* @example
* ```js
* const near = new Near(config);
* ```
*/
class Near {

@@ -36,3 +52,2 @@ constructor(config) {

/**
*
* @param accountId near accountId used to interact with the network.

@@ -45,2 +60,6 @@ */

/**
* Create an account using the {@link AccountCreator}. Either:
* * using a masterAccount with {@link LocalAccountCreator}
* * using the helperUrl with {@link UrlAccountCreator}
* @see {@link NearConfig.masterAccount} and {@link NearConfig.helperUrl}-
*

@@ -58,3 +77,3 @@ * @param accountId

/**
* @deprecated Use `new nearApi.Contract(yourAccount, contractId, { viewMethods, changeMethods })` instead.
* @deprecated Use {@link Contract} instead.
* @param contractId

@@ -68,3 +87,3 @@ * @param options

/**
* @deprecated Use `yourAccount.sendMoney` instead.
* @deprecated Use {@link Account.sendMoney} instead.
* @param amount

@@ -71,0 +90,0 @@ * @param originator

@@ -0,3 +1,4 @@

/** @hidden @module */
import { Provider, FinalExecutionOutcome, ExecutionOutcomeWithId, getTransactionLastResult, FinalExecutionStatusBasic } from './provider';
import { JsonRpcProvider, TypedError, ErrorContext } from './json-rpc-provider';
export { Provider, FinalExecutionOutcome, JsonRpcProvider, ExecutionOutcomeWithId, FinalExecutionStatusBasic, getTransactionLastResult, TypedError, ErrorContext };
"use strict";
/** @hidden @module */
Object.defineProperty(exports, "__esModule", { value: true });

@@ -3,0 +4,0 @@ exports.ErrorContext = exports.TypedError = exports.getTransactionLastResult = exports.FinalExecutionStatusBasic = exports.JsonRpcProvider = exports.Provider = void 0;

@@ -1,31 +0,50 @@

import { Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, BlockReference, BlockResult, ChunkId, ChunkResult, EpochValidatorInfo, NearProtocolConfig, LightClientProof, LightClientProofRequest, GasPrice } from './provider';
import { Network } from '../utils/network';
import { AccessKeyWithPublicKey, Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, BlockReference, BlockResult, BlockChangeResult, ChangeResult, ChunkId, ChunkResult, EpochValidatorInfo, NearProtocolConfig, LightClientProof, LightClientProofRequest, GasPrice, QueryResponseKind } from './provider';
import { ConnectionInfo } from '../utils/web';
import { TypedError, ErrorContext } from '../utils/errors';
import { SignedTransaction } from '../transaction';
/** @hidden */
export { TypedError, ErrorContext };
/**
* Client class to interact with the NEAR RPC API.
* @see {@link https://github.com/near/nearcore/tree/master/chain/jsonrpc}
*/
export declare class JsonRpcProvider extends Provider {
/** @hidden */
readonly connection: ConnectionInfo;
constructor(url?: string);
/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
* @param url RPC API endpoint URL
*/
getNetwork(): Promise<Network>;
constructor(url?: string);
/**
* Gets the RPC's status
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
* @returns {Promise<NodeStatusResult>}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#general-validator-status}
*/
status(): Promise<NodeStatusResult>;
/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await)
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await}
*
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
/**
* Sends a signed transaction to the RPC and immediately returns transaction hash
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-async)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
sendTransactionAsync(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status)
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#transaction-status}
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
*/
txStatus(txHash: Uint8Array | string, accountId: string): Promise<FinalExecutionOutcome>;
private txStatusUint8Array;
private txStatusString;
/**
* Gets a transaction's status from the RPC with receipts
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status-with-receipts)
* @param txHash The hash of the transaction

@@ -35,22 +54,36 @@ * @param accountId The NEAR account that signed the transaction

*/
txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
txStatusReceipts(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
/**
* Query the RPC as [shown in the docs](https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts)
* Query the RPC by passing an {@link RpcQueryRequest}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts}
*
* @typeParam T the shape of the returned query response
*/
query(...args: any[]): Promise<any>;
query<T extends QueryResponseKind>(...args: any[]): Promise<T>;
/**
* Query for block info from the RPC
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#block)
* pass block_id OR finality as blockQuery, not both
* @see {@link https://docs.near.org/docs/interaction/rpc#block}
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/
block(blockQuery: BlockId | BlockReference): Promise<BlockResult>;
/**
* Queries for details of a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#chunk)
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#block-details)
*/
blockChanges(blockQuery: BlockReference): Promise<BlockChangeResult>;
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see {@link https://docs.near.org/docs/interaction/rpc#chunk}
*
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/
chunk(chunkId: ChunkId): Promise<ChunkResult>;
/**
* Query validators of the epoch defined by given block id.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status)
* Query validators of the epoch defined by the given block id.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status}
*
* @param blockId Block hash or height, or null for latest.

@@ -60,34 +93,73 @@ */

/**
* Gets EXPERIMENTAL_genesis_config from RPC
* @returns {Promise<NearProtocolConfig>}
* @deprecated
* Gets the genesis config from RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#genesis-config}
*/
experimental_genesisConfig(): Promise<NearProtocolConfig>;
/**
* Gets EXPERIMENTAL_protocol_config from RPC
* @returns {Promise<NearProtocolConfig>}
* Gets the protocol config at a block from RPC
* @see {@link }
*
* @param blockReference specifies the block to get the protocol config for
*/
experimental_protocolConfig(blockReference: BlockReference): Promise<NearProtocolConfig>;
/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* @deprecated Use `lightClientProof` instead
* @deprecated Use {@link lightClientProof} instead
*/
experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* Gets a light client execution proof for verifying execution outcomes
* @see {@link https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof}
*/
lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
/**
* Directly call the RPC specifying the method and params
* @param method RPC method
* @param params Parameters to the method
* Gets access key changes for a given array of accountIds
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-all)
* @returns {Promise<ChangeResult>}
*/
sendJsonRpc(method: string, params: object): Promise<any>;
accessKeyChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult>;
/**
* Gets single access key changes for a given array of access keys
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-single)
* @returns {Promise<ChangeResult>}
*/
singleAccessKeyChanges(accessKeyArray: AccessKeyWithPublicKey[], blockQuery: BlockReference): Promise<ChangeResult>;
/**
* Gets account changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-account-changes)
* @returns {Promise<ChangeResult>}
*/
accountChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult>;
/**
* Gets contract state changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: If you pass a keyPrefix it must be base64 encoded
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-state-changes)
* @returns {Promise<ChangeResult>}
*/
contractStateChanges(accountIdArray: string[], blockQuery: BlockReference, keyPrefix?: string): Promise<ChangeResult>;
/**
* Gets contract code changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: Change is returned in a base64 encoded WASM file
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-code-changes)
* @returns {Promise<ChangeResult>}
*/
contractCodeChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult>;
/**
* Returns gas price for a specific block_height or block_hash.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#gas-price)
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#gas-price}
*
* @param blockId Block hash or height, or null for latest.
*/
gasPrice(blockId: BlockId | null): Promise<GasPrice>;
/**
* Directly call the RPC specifying the method and params
*
* @param method RPC method
* @param params Parameters to the method
*/
sendJsonRpc<T>(method: string, params: object): Promise<T>;
}

@@ -7,2 +7,7 @@ "use strict";

exports.JsonRpcProvider = exports.ErrorContext = exports.TypedError = void 0;
/**
* This module contains the {@link JsonRpcProvider} client class
* which can be used to interact with the NEAR RPC API.
* @see {@link providers/provider} for a list of request and response types
*/
const depd_1 = __importDefault(require("depd"));

@@ -25,3 +30,10 @@ const provider_1 = require("./provider");

let _nextId = 123;
/**
* Client class to interact with the NEAR RPC API.
* @see {@link https://github.com/near/nearcore/tree/master/chain/jsonrpc}
*/
class JsonRpcProvider extends provider_1.Provider {
/**
* @param url RPC API endpoint URL
*/
constructor(url) {

@@ -32,15 +44,4 @@ super();

/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
*/
async getNetwork() {
return {
name: 'test',
chainId: 'test'
};
}
/**
* Gets the RPC's status
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
* @returns {Promise<NodeStatusResult>}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#general-validator-status}
*/

@@ -51,6 +52,6 @@ async status() {

/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await)
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await}
*
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -62,13 +63,48 @@ async sendTransaction(signedTransaction) {

/**
* Sends a signed transaction to the RPC and immediately returns transaction hash
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-async)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendTransactionAsync(signedTransaction) {
const bytes = signedTransaction.encode();
return this.sendJsonRpc('broadcast_tx_async', [Buffer.from(bytes).toString('base64')]);
}
/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status)
* @param txHash The hash of the transaction
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#transaction-status}
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatus(txHash, accountId) {
if (typeof txHash === 'string') {
return this.txStatusString(txHash, accountId);
}
else {
return this.txStatusUint8Array(txHash, accountId);
}
}
async txStatusUint8Array(txHash, accountId) {
return this.sendJsonRpc('tx', [borsh_1.baseEncode(txHash), accountId]);
}
async txStatusString(txHash, accountId) {
return this.sendJsonRpc('tx', [txHash, accountId]);
}
/**
* Gets a transaction's status from the RPC with receipts
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status-with-receipts)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatusReceipts(txHash, accountId) {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', [borsh_1.baseEncode(txHash), accountId]);
}
/**
* Query the RPC as [shown in the docs](https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts)
* Query the RPC by passing an {@link RpcQueryRequest}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts}
*
* @typeParam T the shape of the returned query response
*/

@@ -91,3 +127,6 @@ async query(...args) {

* Query for block info from the RPC
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#block)
* pass block_id OR finality as blockQuery, not both
* @see {@link https://docs.near.org/docs/interaction/rpc#block}
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/

@@ -105,6 +144,16 @@ async block(blockQuery) {

/**
* Queries for details of a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#chunk)
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#block-details)
*/
async blockChanges(blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc('EXPERIMENTAL_changes_in_block', { block_id: blockId, finality });
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see {@link https://docs.near.org/docs/interaction/rpc#chunk}
*
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/

@@ -115,4 +164,5 @@ async chunk(chunkId) {

/**
* Query validators of the epoch defined by given block id.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status)
* Query validators of the epoch defined by the given block id.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status}
*
* @param blockId Block hash or height, or null for latest.

@@ -124,4 +174,5 @@ */

/**
* Gets EXPERIMENTAL_genesis_config from RPC
* @returns {Promise<NearProtocolConfig>}
* @deprecated
* Gets the genesis config from RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#genesis-config}
*/

@@ -134,4 +185,6 @@ async experimental_genesisConfig() {

/**
* Gets EXPERIMENTAL_protocol_config from RPC
* @returns {Promise<NearProtocolConfig>}
* Gets the protocol config at a block from RPC
* @see {@link }
*
* @param blockReference specifies the block to get the protocol config for
*/

@@ -142,5 +195,3 @@ async experimental_protocolConfig(blockReference) {

/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* @deprecated Use `lightClientProof` instead
* @deprecated Use {@link lightClientProof} instead
*/

@@ -153,4 +204,4 @@ async experimental_lightClientProof(request) {

/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* Gets a light client execution proof for verifying execution outcomes
* @see {@link https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof}
*/

@@ -161,3 +212,95 @@ async lightClientProof(request) {

/**
* Gets access key changes for a given array of accountIds
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-all)
* @returns {Promise<ChangeResult>}
*/
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
});
}
/**
* Gets single access key changes for a given array of access keys
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-single)
* @returns {Promise<ChangeResult>}
*/
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
});
}
/**
* Gets account changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-account-changes)
* @returns {Promise<ChangeResult>}
*/
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
});
}
/**
* Gets contract state changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: If you pass a keyPrefix it must be base64 encoded
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-state-changes)
* @returns {Promise<ChangeResult>}
*/
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
});
}
/**
* Gets contract code changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: Change is returned in a base64 encoded WASM file
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-code-changes)
* @returns {Promise<ChangeResult>}
*/
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
});
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#gas-price}
*
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId) {
return await this.sendJsonRpc('gas_price', [blockId]);
}
/**
* Directly call the RPC specifying the method and params
*
* @param method RPC method

@@ -210,11 +353,3 @@ * @param params Parameters to the method

}
/**
* Returns gas price for a specific block_height or block_hash.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#gas-price)
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId) {
return await this.sendJsonRpc('gas_price', [blockId]);
}
}
exports.JsonRpcProvider = JsonRpcProvider;

@@ -1,3 +0,7 @@

import { Network } from '../utils/network';
/**
* NEAR RPC API request types and responses
* @module
*/
import { SignedTransaction } from '../transaction';
import { PublicKey } from '../utils/key_pair';
export interface SyncInfo {

@@ -81,11 +85,31 @@ latest_block_hash: string;

export interface BlockHeader {
approval_mask: string;
approval_sigs: string;
height: number;
epoch_id: string;
next_epoch_id: string;
hash: string;
height: number;
prev_hash: string;
prev_state_root: string;
chunk_receipts_root: string;
chunk_headers_root: string;
chunk_tx_root: string;
outcome_root: string;
chunks_included: number;
challenges_root: string;
timestamp: number;
total_weight: TotalWeight;
tx_root: string;
timestamp_nanosec: string;
random_value: string;
validator_proposals: any[];
chunk_mask: boolean[];
gas_price: string;
rent_paid: string;
validator_reward: string;
total_supply: string;
challenges_result: any[];
last_final_block: string;
last_ds_final_block: string;
next_bp_hash: string;
block_merkle_root: string;
approvals: string[];
signature: string;
latest_protocol_version: number;
}

@@ -121,2 +145,22 @@ export declare type ChunkHash = string;

}
export interface Chunk {
chunk_hash: string;
prev_block_hash: string;
outcome_root: string;
prev_state_root: string;
encoded_merkle_root: string;
encoded_length: number;
height_created: number;
height_included: number;
shard_id: number;
gas_used: number;
gas_limit: number;
rent_paid: string;
validator_reward: string;
balance_burnt: string;
outgoing_receipts_root: string;
tx_root: string;
validator_proposals: any[];
signature: string;
}
export interface Transaction {

@@ -129,5 +173,18 @@ hash: string;

export interface BlockResult {
author: string;
header: BlockHeader;
transactions: Transaction[];
chunks: Chunk[];
}
export interface BlockChange {
type: string;
account_id: string;
}
export interface BlockChangeResult {
block_hash: string;
changes: BlockChange[];
}
export interface ChangeResult {
block_hash: string;
changes: any[];
}
export interface CurrentEpochValidatorInfo {

@@ -209,10 +266,92 @@ account_id: string;

}
export interface AccessKeyWithPublicKey {
account_id: string;
public_key: string;
}
export interface QueryResponseKind {
block_height: BlockHeight;
block_hash: BlockHash;
}
export interface AccountView extends QueryResponseKind {
amount: string;
locked: string;
code_hash: string;
storage_usage: number;
storage_paid_at: BlockHeight;
}
interface StateItem {
key: string;
value: string;
proof: string[];
}
export interface ViewStateResult extends QueryResponseKind {
values: StateItem[];
proof: string[];
}
export interface CodeResult extends QueryResponseKind {
result: number[];
logs: string[];
}
export interface ContractCodeView extends QueryResponseKind {
code_base64: string;
hash: string;
}
export interface FunctionCallPermissionView {
FunctionCall: {
allowance: string;
receiver_id: string;
method_names: string[];
};
}
export interface AccessKeyView extends QueryResponseKind {
nonce: number;
permission: 'FullAccess' | FunctionCallPermissionView;
}
export interface AccessKeyInfoView {
public_key: PublicKey;
access_key: AccessKeyView;
}
export interface AccessKeyList extends QueryResponseKind {
keys: AccessKeyInfoView[];
}
export interface ViewAccountRequest {
request_type: 'view_account';
account_id: string;
}
export interface ViewCodeRequest {
request_type: 'view_code';
account_id: string;
}
export interface ViewStateRequest {
request_type: 'view_state';
account_id: string;
prefix_base64: string;
}
export interface ViewAccessKeyRequest {
request_type: 'view_access_key';
account_id: string;
public_key: string;
}
export interface ViewAccessKeyListRequest {
request_type: 'view_access_key_list';
account_id: string;
}
export interface CallFunctionRequest {
request_type: 'call_function';
account_id: string;
method_name: string;
args_base64: string;
}
export declare type RpcQueryRequest = (ViewAccountRequest | ViewCodeRequest | ViewStateRequest | ViewAccountRequest | ViewAccessKeyRequest | ViewAccessKeyListRequest | CallFunctionRequest) & BlockReference;
/** @hidden */
export declare abstract class Provider {
abstract getNetwork(): Promise<Network>;
abstract status(): Promise<NodeStatusResult>;
abstract sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
abstract txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
abstract query(params: object): Promise<any>;
abstract query(path: string, data: string): Promise<any>;
abstract sendTransactionAsync(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
abstract txStatus(txHash: Uint8Array | string, accountId: string): Promise<FinalExecutionOutcome>;
abstract txStatusReceipts(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
abstract query<T extends QueryResponseKind>(params: RpcQueryRequest): Promise<T>;
abstract query<T extends QueryResponseKind>(path: string, data: string): Promise<T>;
abstract block(blockQuery: BlockId | BlockReference): Promise<BlockResult>;
abstract blockChanges(blockQuery: BlockId | BlockReference): Promise<BlockChangeResult>;
abstract chunk(chunkId: ChunkId): Promise<ChunkResult>;

@@ -224,4 +363,10 @@ abstract validators(blockId: BlockId): Promise<EpochValidatorInfo>;

abstract gasPrice(blockId: BlockId): Promise<GasPrice>;
abstract accessKeyChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract singleAccessKeyChanges(accessKeyArray: AccessKeyWithPublicKey[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract accountChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract contractStateChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference, keyPrefix: string): Promise<ChangeResult>;
abstract contractCodeChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
}
/** @hidden */
export declare function getTransactionLastResult(txResult: FinalExecutionOutcome): any;
export {};
"use strict";
/**
* NEAR RPC API request types and responses
* @module
*/
Object.defineProperty(exports, "__esModule", { value: true });

@@ -21,5 +25,7 @@ exports.getTransactionLastResult = exports.Provider = exports.IdType = exports.FinalExecutionStatusBasic = exports.ExecutionStatusBasic = void 0;

})(IdType = exports.IdType || (exports.IdType = {}));
/** @hidden */
class Provider {
}
exports.Provider = Provider;
/** @hidden */
function getTransactionLastResult(txResult) {

@@ -26,0 +32,0 @@ if (typeof txResult.status === 'object' && typeof txResult.status.SuccessValue === 'string') {

@@ -44,8 +44,8 @@ {

"AccessKeyNotFound": "Signer \"{{account_id}}\" doesn't have access key with the given public_key {{public_key}}",
"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {{balance}} for operation costing {{cost}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{allowance}} for transaction costing {{cost}}",
"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {{#formatNear}}{{balance}}{{/formatNear}} for operation costing {{#formatNear}}{{cost}}{{/formatNear}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{#formatNear}}{{allowance}}{{/formatNear}} for transaction costing {{#formatNear}}{{cost}}{{/formatNear}}",
"Expired": "Transaction has expired",
"DeleteAccountStaking": "Account {{account_id}} is staking and can not be deleted",
"SignerDoesNotExist": "Signer {{signer_id}} does not exist",
"TriesToStake": "Account {{account_id}} tries to stake {{stake}}, but has staked {{locked}} and only has {{balance}}",
"TriesToStake": "Account {{account_id}} tried to stake {{#formatNear}}{{stake}}{{/formatNear}}, but has staked {{#formatNear}}{{locked}}{{/formatNear}} and only has {{#formatNear}}{{balance}}{{/formatNear}}",
"AddKeyAlreadyExists": "The public key {{public_key}} is already used for an existing access key",

@@ -55,3 +55,3 @@ "InvalidSigner": "Invalid signer account ID {{signer_id}} according to requirements",

"RequiresFullAccess": "The transaction contains more then one action, but it was signed with an access key which allows transaction to apply only one specific action. To apply more then one actions TX must be signed with a full access key",
"TriesToUnstake": "Account {{account_id}} is not yet staked, but tries to unstake",
"TriesToUnstake": "Account {{account_id}} is not yet staked, but tried to unstake",
"InvalidNonce": "Transaction nonce {{tx_nonce}} must be larger than nonce of the used access key {{ak_nonce}}",

@@ -62,4 +62,4 @@ "AccountAlreadyExists": "Can't create a new account {{account_id}}, because it already exists",

"MethodNameMismatch": "Transaction method name {{method_name}} isn't allowed by the access key",
"DeleteAccountHasRent": "Account {{account_id}} can't be deleted. It has {{balance}}, which is enough to cover the rent",
"DeleteAccountHasEnoughBalance": "Account {{account_id}} can't be deleted. It has {{balance}}, which is enough to cover it's storage",
"DeleteAccountHasRent": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover the rent",
"DeleteAccountHasEnoughBalance": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover it's storage",
"InvalidReceiver": "Invalid receiver account ID {{receiver_id}} according to requirements",

@@ -66,0 +66,0 @@ "DeleteKeyDoesNotExist": "Account {{account_id}} tries to remove an access key that doesn't exist",

@@ -9,3 +9,3 @@ /// <reference types="node" />

receiverId: string;
methodNames: String[];
methodNames: string[];
}

@@ -23,3 +23,3 @@ export declare class FullAccessPermission extends Assignable {

export declare function fullAccessKey(): AccessKey;
export declare function functionCallAccessKey(receiverId: string, methodNames: String[], allowance?: BN): AccessKey;
export declare function functionCallAccessKey(receiverId: string, methodNames: string[], allowance?: BN): AccessKey;
export declare class IAction extends Assignable {

@@ -94,2 +94,3 @@ }

* Contains a list of the valid transaction Actions available with this API
* @see {@link https://nomicon.io/RuntimeSpec/Actions.html | Actions Spec}
*/

@@ -96,0 +97,0 @@ export declare class Action extends Enum {

@@ -125,2 +125,3 @@ "use strict";

* Contains a list of the valid transaction Actions available with this API
* @see {@link https://nomicon.io/RuntimeSpec/Actions.html | Actions Spec}
*/

@@ -127,0 +128,0 @@ class Action extends enums_1.Enum {

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

/** @hidden @module */
export declare abstract class Enum {

@@ -2,0 +3,0 @@ enum: string;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Assignable = exports.Enum = void 0;
/** @hidden @module */
class Enum {

@@ -5,0 +6,0 @@ constructor(properties) {

@@ -13,3 +13,2 @@ "use strict";

waitTime *= waitBackoff;
i++;
}

@@ -16,0 +15,0 @@ return null;

import * as key_pair from './key_pair';
import * as network from './network';
import * as serialize from './serialize';

@@ -9,2 +8,2 @@ import * as web from './web';

import { PublicKey, KeyPair, KeyPairEd25519 } from './key_pair';
export { key_pair, network, serialize, web, enums, format, PublicKey, KeyPair, KeyPairEd25519, rpc_errors };
export { key_pair, serialize, web, enums, format, PublicKey, KeyPair, KeyPairEd25519, rpc_errors };

@@ -22,7 +22,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.rpc_errors = exports.KeyPairEd25519 = exports.KeyPair = exports.PublicKey = exports.format = exports.enums = exports.web = exports.serialize = exports.network = exports.key_pair = void 0;
exports.rpc_errors = exports.KeyPairEd25519 = exports.KeyPair = exports.PublicKey = exports.format = exports.enums = exports.web = exports.serialize = exports.key_pair = void 0;
const key_pair = __importStar(require("./key_pair"));
exports.key_pair = key_pair;
const network = __importStar(require("./network"));
exports.network = network;
const serialize = __importStar(require("./serialize"));

@@ -29,0 +27,0 @@ exports.serialize = serialize;

@@ -1,3 +0,4 @@

import { ServerError } from '../generated/rpc_error_types';
export * from '../generated/rpc_error_types';
import { TypedError } from '../utils/errors';
export declare class ServerError extends TypedError {
}
declare class ServerTransactionError extends ServerError {

@@ -10,1 +11,2 @@ transaction_outcome: any;

export declare function getErrorTypeFromErrorMessage(errorMessage: any): "UntypedError" | "CodeDoesNotExist" | "AccountDoesNotExist" | "InvalidNonce" | "AccessKeyDoesNotExist";
export {};
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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.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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -28,11 +6,16 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.getErrorTypeFromErrorMessage = exports.formatError = exports.parseResultError = exports.parseRpcError = void 0;
exports.getErrorTypeFromErrorMessage = exports.formatError = exports.parseResultError = exports.parseRpcError = exports.ServerError = void 0;
const mustache_1 = __importDefault(require("mustache"));
const rpc_error_schema_json_1 = __importDefault(require("../generated/rpc_error_schema.json"));
const error_messages_json_1 = __importDefault(require("../res/error_messages.json"));
const CLASSMAP = __importStar(require("../generated/rpc_error_types"));
const rpc_error_types_1 = require("../generated/rpc_error_types");
__exportStar(require("../generated/rpc_error_types"), exports);
class ServerTransactionError extends rpc_error_types_1.ServerError {
const common_index_1 = require("../common-index");
const errors_1 = require("../utils/errors");
const mustacheHelpers = {
formatNear: () => (n, render) => common_index_1.utils.format.formatNearAmount(render(n))
};
class ServerError extends errors_1.TypedError {
}
exports.ServerError = ServerError;
class ServerTransactionError extends ServerError {
}
function parseRpcError(errorObj) {

@@ -42,3 +25,3 @@ const result = {};

// NOTE: This assumes that all errors extend TypedError
const error = new CLASSMAP[errorClassName](formatError(errorClassName, result), errorClassName);
const error = new ServerError(formatError(errorClassName, result), errorClassName);
Object.assign(error, result);

@@ -60,3 +43,6 @@ return error;

if (typeof error_messages_json_1.default[errorClassName] === 'string') {
return mustache_1.default.render(error_messages_json_1.default[errorClassName], errorData);
return mustache_1.default.render(error_messages_json_1.default[errorClassName], {
...errorData,
...mustacheHelpers
});
}

@@ -63,0 +49,0 @@ return JSON.stringify(errorData);

@@ -13,27 +13,2 @@ "use strict";

const RETRY_NUMBER = 10;
// TODO: Move into separate module and exclude node-fetch kludge from browser build
let fetch;
if (typeof window === 'undefined' || window.name === 'nodejs') {
/* eslint-disable @typescript-eslint/no-var-requires */
const nodeFetch = require('node-fetch');
const http = require('http');
const https = require('https');
/* eslint-enable @typescript-eslint/no-var-requires */
const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
function agent(_parsedURL) {
if (_parsedURL.protocol === 'http:') {
return httpAgent;
}
else {
return httpsAgent;
}
}
fetch = function (resource, init) {
return nodeFetch(resource, { agent: agent(new URL(resource)), ...init });
};
}
else {
fetch = window.fetch;
}
async function fetchJson(connection, json) {

@@ -40,0 +15,0 @@ let url = null;

@@ -13,9 +13,31 @@ import { Account } from './account';

}
/**
* This class is used in conjunction with the {@link BrowserLocalStorageKeyStore}.
* It redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#wallet}
* @example
* ```js
* // create new WalletConnection instance
* const wallet = new WalletConnection(near, 'my-app');
*
* // If not signed in redirect to the NEAR wallet to sign in
* // keys will be stored in the BrowserLocalStorageKeyStore
* if(!wallet.isSingnedIn()) return wallet.requestSignIn()
* ```
*/
export declare class WalletConnection {
/** @hidden */
_walletBaseUrl: string;
/** @hidden */
_authDataKey: string;
/** @hidden */
_keyStore: KeyStore;
/** @hidden */
_authData: any;
/** @hidden */
_networkId: string;
/** @hidden */
_near: Near;
/** @hidden */
_connectedAccount: ConnectedWalletAccount;

@@ -26,3 +48,6 @@ constructor(near: Near, appKeyPrefix: string | null);

* @example
* walletAccount.isSignedIn();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.isSignedIn();
* ```
*/

@@ -33,3 +58,6 @@ isSignedIn(): boolean;

* @example
* walletAccount.getAccountId();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.getAccountId();
* ```
*/

@@ -45,10 +73,11 @@ getAccountId(): any;

* @example
* walletAccount.requestSignIn('account-with-deploy-contract.near', {
* successUrl: "https://example.com/success.html",
* failureUrl: "https://example.com/error.html"
* });
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* // redirects to the NEAR Wallet
* wallet.requestSignIn('account-with-deploy-contract.near');
* ```
*/
requestSignIn(contractIdOrOptions?: string | SignInOptions, title?: string, successUrl?: string, failureUrl?: string): Promise<void>;
/**
* Requests the user to quickly sign for a transaction or batch of transactions
* Requests the user to quickly sign for a transaction or batch of transactions by redirecting to the NEAR wallet.
* @param transactions Array of Transaction objects that will be requested to sign

@@ -59,2 +88,3 @@ * @param callbackUrl The url to navigate to after the user is prompted to sign

/**
* @hidden
* Complete sign in for a given account id and public key. To be invoked by the app when getting a callback from the wallet.

@@ -64,3 +94,3 @@ */

/**
*
* @hidden
* @param accountId The NEAR account owning the given public key

@@ -83,3 +113,3 @@ * @param publicKey The public key being set to the key store

/**
* {@link Account} implementation which redirects to wallet using (@link WalletConnection) when no local key is available.
* {@link Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available.
*/

@@ -89,2 +119,6 @@ export declare class ConnectedWalletAccount extends Account {

constructor(walletConnection: WalletConnection, connection: Connection, accountId: string);
/**
* Sign a transaction by redirecting to the NEAR Wallet
* @see {@link WalletConnection.requestSignTransactions}
*/
protected signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome>;

@@ -91,0 +125,0 @@ /**

@@ -7,2 +7,9 @@ "use strict";

exports.ConnectedWalletAccount = exports.WalletAccount = exports.WalletConnection = void 0;
/**
* The classes in this module are used in conjunction with the {@link BrowserLocalStorageKeyStore}. This module exposes two classes:
* * {@link WalletConnection} which redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
* * {@link ConnectedWalletAccount} is an {@link Account} implementation that uses {@link WalletConnection} to get keys
*
* @module walletAccount
*/
const depd_1 = __importDefault(require("depd"));

@@ -18,2 +25,17 @@ const account_1 = require("./account");

const PENDING_ACCESS_KEY_PREFIX = 'pending_key'; // browser storage key for a pending access key (i.e. key has been generated but we are not sure it was added yet)
/**
* This class is used in conjunction with the {@link BrowserLocalStorageKeyStore}.
* It redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#wallet}
* @example
* ```js
* // create new WalletConnection instance
* const wallet = new WalletConnection(near, 'my-app');
*
* // If not signed in redirect to the NEAR wallet to sign in
* // keys will be stored in the BrowserLocalStorageKeyStore
* if(!wallet.isSingnedIn()) return wallet.requestSignIn()
* ```
*/
class WalletConnection {

@@ -37,3 +59,6 @@ constructor(near, appKeyPrefix) {

* @example
* walletAccount.isSignedIn();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.isSignedIn();
* ```
*/

@@ -46,3 +71,6 @@ isSignedIn() {

* @example
* walletAccount.getAccountId();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.getAccountId();
* ```
*/

@@ -60,6 +88,7 @@ getAccountId() {

* @example
* walletAccount.requestSignIn('account-with-deploy-contract.near', {
* successUrl: "https://example.com/success.html",
* failureUrl: "https://example.com/error.html"
* });
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* // redirects to the NEAR Wallet
* wallet.requestSignIn('account-with-deploy-contract.near');
* ```
*/

@@ -76,2 +105,5 @@ async requestSignIn(contractIdOrOptions = {}, title, successUrl, failureUrl) {

}
/* Throws exception if account does not exist */
const contractAccount = await this._near.account(options.contractId);
await contractAccount.state();
const currentUrl = new URL(window.location.href);

@@ -90,3 +122,3 @@ const newUrl = new URL(this._walletBaseUrl + LOGIN_WALLET_URL_SUFFIX);

/**
* Requests the user to quickly sign for a transaction or batch of transactions
* Requests the user to quickly sign for a transaction or batch of transactions by redirecting to the NEAR wallet.
* @param transactions Array of Transaction objects that will be requested to sign

@@ -106,2 +138,3 @@ * @param callbackUrl The url to navigate to after the user is prompted to sign

/**
* @hidden
* Complete sign in for a given account id and public key. To be invoked by the app when getting a callback from the wallet.

@@ -131,3 +164,3 @@ */

/**
*
* @hidden
* @param accountId The NEAR account owning the given public key

@@ -163,3 +196,3 @@ * @param publicKey The public key being set to the key store

/**
* {@link Account} implementation which redirects to wallet using (@link WalletConnection) when no local key is available.
* {@link Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available.
*/

@@ -172,2 +205,6 @@ class ConnectedWalletAccount extends account_1.Account {

// Overriding Account methods
/**
* Sign a transaction by redirecting to the NEAR Wallet
* @see {@link WalletConnection.requestSignTransactions}
*/
async signAndSendTransaction(receiverId, actions) {

@@ -251,3 +288,3 @@ const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);

if (localKey) {
const accessKey = accessKeys.find(key => key.public_key === localKey.toString());
const accessKey = accessKeys.find(key => key.public_key.toString() === localKey.toString());
if (accessKey && await this.accessKeyMatchesTransaction(accessKey, receiverId, actions)) {

@@ -254,0 +291,0 @@ return accessKey;

{
"name": "near-api-js",
"description": "JavaScript library to interact with NEAR Protocol via RPC API",
"version": "0.39.0",
"repository": {
"type": "git",
"url": "git+https://github.com/near/near-api-js.git"
},
"homepage": "https://github.com/near/near-api-js",
"main": "lib/index.js",
"browser": "lib/browser-index.js",
"types": "lib/index.d.ts",
"dependencies": {
"@types/bn.js": "^5.1.0",
"bn.js": "^5.0.0",
"borsh": "^0.3.1",
"bs58": "^4.0.0",
"depd": "^2.0.0",
"error-polyfill": "^0.1.2",
"http-errors": "^1.7.2",
"js-sha256": "^0.9.0",
"mustache": "^4.0.0",
"node-fetch": "^2.6.1",
"text-encoding-utf-8": "^1.0.2",
"tweetnacl": "^1.0.1"
},
"devDependencies": {
"@types/http-errors": "^1.6.1",
"@typescript-eslint/eslint-plugin": "^2.18.0",
"@typescript-eslint/parser": "^2.18.0",
"browserify": "^16.2.3",
"bundlewatch": "^0.3.1",
"eslint": "^6.5.1",
"in-publish": "^2.0.0",
"jest": "^26.0.1",
"localstorage-memory": "^1.0.3",
"near-hello": "^0.5.1",
"rimraf": "^3.0.0",
"semver": "^7.1.1",
"ts-morph": "^10.0.0",
"typedoc": "^0.19.2",
"typescript": "^3.5.1",
"uglifyify": "^5.0.1"
},
"jest": {
"testEnvironment": "node",
"coverageDirectory": "./coverage/",
"collectCoverage": true
},
"keywords": [],
"license": "(MIT AND Apache-2.0)",
"scripts": {
"dist": "yarn browserify && yarn doc",
"browserify": "browserify browser-exports.js -i node-fetch -i http -i https -o dist/near-api-js.js && browserify browser-exports.js -i node-fetch -g uglifyify -o dist/near-api-js.min.js",
"prebrowserify": "yarn build",
"prepublish": "not-in-install && (yarn build && yarn browserify) || in-install",
"compile": "tsc -p ./tsconfig.json",
"dev": "yarn compile -w",
"doc": "typedoc src && touch docs/.nojekyll",
"build": "yarn compile",
"pretest": "yarn build",
"test": "jest test --runInBand",
"lint": "eslint test && eslint src/**/*.ts",
"fix": "eslint test --fix && eslint src/**/*.ts --fix",
"prefuzz": "yarn build",
"fuzz": "jsfuzz test/fuzz/borsh-roundtrip.js test/fuzz/corpus/"
},
"bundlewatch": {
"files": [
{
"path": "dist/near-api-js.min.js",
"maxSize": "95kB"
}
]
},
"author": "NEAR Inc"
"name": "near-api-js",
"description": "JavaScript library to interact with NEAR Protocol via RPC API",
"version": "0.40.0",
"repository": {
"type": "git",
"url": "git+https://github.com/near/near-api-js.git"
},
"homepage": "https://github.com/near/near-api-js",
"main": "lib/index.js",
"browser": "lib/browser-index.js",
"types": "lib/index.d.ts",
"dependencies": {
"bn.js": "5.1.0",
"borsh": "^0.3.1",
"bs58": "^4.0.0",
"depd": "^2.0.0",
"error-polyfill": "^0.1.2",
"http-errors": "^1.7.2",
"js-sha256": "^0.9.0",
"mustache": "^4.0.0",
"node-fetch": "^2.6.1",
"text-encoding-utf-8": "^1.0.2",
"tweetnacl": "^1.0.1"
},
"devDependencies": {
"@types/bn.js": "^5.1.0",
"@types/http-errors": "^1.6.1",
"@typescript-eslint/eslint-plugin": "^2.18.0",
"@typescript-eslint/parser": "^2.18.0",
"browserify": "^16.2.3",
"bundlewatch": "^0.3.1",
"eslint": "^6.5.1",
"in-publish": "^2.0.0",
"jest": "^26.0.1",
"localstorage-memory": "^1.0.3",
"near-hello": "^0.5.1",
"rimraf": "^3.0.0",
"semver": "^7.1.1",
"ts-morph": "^10.0.0",
"typedoc": "^0.20.35",
"typedoc-neo-theme": "^1.1.0",
"typescript": "^3.5.1",
"uglifyify": "^5.0.1"
},
"jest": {
"testEnvironment": "node",
"coverageDirectory": "./coverage/",
"collectCoverage": true
},
"keywords": [],
"license": "(MIT AND Apache-2.0)",
"scripts": {
"dist": "yarn browserify && yarn doc",
"browserify": "browserify browser-exports.js -i node-fetch -i http -i https -o dist/near-api-js.js && browserify browser-exports.js -i node-fetch -g uglifyify -o dist/near-api-js.min.js",
"prebrowserify": "yarn build",
"prepublish": "not-in-install && (yarn build && yarn browserify) || in-install",
"compile": "tsc -p ./tsconfig.json",
"dev": "yarn compile -w",
"doc": "typedoc src && touch docs/.nojekyll",
"build": "yarn compile",
"pretest": "yarn build",
"test": "jest test --runInBand",
"lint": "eslint test && eslint src/**/*.ts",
"fix": "eslint test --fix && eslint src/**/*.ts --fix",
"prefuzz": "yarn build",
"fuzz": "jsfuzz test/fuzz/borsh-roundtrip.js test/fuzz/corpus/"
},
"bundlewatch": {
"files": [
{
"path": "dist/near-api-js.min.js",
"maxSize": "105kB"
}
]
},
"author": "NEAR Inc"
}

@@ -38,3 +38,3 @@ # near-api-js

# Update error messages
# Update error schema

@@ -44,5 +44,4 @@ Follow next steps:

1. [Change hash for the commit with errors in the nearcore](https://github.com/near/near-api-js/blob/master/gen_error_types.js#L7-L9)
2. Generate new types for errors: `node gen_error_types.js`
3. `yarn fix` fix any issues with linter.
4. `yarn build` to update `lib/**.js` files
2. Fetch new schema: `node fetch_error_schema.js`
3. `yarn build` to update `lib/**.js` files

@@ -49,0 +48,0 @@ # License

@@ -12,4 +12,5 @@ 'use strict';

import { fetchJson } from './utils/web';
import { FunctionCallPermissionView } from './providers/provider';
export const MULTISIG_STORAGE_KEY = '__multisigRequest'
export const MULTISIG_STORAGE_KEY = '__multisigRequest';
export const MULTISIG_ALLOWANCE = new BN(parseNearAmount('1'));

@@ -23,6 +24,6 @@ export const MULTISIG_GAS = new BN('100000000000000');

interface MultisigContract {
get_request_nonce(): any,
list_request_ids(): any,
delete_request({ request_id: Number }): any,
};
get_request_nonce(): any;
list_request_ids(): any;
delete_request({ request_id: Number }): any;
}

@@ -34,5 +35,5 @@ type sendCodeFunction = () => Promise<any>;

// in memory request cache for node w/o localStorage
let storageFallback = {
const storageFallback = {
[MULTISIG_STORAGE_KEY]: null
}
};

@@ -48,3 +49,3 @@ export class AccountMultisig extends Account {

this.onAddRequestResult = options.onAddRequestResult;
this.contract = <MultisigContract>getContract(this);
this.contract = getContract(this) as MultisigContract;
}

@@ -60,7 +61,7 @@

if (this.isDeleteAction(actions)) {
return await super.signAndSendTransaction(accountId, actions)
return await super.signAndSendTransaction(accountId, actions);
}
await this.deleteUnconfirmedRequests()
await this.deleteUnconfirmedRequests();
const requestId = await this.getRequestNonce()
const requestId = await this.getRequestNonce();
this.setRequest({ accountId, requestId, actions });

@@ -78,16 +79,16 @@ const args = Buffer.from(JSON.stringify({

if (this.onAddRequestResult) {
await this.onAddRequestResult(result)
await this.onAddRequestResult(result);
}
return result
return result;
}
async deleteUnconfirmedRequests () {
const { contract } = this
const request_ids = await this.getRequestIds()
const { contract } = this;
const request_ids = await this.getRequestIds();
for (const request_id of request_ids) {
try {
await contract.delete_request({ request_id })
await contract.delete_request({ request_id });
} catch(e) {
console.warn("Attempt to delete an earlier request before 15 minutes failed. Will try again.")
console.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.');
}

@@ -99,3 +100,3 @@ }

async getRequestNonce(): Promise<Number> {
async getRequestNonce(): Promise<number> {
return this.contract.get_request_nonce();

@@ -108,4 +109,4 @@ }

isDeleteAction(actions): Boolean {
return actions && actions[0] && actions[0].functionCall && actions[0].functionCall.methodName === 'delete_request'
isDeleteAction(actions): boolean {
return actions && actions[0] && actions[0].functionCall && actions[0].functionCall.methodName === 'delete_request';
}

@@ -115,5 +116,5 @@

if (this.storage) {
return JSON.parse(this.storage.getItem(MULTISIG_STORAGE_KEY) || `{}`)
return JSON.parse(this.storage.getItem(MULTISIG_STORAGE_KEY) || '{}');
}
return storageFallback[MULTISIG_STORAGE_KEY]
return storageFallback[MULTISIG_STORAGE_KEY];
}

@@ -123,5 +124,5 @@

if (this.storage) {
return this.storage.setItem(MULTISIG_STORAGE_KEY, JSON.stringify(data))
return this.storage.setItem(MULTISIG_STORAGE_KEY, JSON.stringify(data));
}
storageFallback[MULTISIG_STORAGE_KEY] = data
storageFallback[MULTISIG_STORAGE_KEY] = data;
}

@@ -141,3 +142,3 @@ }

public onConfirmResult: Function;
public helperUrl: string = 'https://helper.testnet.near.org';
public helperUrl = 'https://helper.testnet.near.org';

@@ -152,3 +153,3 @@ constructor(connection: Connection, accountId: string, options: any) {

this.onConfirmResult = options.onConfirmResult;
this.contract = <MultisigContract>getContract(this);
this.contract = getContract(this) as MultisigContract;
}

@@ -159,3 +160,3 @@

// TODO: Should following override onRequestResult in superclass instead of doing custom signAndSendTransaction?
await this.sendCode()
await this.sendCode();
const result = await this.promptAndVerify();

@@ -165,3 +166,3 @@ if (this.onConfirmResult) {

}
return result
return result;
}

@@ -172,7 +173,7 @@

async deployMultisig(contractBytes: Uint8Array) {
const { accountId } = this
const { accountId } = this;
const seedOrLedgerKey = (await this.getRecoveryMethods()).data
.filter(({ kind, publicKey }) => (kind === 'phrase' || kind === 'ledger') && publicKey !== null)
.map((rm) => rm.publicKey)
.map((rm) => rm.publicKey);

@@ -182,5 +183,5 @@ const fak2lak = (await this.getAccessKeys())

.map((ak) => ak.public_key)
.map(toPK)
.map(toPK);
const confirmOnlyKey = toPK((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey)
const confirmOnlyKey = toPK((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);

@@ -194,7 +195,7 @@ const newArgs = Buffer.from(JSON.stringify({ 'num_confirmations': 2 }));

deployContract(contractBytes),
]
];
if ((await this.state()).code_hash === '11111111111111111111111111111111') {
actions.push(functionCall('new', newArgs, MULTISIG_GAS, MULTISIG_DEPOSIT),)
actions.push(functionCall('new', newArgs, MULTISIG_GAS, MULTISIG_DEPOSIT),);
}
console.log('deploying multisig contract for', accountId)
console.log('deploying multisig contract for', accountId);
return await super.signAndSendTransactionWithAccount(accountId, actions);

@@ -204,12 +205,13 @@ }

async disable(contractBytes: Uint8Array) {
const { accountId } = this
const accessKeys = await this.getAccessKeys()
const lak2fak = accessKeys.filter(({ access_key }) =>
access_key && access_key.permission && access_key.permission.FunctionCall &&
access_key.permission.FunctionCall.receiver_id === accountId &&
access_key.permission.FunctionCall.method_names &&
access_key.permission.FunctionCall.method_names.length === 4 &&
access_key.permission.FunctionCall.method_names.includes('add_request_and_confirm')
)
const confirmOnlyKey = PublicKey.from((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey)
const { accountId } = this;
const accessKeys = await this.getAccessKeys();
const lak2fak = accessKeys
.filter(({ access_key }) => access_key.permission !== 'FullAccess')
.filter(({ access_key }) => {
const perm = (access_key.permission as FunctionCallPermissionView).FunctionCall;
return perm.receiver_id === accountId &&
perm.method_names.length === 4 &&
perm.method_names.includes('add_request_and_confirm');
});
const confirmOnlyKey = PublicKey.from((await this.postSignedJson('/2fa/getAccessKey', { accountId })).publicKey);
const actions = [

@@ -220,5 +222,5 @@ deleteKey(confirmOnlyKey),

deployContract(contractBytes),
]
console.log('disabling 2fa for', accountId)
return await this.signAndSendTransaction(accountId, actions)
];
console.log('disabling 2fa for', accountId);
return await this.signAndSendTransaction(accountId, actions);
}

@@ -230,3 +232,3 @@

if (this.isDeleteAction(actions)) {
return
return;
}

@@ -239,3 +241,3 @@ const method = await this.get2faMethod();

});
return requestId
return requestId;
}

@@ -249,3 +251,3 @@

const method = await this.get2faMethod();
const securityCode = await this.getCode(method)
const securityCode = await this.getCode(method);
try {

@@ -270,5 +272,5 @@ const result = await this.verifyCode(securityCode);

if (!request) {
throw new Error('no request pending')
throw new Error('no request pending');
}
const { requestId } = request
const { requestId } = request;
return await this.postSignedJson('/2fa/verify', {

@@ -282,15 +284,15 @@ accountId,

async getRecoveryMethods() {
const { accountId } = this
const { accountId } = this;
return {
accountId,
data: await this.postSignedJson('/account/recoveryMethods', { accountId })
}
};
}
async get2faMethod() {
let { data } = await this.getRecoveryMethods()
let { data } = await this.getRecoveryMethods();
if (data && data.length) {
data = data.find((m) => m.kind.indexOf('2fa-') === 0);
}
if (!data) return null
if (!data) return null;
const { kind, detail } = data;

@@ -302,4 +304,4 @@ return { kind, detail };

const { accountId } = this;
const block = await this.connection.provider.block({ finality: 'final' })
const blockNumber = block.header.height.toString()
const block = await this.connection.provider.block({ finality: 'final' });
const blockNumber = block.header.height.toString();
const signed = await this.connection.signer.signMessage(Buffer.from(blockNumber), accountId, this.connection.networkId);

@@ -319,3 +321,3 @@ const blockNumberSignature = Buffer.from(signed.signature).toString('base64');

// helpers
const toPK = (pk) => PublicKey.from(pk)
const toPK = (pk) => PublicKey.from(pk);
const convertPKForContract = (pk) => pk.toString().replace('ed25519:', '');

@@ -362,2 +364,2 @@

return action;
});
});

@@ -1,3 +0,1 @@

'use strict';
import BN from 'bn.js';

@@ -17,3 +15,2 @@ import depd from 'depd';

deleteAccount,
AccessKey,
Action,

@@ -23,3 +20,3 @@ SignedTransaction

import { FinalExecutionOutcome, TypedError, ErrorContext } from './providers';
import { Finality, BlockId } from './providers/provider';
import { Finality, BlockId, ViewStateResult, AccountView, AccessKeyView, CodeResult, AccessKeyList, AccessKeyInfoView, FunctionCallPermissionView } from './providers/provider';
import { Connection } from './connection';

@@ -30,3 +27,3 @@ import { baseDecode, baseEncode } from 'borsh';

import { parseRpcError, parseResultError } from './utils/rpc_errors';
import { ServerError } from './generated/rpc_error_types';
import { ServerError } from './utils/rpc_errors';

@@ -52,9 +49,2 @@ import exponentialBackoff from './utils/exponential-backoff';

export interface AccountState {
amount: string;
code_hash: string;
storage_usage: number;
locked: string;
}
export interface AccountBalance {

@@ -67,2 +57,8 @@ total: string;

export interface AccountAuthorizedApp {
contractId: string;
amount: string;
publicKey: PublicKey;
}
interface ReceiptLogWithFailure {

@@ -79,3 +75,7 @@ receiptIds: [string];

/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
* This class provides common account related RPC calls including signing transactions with a {@link KeyPair}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
* @hint Use {@link WalletConnection} in the browser to redirect to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for Account/key management using the {@link BrowserLocalStorageKeyStore}.
* @see {@link https://nomicon.io/DataStructures/Account.html | Account Spec}
*/

@@ -86,2 +86,3 @@ export class Account {

/** @hidden */
protected get ready(): Promise<void> {

@@ -104,9 +105,14 @@ const deprecate = depd('Account.ready()');

/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
* Returns basic NEAR account information via the `view_account` RPC query method
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-account}
*/
async state(): Promise<AccountState> {
return await this.connection.provider.query(`account/${this.accountId}`, '');
async state(): Promise<AccountView> {
return this.connection.provider.query<AccountView>({
request_type: 'view_account',
account_id: this.accountId,
finality: 'optimistic'
});
}
/** @hidden */
private printLogsAndFailures(contractId: string, results: [ReceiptLogWithFailure]) {

@@ -122,2 +128,3 @@ for (const result of results) {

/** @hidden */
private printLogs(contractId: string, logs: string[], prefix = '') {

@@ -129,2 +136,8 @@ for (const log of logs) {

/**
* Create a signed transaction which can be broadcast to the network
* @param receiverId NEAR account receiving the transaction
* @param actions list of actions to perform as part of the transaction
* @see {@link JsonRpcProvider.sendTransaction}
*/
protected async signTransaction(receiverId: string, actions: Action[]): Promise<[Uint8Array, SignedTransaction]> {

@@ -147,5 +160,7 @@ const accessKeyInfo = await this.findAccessKey(receiverId, actions);

/**
* Sign a transaction to preform a list of actions and broadcast it using the RPC API.
* @see {@link JsonRpcProvider.sendTransaction}
*
* @param receiverId NEAR account receiving the transaction
* @param actions The transaction [Action as described in the spec](https://nomicon.io/RuntimeSpec/Actions.html).
* @returns {Promise<FinalExecutionOutcome>}
* @param actions list of actions to perform as part of the transaction
*/

@@ -203,5 +218,15 @@ protected async signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome> {

accessKeyByPublicKeyCache: { [key: string]: AccessKey } = {}
/** @hidden */
accessKeyByPublicKeyCache: { [key: string]: AccessKeyView } = {}
async findAccessKey(receiverId: string, actions: Action[]): Promise<{publicKey: PublicKey; accessKey: AccessKey}> {
/**
* Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link KeyStore}.
*
* @todo Find matching access key based on transaction (i.e. receiverId and actions)
*
* @param receiverId currently unused (see todo)
* @param actions currently unused (see todo)
* @returns `{ publicKey PublicKey; accessKey: AccessKeyView }`
*/
async findAccessKey(receiverId: string, actions: Action[]): Promise<{publicKey: PublicKey; accessKey: AccessKeyView}> {
// TODO: Find matching access key based on transaction (i.e. receiverId and actions)

@@ -219,3 +244,17 @@ const publicKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);

try {
const accessKey = await this.connection.provider.query(`access_key/${this.accountId}/${publicKey.toString()}`, '');
const accessKey = await this.connection.provider.query<AccessKeyView>({
request_type: 'view_access_key',
account_id: this.accountId,
public_key: publicKey.toString(),
finality: 'optimistic'
});
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if(this.accessKeyByPublicKeyCache[publicKey.toString()]) {
return { publicKey, accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()] };
}
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;

@@ -233,6 +272,7 @@ return { publicKey, accessKey };

/**
* Create a new account and deploy a contract to it
*
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param publicKey The public key to add to the created contract account
* @param data The compiled contract code
* @returns {Promise<Account>}
*/

@@ -249,3 +289,2 @@ async createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: BN): Promise<Account> {

* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -259,3 +298,2 @@ async sendMoney(receiverId: string, amount: BN): Promise<FinalExecutionOutcome> {

* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -269,5 +307,4 @@ async createAccount(newAccountId: string, publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome> {

* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
* @returns void
*/
async deleteAccount(beneficiaryId: string) {
async deleteAccount(beneficiaryId: string): Promise<FinalExecutionOutcome> {
return this.signAndSendTransaction(this.accountId, [deleteAccount(beneficiaryId)]);

@@ -278,3 +315,2 @@ }

* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -292,3 +328,2 @@ async deployContract(data: Uint8Array): Promise<FinalExecutionOutcome> {

* @param deposit amount of NEAR (in yoctoNEAR) to send together with the call
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -302,2 +337,4 @@ async functionCall(contractId: string, methodName: string, args: any, gas?: BN, amount?: BN): Promise<FinalExecutionOutcome> {

/**
* @see {@link https://docs.near.org/docs/concepts/account#access-keys}
* @todo expand this API to support more options.
* @param publicKey A public key to be associated with the contract

@@ -307,4 +344,2 @@ * @param contractId NEAR account where the contract is deployed

* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
* TODO: expand this API to support more options.
*/

@@ -336,5 +371,6 @@ async addKey(publicKey: string | PublicKey, contractId?: string, methodNames?: string|string[], amount?: BN): Promise<FinalExecutionOutcome> {

/**
* @see {@link https://docs.near.org/docs/validator/staking-overview}
*
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -345,2 +381,3 @@ async stake(publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome> {

/** @hidden */
private validateArgs(args: any) {

@@ -358,2 +395,5 @@ const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length;

/**
* Invoke a contract view function using the RPC API.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#call-a-contract-function}
*
* @param contractId NEAR account where the contract is deployed

@@ -367,11 +407,19 @@ * @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code

methodName: string,
args: any,
args: any = {},
{ parse = parseJsonFromRawResponse } = {}
): Promise<any> {
args = args || {};
this.validateArgs(args);
const result = await this.connection.provider.query(`call/${contractId}/${methodName}`, baseEncode(JSON.stringify(args)));
const result = await this.connection.provider.query<CodeResult>({
request_type: 'call_function',
account_id: contractId,
method_name: methodName,
args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),
finality: 'optimistic'
});
if (result.logs) {
this.printLogs(contractId, result.logs);
}
return result.result && result.result.length > 0 && parse(Buffer.from(result.result));

@@ -381,6 +429,5 @@ }

/**
* See https://docs.near.org/docs/develop/front-end/rpc#view-contract-state
*
* Returns the state (key value pairs) of this account's contract based on the key prefix.
* Pass an empty string for prefix if you would like to return the entire state.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-contract-state}
*

@@ -390,8 +437,6 @@ * @param prefix allows to filter which keys should be returned. Empty prefix means all keys. String prefix is utf-8 encoded.

*/
async viewState(prefix: string | Uint8Array, blockQuery: { blockId: BlockId } | { finality: Finality } ): Promise<Array<{ key: Buffer; value: Buffer}>> {
const { blockId, finality } = blockQuery as any || {};
const { values } = await this.connection.provider.query({
async viewState(prefix: string | Uint8Array, blockQuery: { blockId: BlockId } | { finality: Finality } = { finality: 'optimistic' } ): Promise<Array<{ key: Buffer; value: Buffer}>> {
const { values } = await this.connection.provider.query<ViewStateResult>({
request_type: 'view_state',
block_id: blockId,
finality: blockId ? undefined : finality || 'optimistic',
...blockQuery,
account_id: this.accountId,

@@ -408,6 +453,11 @@ prefix_base64: Buffer.from(prefix).toString('base64')

/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
* Get all access keys for the account
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-access-key-list}
*/
async getAccessKeys(): Promise<any> {
const response = await this.connection.provider.query(`access_key/${this.accountId}`, '');
async getAccessKeys(): Promise<AccessKeyInfoView[]> {
const response = await this.connection.provider.query<AccessKeyList>({
request_type: 'view_access_key_list',
account_id: this.accountId,
finality: 'optimistic'
});
// A breaking API change introduced extra information into the

@@ -423,21 +473,20 @@ // response, so it now returns an object with a `keys` field instead

/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
* Returns a list of authorized apps
* @todo update the response value to return all the different keys, not just app keys.
*/
async getAccountDetails(): Promise<any> {
async getAccountDetails(): Promise<{ authorizedApps: AccountAuthorizedApp[] }> {
// TODO: update the response value to return all the different keys, not just app keys.
// Also if we need this function, or getAccessKeys is good enough.
const accessKeys = await this.getAccessKeys();
const result: any = { authorizedApps: [], transactions: [] };
accessKeys.map((item) => {
if (item.access_key.permission.FunctionCall !== undefined) {
const perm = item.access_key.permission.FunctionCall;
result.authorizedApps.push({
contractId: perm.receiver_id,
amount: perm.allowance,
const authorizedApps = accessKeys
.filter(item => item.access_key.permission !== 'FullAccess')
.map(item => {
const perm = (item.access_key.permission as FunctionCallPermissionView);
return {
contractId: perm.FunctionCall.receiver_id,
amount: perm.FunctionCall.allowance,
publicKey: item.public_key,
});
}
});
return result;
};
});
return { authorizedApps };
}

@@ -447,3 +496,2 @@

* Returns calculated account balance
* @returns {Promise<AccountBalance>}
*/

@@ -450,0 +498,0 @@ async getAccountBalance(): Promise<AccountBalance> {

@@ -1,4 +0,27 @@

import { Near, NearConfig } from './near';
/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass: {@link ConnectConfig.keyStore}
*
* Both are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
*
* @module browserConnect
*/
import { Near, NearConfig } from "./near";
export type ConnectConfig = NearConfig & {
export interface ConnectConfig extends NearConfig {
/** @hidden */
keyPath?: string;

@@ -12,2 +35,2 @@ }

return new Near(config);
}
}

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

/** @hidden @module */
export * as keyStores from './key_stores/browser-index';

@@ -2,0 +3,0 @@ export * from './common-index';

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

/** @hidden @module */
import * as providers from './providers';

@@ -2,0 +3,0 @@ import * as utils from './utils';

@@ -0,6 +1,37 @@

/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass:
* 1. {@link ConnectConfig.keyStore}
* 2. {@link ConnectConfig.keyPath}
*
* If all three are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
* @module connect
*/
import { readKeyFile } from './key_stores/unencrypted_file_system_keystore';
import { InMemoryKeyStore, MergeKeyStore } from './key_stores';
import { Near, NearConfig } from './near';
import fetch from './utils/setup-node-fetch';
export type ConnectConfig = NearConfig & {
global.fetch = fetch;
export interface ConnectConfig extends NearConfig {
/**
* Initialize an {@link InMemoryKeyStore} by reading the file at keyPath.
*
* @important {@link ConnectConfig.keyStore | keyStore} and {@link ConnectConfig.deps | deps.keyStore} take priority over keyPath.
*/
keyPath?: string;

@@ -33,2 +64,2 @@ }

return new Near(config);
}
}

@@ -21,4 +21,46 @@ import BN from 'bn.js';

export interface ContractMethods {
/**
* Methods that change state. These methods cost gas and require a signed transaction.
*
* @see {@link Account.functionCall}
*/
changeMethods: string[];
/**
* View methods do not require a signed transaction.
*
* @@see {@link Account.viewFunction}
*/
viewMethods: string[];
}
/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
* Defines a smart contract on NEAR including the change (mutable) and view (non-mutable) methods
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#contract}
* @example
* ```js
* import { Contract } from 'near-api-js';
*
* async function contractExample() {
* const methodOptions = {
* viewMethods: ['getMessageByAccountId'],
* changeMethods: ['addMessage']
* };
* const contract = new Contract(
* wallet.account(),
* 'contract-id.testnet',
* methodOptions
* );
*
* // use a contract view method
* const messages = await contract.getMessages({
* accountId: 'example-account.testnet'
* });
*
* // use a contract change method
* await contract.addMessage({ text: 'My new message' })
* }
* ```
*/

@@ -29,3 +71,8 @@ export class Contract {

constructor(account: Account, contractId: string, options: { viewMethods: string[]; changeMethods: string[] }) {
/**
* @param account NEAR account to sign change method transactions
* @param contractId NEAR account id where the contract is deployed
* @param options NEAR smart contract methods that your application will use. These will be available as `contract.methodName`
*/
constructor(account: Account, contractId: string, options: ContractMethods) {
this.account = account;

@@ -32,0 +79,0 @@ this.contractId = contractId;

@@ -0,3 +1,4 @@

/** @ignore @module */
export * as keyStores from './key_stores/index';
export * from './common-index';
export * from './connect';

@@ -6,6 +6,34 @@ import { KeyStore } from './keystore';

/**
* This class is used to store keys in the browsers local storage.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores } from 'near-api-js';
*
* const keyStore = new keyStores.BrowserLocalStorageKeyStore();
* const config = {
* keyStore, // instance of BrowserLocalStorageKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export class BrowserLocalStorageKeyStore extends KeyStore {
/** @hidden */
private localStorage: any;
/** @hidden */
private prefix: string;
/**
* @param localStorage defaults to window.localStorage
* @param prefix defaults to `near-api-js:keystore:`
*/
constructor(localStorage: any = window.localStorage, prefix = LOCAL_STORAGE_KEY_PREFIX) {

@@ -18,3 +46,3 @@ super();

/**
* Sets a local storage item
* Stores a {@link KeyPair} in local storage.
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -29,3 +57,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -44,3 +72,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Removes a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -54,3 +82,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Removes all items that start with `prefix` from local storage
*/

@@ -99,2 +127,3 @@ async clear(): Promise<void> {

/**
* @hidden
* Helper function to retrieve a local storage key

@@ -109,2 +138,3 @@ * @param networkId The targeted network. (ex. default, betanet, etc…)

/** @hidden */
private *storageKeys(): IterableIterator<string> {

@@ -111,0 +141,0 @@ for (let i = 0; i < this.localStorage.length; i++) {

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

/** @hidden @module */
import { KeyStore } from './keystore';

@@ -3,0 +3,0 @@ import { InMemoryKeyStore } from './in_memory_key_store';

@@ -5,5 +5,30 @@ import { KeyStore } from './keystore';

/**
* Simple in-memory keystore for testing purposes.
* Simple in-memory keystore for mainly for testing purposes.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const keyStore = new keyStores.InMemoryKeyStore();
* keyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const config = {
* keyStore, // instance of InMemoryKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export class InMemoryKeyStore extends KeyStore {
/** @hidden */
private keys: { [key: string]: string };

@@ -17,3 +42,3 @@

/**
* Sets an in-memory storage item
* Stores a {@KeyPair} in in-memory storage item
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -28,3 +53,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from in-memory storage
* Gets a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -43,3 +68,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from in-memory storage
* Removes a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -53,3 +78,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Sets all in-memory keys to empty objects
* Removes all {@link KeyPairs} from in-memory storage
*/

@@ -89,2 +114,3 @@ async clear(): Promise<void> {

/** @hidden */
toString(): string {

@@ -91,0 +117,0 @@ return 'InMemoryKeyStore';

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

/** @ignore @module */
import { KeyStore } from './keystore';

@@ -3,0 +3,0 @@ import { InMemoryKeyStore } from './in_memory_key_store';

import { KeyPair } from '../utils/key_pair';
/**
* Key store interface for `InMemorySigner`.
* KeyStores are passed to {@link Near} via {@link NearConfig}
* and are used by the {@link InMemorySigner} to sign transactions.
*
* @example {@link connect}
*/

@@ -6,0 +9,0 @@ export abstract class KeyStore {

@@ -6,2 +6,32 @@ import { KeyStore } from './keystore';

* Keystore which can be used to merge multiple key stores into one virtual key store.
*
* @example
* ```js
* const { homedir } = require('os');
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const inMemoryKeyStore = new keyStores.InMemoryKeyStore();
* inMemoryKeyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const fileSystemKeyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
*
* const keyStore = new MergeKeyStore([
* inMemoryKeyStore,
* fileSystemKeyStore
* ]);
* const config = {
* keyStore, // instance of MergeKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/

@@ -20,3 +50,3 @@ export class MergeKeyStore extends KeyStore {

/**
* Sets a storage item to the first index of a key store array
* Store a {@link KeyPain} to the first index of a key store array
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -31,3 +61,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from the array of key stores
* Gets a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -48,3 +78,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from the array of key stores
* Removes a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -97,2 +127,3 @@ * @param accountId The NEAR account tied to the key pair

/** @hidden */
toString(): string {

@@ -99,0 +130,0 @@ return `MergeKeyStore(${this.keyStores.join(', ')})`;

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

/** @hidden */
export async function loadJsonFile(filename: string): Promise<any> {

@@ -47,2 +48,3 @@ const content = await readFile(filename);

/** @hidden */
export async function readKeyFile(filename: string): Promise<[string, KeyPair]> {

@@ -58,5 +60,32 @@ const accountInfo = await loadJsonFile(filename);

/**
* This module contains the {@link UnencryptedFileSystemKeyStore} class which is used to store keys on the file system.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* const { homedir } = require('os');
* const { connect, keyStores } = require('near-api-js');
*
* const keyStore = new keyStores.UnencryptedFileSystemKeyStore(`${homedir()}/.near-credentials`);
* const config = {
* keyStore, // instance of UnencryptedFileSystemKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/
export class UnencryptedFileSystemKeyStore extends KeyStore {
/** @hidden */
readonly keyDir: string;
/**
* @param keyDir base directory for key storage. Keys will be stored in `keyDir/networkId/accountId.json`
*/
constructor(keyDir: string) {

@@ -68,3 +97,3 @@ super();

/**
* Sets a storage item in a file, unencrypted
* Store a {@link KeyPair} in an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -81,3 +110,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Gets a key from local storage
* Gets a {@link KeyPair} from an unencrypted file
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -97,3 +126,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes a key from local storage
* Deletes an unencrypted file holding a {@link KeyPair}
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -109,3 +138,3 @@ * @param accountId The NEAR account tied to the key pair

/**
* Removes all items from local storage
* Deletes all unencrypted files from the `keyDir` path.
*/

@@ -120,2 +149,3 @@ async clear(): Promise<void> {

/** @hidden */
private getKeyFilePath(networkId: string, accountId: string): string {

@@ -126,3 +156,3 @@ return `${this.keyDir}/${networkId}/${accountId}.json`;

/**
* Get the network(s) from local storage
* Get the network(s) from files in `keyDir`
* @returns {Promise<string[]>}

@@ -140,3 +170,3 @@ */

/**
* Gets the account(s) from local storage
* Gets the account(s) files in `keyDir/networkId`
* @param networkId The targeted network. (ex. default, betanet, etc…)

@@ -155,2 +185,3 @@ * @returns{Promise<string[]>}

/** @hidden */
toString(): string {

@@ -157,0 +188,0 @@ return `UnencryptedFileSystemKeyStore(${this.keyDir})`;

@@ -0,1 +1,10 @@

/**
* This module contains the main class developers will use to interact with NEAR.
* The {@link Near} class is used to interact with {@link Account | Accounts} through the {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}.
* It is configured via the {@link NearConfig}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
*
* @module near
*/
import BN from 'bn.js';

@@ -10,14 +19,55 @@ import { Account } from './account';

export type NearConfig = {
keyStore?: KeyStore;
signer?: Signer;
deps?: { keyStore: KeyStore };
helperUrl?: string;
initialBalance?: string;
masterAccount?: string;
networkId: string;
nodeUrl: string;
walletUrl?: string;
export interface NearConfig {
/** Holds {@link KeyPair | KeyPairs} for signing transactions */
keyStore?: KeyStore;
/** @hidden */
signer?: Signer;
/** @deprecated use {@link NearConfig.keyStore} */
deps?: { keyStore: KeyStore };
/**
* {@link https://github.com/near/near-contract-helper | NEAR Contract Helper} url used to create accounts if no master account is provided
* @see {@link UrlAccountCreator}
*/
helperUrl?: string;
/**
* The balance transferred from the {@link NearConfig.masterAccount | masterAccount} to a created account
* @see {@link LocalAccountCreator}
*/
initialBalance?: string;
/**
* The account to use when creating new accounts
* @see {@link LocalAccountCreator}
*/
masterAccount?: string;
/**
* {@link KeyPair | KeyPairs} are stored in a {@link KeyStore} under the `networkId` namespace.
*/
networkId: string;
/**
* NEAR RPC API url. used to make JSON RPC calls to interact with NEAR.
* @see {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}
*/
nodeUrl: string;
/**
* NEAR wallet url used to redirect users to their wallet in browser applications.
* @see {@link https://docs.near.org/docs/tools/near-wallet}
*/
walletUrl?: string;
}
/**
* This is the main class developers should use to interact with NEAR.
* @example
* ```js
* const near = new Near(config);
* ```
*/
export class Near {

@@ -48,3 +98,2 @@ readonly config: any;

/**
*
* @param accountId near accountId used to interact with the network.

@@ -58,3 +107,7 @@ */

/**
*
* Create an account using the {@link AccountCreator}. Either:
* * using a masterAccount with {@link LocalAccountCreator}
* * using the helperUrl with {@link UrlAccountCreator}
* @see {@link NearConfig.masterAccount} and {@link NearConfig.helperUrl}-
*
* @param accountId

@@ -72,3 +125,3 @@ * @param publicKey

/**
* @deprecated Use `new nearApi.Contract(yourAccount, contractId, { viewMethods, changeMethods })` instead.
* @deprecated Use {@link Contract} instead.
* @param contractId

@@ -83,3 +136,3 @@ * @param options

/**
* @deprecated Use `yourAccount.sendMoney` instead.
* @deprecated Use {@link Account.sendMoney} instead.
* @param amount

@@ -86,0 +139,0 @@ * @param originator

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

/** @hidden @module */

@@ -2,0 +3,0 @@ import { Provider, FinalExecutionOutcome, ExecutionOutcomeWithId, getTransactionLastResult, FinalExecutionStatusBasic } from './provider';

@@ -0,3 +1,9 @@

/**
* This module contains the {@link JsonRpcProvider} client class
* which can be used to interact with the NEAR RPC API.
* @see {@link providers/provider} for a list of request and response types
*/
import depd from 'depd';
import {
AccessKeyWithPublicKey,
Provider,

@@ -9,2 +15,4 @@ FinalExecutionOutcome,

BlockResult,
BlockChangeResult,
ChangeResult,
ChunkId,

@@ -16,5 +24,5 @@ ChunkResult,

LightClientProofRequest,
GasPrice
GasPrice,
QueryResponseKind
} from './provider';
import { Network } from '../utils/network';
import { ConnectionInfo, fetchJson } from '../utils/web';

@@ -27,2 +35,3 @@ import { TypedError, ErrorContext } from '../utils/errors';

/** @hidden */
export { TypedError, ErrorContext };

@@ -42,5 +51,13 @@

/**
* Client class to interact with the NEAR RPC API.
* @see {@link https://github.com/near/nearcore/tree/master/chain/jsonrpc}
*/
export class JsonRpcProvider extends Provider {
/** @hidden */
readonly connection: ConnectionInfo;
/**
* @param url RPC API endpoint URL
*/
constructor(url?: string) {

@@ -52,16 +69,4 @@ super();

/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
*/
async getNetwork(): Promise<Network> {
return {
name: 'test',
chainId: 'test'
};
}
/**
* Gets the RPC's status
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
* @returns {Promise<NodeStatusResult>}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#general-validator-status}
*/

@@ -73,6 +78,6 @@ async status(): Promise<NodeStatusResult> {

/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await)
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await}
*
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/

@@ -85,4 +90,38 @@ async sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome> {

/**
* Sends a signed transaction to the RPC and immediately returns transaction hash
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-async)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendTransactionAsync(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome> {
const bytes = signedTransaction.encode();
return this.sendJsonRpc('broadcast_tx_async', [Buffer.from(bytes).toString('base64')]);
}
/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status)
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#transaction-status}
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
*/
async txStatus(txHash: Uint8Array | string, accountId: string): Promise<FinalExecutionOutcome> {
if(typeof txHash === 'string') {
return this.txStatusString(txHash, accountId);
} else {
return this.txStatusUint8Array(txHash, accountId);
}
}
private async txStatusUint8Array(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('tx', [baseEncode(txHash), accountId]);
}
private async txStatusString(txHash: string, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('tx', [txHash, accountId]);
}
/**
* Gets a transaction's status from the RPC with receipts
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status-with-receipts)
* @param txHash The hash of the transaction

@@ -92,4 +131,4 @@ * @param accountId The NEAR account that signed the transaction

*/
async txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('tx', [baseEncode(txHash), accountId]);
async txStatusReceipts(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {
return this.sendJsonRpc('EXPERIMENTAL_tx_status', [baseEncode(txHash), accountId]);
}

@@ -99,10 +138,14 @@

* Query the RPC as [shown in the docs](https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts)
* Query the RPC by passing an {@link RpcQueryRequest}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts}
*
* @typeParam T the shape of the returned query response
*/
async query(...args: any[]): Promise<any> {
async query<T extends QueryResponseKind>(...args: any[]): Promise<T> {
let result;
if (args.length === 1) {
result = await this.sendJsonRpc('query', args[0]);
result = await this.sendJsonRpc<T>('query', args[0]);
} else {
const [path, data] = args;
result = await this.sendJsonRpc('query', [path, data]);
result = await this.sendJsonRpc<T>('query', [path, data]);
}

@@ -119,3 +162,6 @@ if (result && result.error) {

* Query for block info from the RPC
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#block)
* pass block_id OR finality as blockQuery, not both
* @see {@link https://docs.near.org/docs/interaction/rpc#block}
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/

@@ -131,3 +177,2 @@ async block(blockQuery: BlockId | BlockReference): Promise<BlockResult> {

}
return this.sendJsonRpc('block', { block_id: blockId, finality });

@@ -137,6 +182,17 @@ }

/**
* Queries for details of a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* See [docs for more info](https://docs.near.org/docs/interaction/rpc#chunk)
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#block-details)
*/
async blockChanges(blockQuery: BlockReference): Promise<BlockChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes_in_block', { block_id: blockId, finality });
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see {@link https://docs.near.org/docs/interaction/rpc#chunk}
*
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/

@@ -148,4 +204,5 @@ async chunk(chunkId: ChunkId): Promise<ChunkResult> {

/**
* Query validators of the epoch defined by given block id.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status)
* Query validators of the epoch defined by the given block id.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status}
*
* @param blockId Block hash or height, or null for latest.

@@ -158,4 +215,5 @@ */

/**
* Gets EXPERIMENTAL_genesis_config from RPC
* @returns {Promise<NearProtocolConfig>}
* @deprecated
* Gets the genesis config from RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#genesis-config}
*/

@@ -169,4 +227,6 @@ async experimental_genesisConfig(): Promise<NearProtocolConfig> {

/**
* Gets EXPERIMENTAL_protocol_config from RPC
* @returns {Promise<NearProtocolConfig>}
* Gets the protocol config at a block from RPC
* @see {@link }
*
* @param blockReference specifies the block to get the protocol config for
*/

@@ -178,5 +238,3 @@ async experimental_protocolConfig(blockReference: BlockReference): Promise<NearProtocolConfig> {

/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* @deprecated Use `lightClientProof` instead
* @deprecated Use {@link lightClientProof} instead
*/

@@ -190,4 +248,4 @@ async experimental_lightClientProof(request: LightClientProofRequest): Promise<LightClientProof> {

/**
* Gets light_client_proof from RPC (https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
* @returns {Promise<LightClientProof>}
* Gets a light client execution proof for verifying execution outcomes
* @see {@link https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof}
*/

@@ -199,7 +257,105 @@ async lightClientProof(request: LightClientProofRequest): Promise<LightClientProof> {

/**
* Gets access key changes for a given array of accountIds
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-all)
* @returns {Promise<ChangeResult>}
*/
async accessKeyChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'all_access_key_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Gets single access key changes for a given array of access keys
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-single)
* @returns {Promise<ChangeResult>}
*/
async singleAccessKeyChanges(accessKeyArray: AccessKeyWithPublicKey[], blockQuery: BlockReference): Promise<ChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'single_access_key_changes',
keys: accessKeyArray,
block_id: blockId,
finality
});
}
/**
* Gets account changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-account-changes)
* @returns {Promise<ChangeResult>}
*/
async accountChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'account_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Gets contract state changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: If you pass a keyPrefix it must be base64 encoded
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-state-changes)
* @returns {Promise<ChangeResult>}
*/
async contractStateChanges(accountIdArray: string[], blockQuery: BlockReference, keyPrefix = ''): Promise<ChangeResult> {
const { finality } = blockQuery as any;
const { blockId } = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'data_changes',
account_ids: accountIdArray,
key_prefix_base64: keyPrefix,
block_id: blockId,
finality
});
}
/**
* Gets contract code changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: Change is returned in a base64 encoded WASM file
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-code-changes)
* @returns {Promise<ChangeResult>}
*/
async contractCodeChanges(accountIdArray: string[], blockQuery: BlockReference): Promise<ChangeResult> {
const {finality} = blockQuery as any;
const {blockId} = blockQuery as any;
return this.sendJsonRpc('EXPERIMENTAL_changes', {
changes_type: 'contract_code_changes',
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#gas-price}
*
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId: BlockId | null): Promise<GasPrice> {
return await this.sendJsonRpc('gas_price', [blockId]);
}
/**
* Directly call the RPC specifying the method and params
*
* @param method RPC method
* @param params Parameters to the method
*/
async sendJsonRpc(method: string, params: object): Promise<any> {
async sendJsonRpc<T>(method: string, params: object): Promise<T> {
const result = await exponentialBackoff(REQUEST_RETRY_WAIT, REQUEST_RETRY_NUMBER, REQUEST_RETRY_WAIT_BACKOFF, async () => {

@@ -220,3 +376,3 @@ try {

}
throw parseRpcError(response.error.data);

@@ -251,11 +407,2 @@ } else {

}
/**
* Returns gas price for a specific block_height or block_hash.
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#gas-price)
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId: BlockId | null): Promise<GasPrice> {
return await this.sendJsonRpc('gas_price', [blockId]);
}
}

@@ -1,3 +0,8 @@

import { Network } from '../utils/network';
/**
* NEAR RPC API request types and responses
* @module
*/
import { SignedTransaction } from '../transaction';
import { PublicKey } from '../utils/key_pair';

@@ -92,11 +97,31 @@ export interface SyncInfo {

export interface BlockHeader {
approval_mask: string;
approval_sigs: string;
height: number;
epoch_id: string;
next_epoch_id: string;
hash: string;
height: number;
prev_hash: string;
prev_state_root: string;
chunk_receipts_root: string;
chunk_headers_root: string;
chunk_tx_root: string;
outcome_root: string;
chunks_included: number;
challenges_root: string;
timestamp: number;
total_weight: TotalWeight;
tx_root: string;
timestamp_nanosec: string;
random_value: string;
validator_proposals: any[];
chunk_mask: boolean[];
gas_price: string;
rent_paid: string;
validator_reward: string;
total_supply: string;
challenges_result: any[];
last_final_block: string;
last_ds_final_block: string;
next_bp_hash: string;
block_merkle_root: string;
approvals: string[];
signature: string;
latest_protocol_version: number;
}

@@ -136,2 +161,23 @@

export interface Chunk {
chunk_hash: string;
prev_block_hash: string;
outcome_root: string;
prev_state_root: string;
encoded_merkle_root: string;
encoded_length: number;
height_created: number;
height_included: number;
shard_id: number;
gas_used: number;
gas_limit: number;
rent_paid: string;
validator_reward: string;
balance_burnt: string;
outgoing_receipts_root: string;
tx_root: string;
validator_proposals: any[];
signature: string;
}
export interface Transaction {

@@ -145,6 +191,22 @@ hash: string;

export interface BlockResult {
author: string;
header: BlockHeader;
transactions: Transaction[];
chunks: Chunk[];
}
export interface BlockChange {
type: string;
account_id: string;
}
export interface BlockChangeResult {
block_hash: string;
changes: BlockChange[];
}
export interface ChangeResult {
block_hash: string;
changes: any[];
}
export interface CurrentEpochValidatorInfo {

@@ -247,12 +309,118 @@ account_id: string;

export interface AccessKeyWithPublicKey {
account_id: string;
public_key: string;
}
export interface QueryResponseKind {
block_height: BlockHeight;
block_hash: BlockHash;
}
export interface AccountView extends QueryResponseKind {
amount: string;
locked: string;
code_hash: string;
storage_usage: number;
storage_paid_at: BlockHeight;
}
interface StateItem {
key: string;
value: string;
proof: string[];
}
export interface ViewStateResult extends QueryResponseKind {
values: StateItem[];
proof: string[];
}
export interface CodeResult extends QueryResponseKind {
result: number[];
logs: string[];
}
export interface ContractCodeView extends QueryResponseKind {
code_base64: string;
hash: string;
}
export interface FunctionCallPermissionView {
FunctionCall: {
allowance: string;
receiver_id: string;
method_names: string[];
};
}
export interface AccessKeyView extends QueryResponseKind {
nonce: number;
permission: 'FullAccess' | FunctionCallPermissionView;
}
export interface AccessKeyInfoView {
public_key: PublicKey;
access_key: AccessKeyView;
}
export interface AccessKeyList extends QueryResponseKind {
keys: AccessKeyInfoView[];
}
export interface ViewAccountRequest {
request_type: 'view_account';
account_id: string;
}
export interface ViewCodeRequest {
request_type: 'view_code';
account_id: string;
}
export interface ViewStateRequest {
request_type: 'view_state';
account_id: string;
prefix_base64: string;
}
export interface ViewAccessKeyRequest {
request_type: 'view_access_key';
account_id: string;
public_key: string;
}
export interface ViewAccessKeyListRequest {
request_type: 'view_access_key_list';
account_id: string;
}
export interface CallFunctionRequest {
request_type: 'call_function';
account_id: string;
method_name: string;
args_base64: string;
}
export type RpcQueryRequest = (ViewAccountRequest |
ViewCodeRequest |
ViewStateRequest |
ViewAccountRequest |
ViewAccessKeyRequest |
ViewAccessKeyListRequest |
CallFunctionRequest) & BlockReference
/** @hidden */
export abstract class Provider {
abstract getNetwork(): Promise<Network>;
abstract status(): Promise<NodeStatusResult>;
abstract sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
abstract txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
abstract query(params: object): Promise<any>;
abstract query(path: string, data: string): Promise<any>;
abstract sendTransactionAsync(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
abstract txStatus(txHash: Uint8Array | string, accountId: string): Promise<FinalExecutionOutcome>;
abstract txStatusReceipts(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
abstract query<T extends QueryResponseKind>(params: RpcQueryRequest): Promise<T>;
abstract query<T extends QueryResponseKind>(path: string, data: string): Promise<T>;
// TODO: BlockQuery type?
abstract block(blockQuery: BlockId | BlockReference): Promise<BlockResult>;
abstract blockChanges(blockQuery: BlockId | BlockReference): Promise<BlockChangeResult>;
abstract chunk(chunkId: ChunkId): Promise<ChunkResult>;

@@ -264,5 +432,11 @@ // TODO: Use BlockQuery?

abstract lightClientProof(request: LightClientProofRequest): Promise<LightClientProof>;
abstract gasPrice(blockId: BlockId): Promise<GasPrice>
abstract gasPrice(blockId: BlockId): Promise<GasPrice>;
abstract accessKeyChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract singleAccessKeyChanges(accessKeyArray: AccessKeyWithPublicKey[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract accountChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
abstract contractStateChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference, keyPrefix: string): Promise<ChangeResult>;
abstract contractCodeChanges(accountIdArray: string[], BlockQuery: BlockId | BlockReference): Promise<ChangeResult>;
}
/** @hidden */
export function getTransactionLastResult(txResult: FinalExecutionOutcome): any {

@@ -269,0 +443,0 @@ if (typeof txResult.status === 'object' && typeof txResult.status.SuccessValue === 'string') {

@@ -44,8 +44,8 @@ {

"AccessKeyNotFound": "Signer \"{{account_id}}\" doesn't have access key with the given public_key {{public_key}}",
"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {{balance}} for operation costing {{cost}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{allowance}} for transaction costing {{cost}}",
"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {{#formatNear}}{{balance}}{{/formatNear}} for operation costing {{#formatNear}}{{cost}}{{/formatNear}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{#formatNear}}{{allowance}}{{/formatNear}} for transaction costing {{#formatNear}}{{cost}}{{/formatNear}}",
"Expired": "Transaction has expired",
"DeleteAccountStaking": "Account {{account_id}} is staking and can not be deleted",
"SignerDoesNotExist": "Signer {{signer_id}} does not exist",
"TriesToStake": "Account {{account_id}} tries to stake {{stake}}, but has staked {{locked}} and only has {{balance}}",
"TriesToStake": "Account {{account_id}} tried to stake {{#formatNear}}{{stake}}{{/formatNear}}, but has staked {{#formatNear}}{{locked}}{{/formatNear}} and only has {{#formatNear}}{{balance}}{{/formatNear}}",
"AddKeyAlreadyExists": "The public key {{public_key}} is already used for an existing access key",

@@ -55,3 +55,3 @@ "InvalidSigner": "Invalid signer account ID {{signer_id}} according to requirements",

"RequiresFullAccess": "The transaction contains more then one action, but it was signed with an access key which allows transaction to apply only one specific action. To apply more then one actions TX must be signed with a full access key",
"TriesToUnstake": "Account {{account_id}} is not yet staked, but tries to unstake",
"TriesToUnstake": "Account {{account_id}} is not yet staked, but tried to unstake",
"InvalidNonce": "Transaction nonce {{tx_nonce}} must be larger than nonce of the used access key {{ak_nonce}}",

@@ -62,4 +62,4 @@ "AccountAlreadyExists": "Can't create a new account {{account_id}}, because it already exists",

"MethodNameMismatch": "Transaction method name {{method_name}} isn't allowed by the access key",
"DeleteAccountHasRent": "Account {{account_id}} can't be deleted. It has {{balance}}, which is enough to cover the rent",
"DeleteAccountHasEnoughBalance": "Account {{account_id}} can't be deleted. It has {{balance}}, which is enough to cover it's storage",
"DeleteAccountHasRent": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover the rent",
"DeleteAccountHasEnoughBalance": "Account {{account_id}} can't be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover it's storage",
"InvalidReceiver": "Invalid receiver account ID {{receiver_id}} according to requirements",

@@ -66,0 +66,0 @@ "DeleteKeyDoesNotExist": "Account {{account_id}} tries to remove an access key that doesn't exist",

@@ -12,3 +12,3 @@ import sha256 from 'js-sha256';

receiverId: string;
methodNames: String[];
methodNames: string[];
}

@@ -32,3 +32,3 @@

export function functionCallAccessKey(receiverId: string, methodNames: String[], allowance?: BN): AccessKey {
export function functionCallAccessKey(receiverId: string, methodNames: string[], allowance?: BN): AccessKey {
return new AccessKey({ nonce: 0, permission: new AccessKeyPermission({functionCall: new FunctionCallPermission({receiverId, allowance, methodNames})})});

@@ -129,2 +129,3 @@ }

* Contains a list of the valid transaction Actions available with this API
* @see {@link https://nomicon.io/RuntimeSpec/Actions.html | Actions Spec}
*/

@@ -131,0 +132,0 @@ export class Action extends Enum {

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

/** @hidden @module */
export abstract class Enum {

@@ -2,0 +3,0 @@ enum: string;

@@ -13,3 +13,2 @@ export default async function exponentialBackoff(startWaitTime, retryNumber, waitBackoff, getResult) {

waitTime *= waitBackoff;
i++;
}

@@ -16,0 +15,0 @@

import * as key_pair from './key_pair';
import * as network from './network';
import * as serialize from './serialize';

@@ -14,3 +13,2 @@ import * as web from './web';

key_pair,
network,
serialize,

@@ -17,0 +15,0 @@ web,

@@ -5,7 +5,12 @@

import messages from '../res/error_messages.json';
import * as CLASSMAP from '../generated/rpc_error_types';
import { ServerError } from '../generated/rpc_error_types';
import { utils } from '../common-index';
import { TypedError } from '../utils/errors';
export * from '../generated/rpc_error_types';
const mustacheHelpers = {
formatNear: () => (n, render) => utils.format.formatNearAmount(render(n))
};
export class ServerError extends TypedError {
}
class ServerTransactionError extends ServerError {

@@ -19,3 +24,3 @@ public transaction_outcome: any;

// NOTE: This assumes that all errors extend TypedError
const error = new CLASSMAP[errorClassName](formatError(errorClassName, result), errorClassName);
const error = new ServerError(formatError(errorClassName, result), errorClassName);
Object.assign(error, result);

@@ -37,3 +42,6 @@ return error;

if (typeof messages[errorClassName] === 'string') {
return Mustache.render(messages[errorClassName], errorData);
return Mustache.render(messages[errorClassName], {
...errorData,
...mustacheHelpers
});
}

@@ -40,0 +48,0 @@ return JSON.stringify(errorData);

@@ -19,29 +19,2 @@ import createError from 'http-errors';

// TODO: Move into separate module and exclude node-fetch kludge from browser build
let fetch;
if (typeof window === 'undefined' || window.name === 'nodejs') {
/* eslint-disable @typescript-eslint/no-var-requires */
const nodeFetch = require('node-fetch');
const http = require('http');
const https = require('https');
/* eslint-enable @typescript-eslint/no-var-requires */
const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
function agent(_parsedURL) {
if (_parsedURL.protocol === 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
fetch = function(resource, init) {
return nodeFetch(resource, { agent: agent(new URL(resource)), ...init });
};
} else {
fetch = window.fetch;
}
export async function fetchJson(connection: string | ConnectionInfo, json?: string): Promise<any> {

@@ -48,0 +21,0 @@ let url: string = null;

@@ -0,1 +1,8 @@

/**
* The classes in this module are used in conjunction with the {@link BrowserLocalStorageKeyStore}. This module exposes two classes:
* * {@link WalletConnection} which redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
* * {@link ConnectedWalletAccount} is an {@link Account} implementation that uses {@link WalletConnection} to get keys
*
* @module walletAccount
*/
import depd from 'depd';

@@ -25,10 +32,37 @@ import { Account } from './account';

/**
* This class is used in conjunction with the {@link BrowserLocalStorageKeyStore}.
* It redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#wallet}
* @example
* ```js
* // create new WalletConnection instance
* const wallet = new WalletConnection(near, 'my-app');
*
* // If not signed in redirect to the NEAR wallet to sign in
* // keys will be stored in the BrowserLocalStorageKeyStore
* if(!wallet.isSingnedIn()) return wallet.requestSignIn()
* ```
*/
export class WalletConnection {
/** @hidden */
_walletBaseUrl: string;
/** @hidden */
_authDataKey: string;
/** @hidden */
_keyStore: KeyStore;
/** @hidden */
_authData: any;
/** @hidden */
_networkId: string;
/** @hidden */
_near: Near;
/** @hidden */
_connectedAccount: ConnectedWalletAccount;

@@ -54,3 +88,6 @@

* @example
* walletAccount.isSignedIn();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.isSignedIn();
* ```
*/

@@ -64,3 +101,6 @@ isSignedIn() {

* @example
* walletAccount.getAccountId();
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.getAccountId();
* ```
*/

@@ -79,6 +119,7 @@ getAccountId() {

* @example
* walletAccount.requestSignIn('account-with-deploy-contract.near', {
* successUrl: "https://example.com/success.html",
* failureUrl: "https://example.com/error.html"
* });
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* // redirects to the NEAR Wallet
* wallet.requestSignIn('account-with-deploy-contract.near');
* ```
*/

@@ -100,2 +141,6 @@ async requestSignIn(

/* Throws exception if account does not exist */
const contractAccount = await this._near.account(options.contractId);
await contractAccount.state();
const currentUrl = new URL(window.location.href);

@@ -115,3 +160,3 @@ const newUrl = new URL(this._walletBaseUrl + LOGIN_WALLET_URL_SUFFIX);

/**
* Requests the user to quickly sign for a transaction or batch of transactions
* Requests the user to quickly sign for a transaction or batch of transactions by redirecting to the NEAR wallet.
* @param transactions Array of Transaction objects that will be requested to sign

@@ -134,2 +179,3 @@ * @param callbackUrl The url to navigate to after the user is prompted to sign

/**
* @hidden
* Complete sign in for a given account id and public key. To be invoked by the app when getting a callback from the wallet.

@@ -160,3 +206,3 @@ */

/**
*
* @hidden
* @param accountId The NEAR account owning the given public key

@@ -195,3 +241,3 @@ * @param publicKey The public key being set to the key store

/**
* {@link Account} implementation which redirects to wallet using (@link WalletConnection) when no local key is available.
* {@link Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available.
*/

@@ -208,2 +254,6 @@ export class ConnectedWalletAccount extends Account {

/**
* Sign a transaction by redirecting to the NEAR Wallet
* @see {@link WalletConnection.requestSignTransactions}
*/
protected async signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome> {

@@ -295,3 +345,3 @@ const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);

if (localKey) {
const accessKey = accessKeys.find(key => key.public_key === localKey.toString());
const accessKey = accessKeys.find(key => key.public_key.toString() === localKey.toString());
if (accessKey && await this.accessKeyMatchesTransaction(accessKey, receiverId, actions)) {

@@ -298,0 +348,0 @@ return accessKey;

@@ -70,2 +70,13 @@

test('findAccessKey returns the same access key when fetched simultaneously', async() => {
const account = await testUtils.createAccount(nearjs);
const [key1, key2] = await Promise.all([
account.findAccessKey(),
account.findAccessKey()
]);
expect(key1.accessKey).toBe(key2.accessKey);
});
describe('errors', () => {

@@ -72,0 +83,0 @@ let oldLog;

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

const nearApi = require('../lib/index');
const testUtils = require('./test-utils');
const BN = require('bn.js');
const base58 = require('bs58');

@@ -41,2 +41,13 @@ jest.setTimeout(20000);

test('json rpc fetch block changes', withProvider(async (provider) => {
let stat = await provider.status();
let height = stat.sync_info.latest_block_height - 1;
let response = await provider.blockChanges({ blockId: height });
console.log(response);
expect(response).toMatchObject({
block_hash: expect.any(String),
changes: expect.any(Array)
});
}));
test('json rpc fetch chunk info', withProvider(async (provider) => {

@@ -57,2 +68,14 @@ let stat = await provider.status();

test('txStatus with string hash and buffer hash', withProvider(async(provider) => {
const near = await testUtils.setUpTestConnection();
const sender = await testUtils.createAccount(near);
const receiver = await testUtils.createAccount(near);
const outcome = await sender.sendMoney(receiver.accountId, new BN('1'));
const responseWithString = await provider.txStatus(outcome.transaction.hash, sender.accountId);
const responseWithUint8Array = await provider.txStatus(base58.decode(outcome.transaction.hash), sender.accountId);
expect(responseWithString).toEqual(outcome);
expect(responseWithUint8Array).toEqual(outcome);
}));
test('json rpc query account', withProvider(async (provider) => {

@@ -65,2 +88,98 @@ const near = await testUtils.setUpTestConnection();

test('json rpc query view_state', withProvider(async (provider) => {
const near = await testUtils.setUpTestConnection();
const account = await testUtils.createAccount(near);
const contract = await testUtils.deployContract(account, testUtils.generateUniqueString('test'));
await contract.setValue({ value: 'hello' });
return testUtils.waitFor(async() => {
const response = await provider.query({
request_type: 'view_state',
finality: 'final',
account_id: contract.contractId,
prefix_base64: ''
});
expect(response).toEqual({
block_height: expect.any(Number),
block_hash: expect.any(String),
values: [
{ key: 'bmFtZQ==', value: 'aGVsbG8=', proof: [] }
],
proof: []
});
});
}));
test('json rpc query view_account', withProvider(async (provider) => {
const response = await provider.query({
request_type: 'view_account',
finality: 'final',
account_id: 'test.near'
});
expect(response).toEqual({
block_height: expect.any(Number),
block_hash: expect.any(String),
amount: expect.any(String),
locked: expect.any(String),
code_hash: '11111111111111111111111111111111',
storage_usage: 182,
storage_paid_at: 0,
});
}));
test('json rpc query view_code', withProvider(async (provider) => {
const near = await testUtils.setUpTestConnection();
const account = await testUtils.createAccount(near);
const contract = await testUtils.deployContract(account, testUtils.generateUniqueString('test'));
return testUtils.waitFor(async() => {
const response = await provider.query({
request_type: 'view_code',
finality: 'final',
account_id: contract.contractId
});
expect(response).toEqual({
block_height: expect.any(Number),
block_hash: expect.any(String),
code_base64: expect.any(String),
hash: expect.any(String)
});
});
}));
test('json rpc query call_function', withProvider(async (provider) => {
const near = await testUtils.setUpTestConnection();
const account = await testUtils.createAccount(near);
const contract = await testUtils.deployContract(account, testUtils.generateUniqueString('test'));
await contract.setValue({ value: 'hello' });
return testUtils.waitFor(async() => {
const response = await provider.query({
request_type: 'call_function',
finality: 'final',
account_id: contract.contractId,
method_name: 'getValue',
args_base64: ''
});
expect(response).toEqual({
block_height: expect.any(Number),
block_hash: expect.any(String),
logs: [],
result: [
34,
104,
101,
108,
108,
111,
34
]
});
});
}));
test('final tx result', async() => {

@@ -67,0 +186,0 @@ const result = {

@@ -85,2 +85,18 @@ const fs = require('fs').promises;

function waitFor(fn) {
const _waitFor = async (count = 10) => {
try {
return await fn();
} catch(e) {
if(count > 0) {
await sleep(500);
return _waitFor(count - 1);
}
else throw e;
}
};
return _waitFor();
}
async function ensureDir(dirpath) {

@@ -102,2 +118,3 @@ try {

sleep,
waitFor,
ensureDir,

@@ -104,0 +121,0 @@ HELLO_WASM_PATH,

const nearApi = require('../../lib/index');
const { ServerError } = require('../../lib/utils/rpc_errors');
const {
parseRpcError,
AccountAlreadyExists,
ReceiverMismatch,
InvalidTxError,
ActionError,
TxExecutionError,
InvalidAccessKeyError,
FunctionCallError,
HostError,
InvalidIteratorIndex,
GasLimitExceeded,
formatError,

@@ -28,4 +19,3 @@ getErrorTypeFromErrorMessage,

let error = parseRpcError(rpc_error);
expect(error instanceof TxExecutionError).toBe(true);
expect(error instanceof AccountAlreadyExists).toBe(true);
expect(error.type === 'AccountAlreadyExists').toBe(true);
expect(error.index).toBe(1);

@@ -50,6 +40,3 @@ expect(error.account_id).toBe('bob.near');

let error = parseRpcError(rpc_error);
expect(error instanceof TxExecutionError).toBe(true);
expect(error instanceof InvalidTxError).toBe(true);
expect(error instanceof InvalidAccessKeyError).toBe(true);
expect(error instanceof ReceiverMismatch).toBe(true);
expect(error.type === 'ReceiverMismatch').toBe(true);
expect(error.ak_receiver).toBe('test.near');

@@ -75,8 +62,3 @@ expect(error.tx_receiver).toBe('bob.near');

let error = parseRpcError(rpc_error);
expect(error instanceof TxExecutionError).toBe(true);
expect(error instanceof AccountAlreadyExists).toBe(false);
expect(error instanceof ActionError).toBe(true);
expect(error instanceof FunctionCallError).toBe(true);
expect(error instanceof HostError).toBe(true);
expect(error instanceof InvalidIteratorIndex).toBe(true);
expect(error.type === 'InvalidIteratorIndex').toBe(true);
expect(error.iterator_index).toBe(42);

@@ -98,9 +80,4 @@ expect(formatError(error.type, error)).toBe('Iterator index 42 does not exist');

let error = parseRpcError(rpc_error);
expect(error instanceof TxExecutionError).toBe(true);
expect(error.type === 'GasLimitExceeded').toBe(true);
expect(error instanceof ActionError).toBe(true);
expect(error instanceof FunctionCallError).toBe(true);
expect(error instanceof HostError).toBe(true);
expect(error instanceof GasLimitExceeded).toBe(true);
expect(formatError(error.type, error)).toBe('Exceeded the maximum amount of gas allowed to burn per contract');

@@ -112,3 +89,3 @@ });

const error = parseRpcError(JSON.parse(errorStr).status.Failure);
expect(error).toEqual(new FunctionCallError('{"index":0,"kind":{"EvmError":"ArgumentParseError"}}'));
expect(error).toEqual(new ServerError('{"index":0,"kind":{"EvmError":"ArgumentParseError"}}'));
});

@@ -131,2 +108,27 @@

});
test('test NotEnoughBalance message uses human readable values', () => {
const error = parseRpcError({
NotEnoughBalance: {
balance: '1000000000000000000000000',
cost: '10000000000000000000000000',
signer_id: 'test.near'
}
});
expect(error.message).toEqual('Sender test.near does not have enough balance 1 for operation costing 10');
});
test('test TriesToStake message uses human readable values', () => {
const error = parseRpcError({
TriesToStake: {
account_id: 'test.near',
balance: '9000000000000000000000000',
locked: '1000000000000000000000000',
stake: '10000000000000000000000000',
}
});
expect(error.message).toEqual('Account test.near tried to stake 10, but has staked 1 and only has 9');
});
});

@@ -32,2 +32,7 @@ const url = require('url');

signer: new nearApi.InMemorySigner(keyStore)
},
account() {
return {
state() {}
};
}

@@ -138,13 +143,12 @@ };

nearFake.connection.provider = {
query(path, data) {
if (path === 'account/signer.near') {
query(params) {
if (params.request_type === 'view_account' && params.account_id === 'signer.near') {
return { };
}
if (path === 'access_key/signer.near') {
if (params.request_type === 'view_access_key_list' && params.account_id === 'signer.near') {
return { keys: accountAccessKeys };
}
if (path.startsWith('access_key/signer.near')) {
const [,,publicKey] = path.split('/');
if (params.request_type === 'view_access_key' && params.account_id === 'signer.near') {
for (let accessKey of accountAccessKeys) {
if (accessKey.public_key === publicKey) {
if (accessKey.public_key === params.public_key) {
return accessKey;

@@ -154,3 +158,3 @@ }

}
fail(`Unexpected query: ${path} ${data}`);
fail(`Unexpected query: ${JSON.stringify(params)}`);
},

@@ -157,0 +161,0 @@ sendTransaction(signedTransaction) {

Sorry, the diff of this file is not supported yet

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