Socket
Socket
Sign inDemoInstall

near-api-js

Package Overview
Dependencies
Maintainers
1
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

near-api-js - npm Package Compare versions

Comparing version 0.23.0 to 0.23.1

dist/near-api-js.js

2

browser-exports.js
require('error-polyfill');
window.nearlib = require('./lib/index');
window.nearApi = require('./lib/browser-index');
window.Buffer = Buffer;

@@ -6,3 +6,3 @@ import BN from 'bn.js';

/**
* Account creator provides interface to specific implementation to acutally create account.
* Account creator provides an interface for implementations to actually create accounts
*/

@@ -16,2 +16,8 @@ export declare abstract class AccountCreator {

constructor(masterAccount: Account, initialBalance: BN);
/**
* Creates an account using a masterAccount, meaning the new account is created from an existing account
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
createAccount(newAccountId: string, publicKey: PublicKey): Promise<void>;

@@ -23,3 +29,10 @@ }

constructor(connection: Connection, helperUrl: string);
/**
* Creates an account using a helperUrl
* This is [hosted here](https://helper.nearprotocol.com) or set up locally with the [near-contract-helper](https://github.com/nearprotocol/near-contract-helper) repository
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
createAccount(newAccountId: string, publicKey: PublicKey): Promise<void>;
}

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

/**
* Account creator provides interface to specific implementation to acutally create account.
* Account creator provides an interface for implementations to actually create accounts
*/

@@ -17,2 +17,8 @@ class AccountCreator {

}
/**
* Creates an account using a masterAccount, meaning the new account is created from an existing account
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
async createAccount(newAccountId, publicKey) {

@@ -29,2 +35,9 @@ await this.masterAccount.createAccount(newAccountId, publicKey, this.initialBalance);

}
/**
* Creates an account using a helperUrl
* This is [hosted here](https://helper.nearprotocol.com) or set up locally with the [near-contract-helper](https://github.com/nearprotocol/near-contract-helper) repository
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
async createAccount(newAccountId, publicKey) {

@@ -31,0 +44,0 @@ await web_1.fetchJson(`${this.helperUrl}/account`, JSON.stringify({ newAccountId, newAccountPublicKey: publicKey.toString() }));

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

}
/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
*/
export declare class Account {

@@ -20,21 +23,102 @@ readonly connection: Connection;

constructor(connection: Connection, accountId: string);
/**
* Helper function when getting the state of a NEAR account
* @returns Promise<void>
*/
fetchState(): Promise<void>;
/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
*/
state(): Promise<AccountState>;
private printLogs;
/**
* @param txHash The transaction hash to retry
* @param accountId The NEAR account sending the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
private retryTxResult;
/**
* @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>}
*/
protected signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome>;
private findAccessKey;
/**
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param data The compiled contract code
* @returns {Promise<Account>}
*/
createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: BN): Promise<Account>;
/**
* @param receiverId NEAR account receiving Ⓝ
* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
sendMoney(receiverId: string, amount: BN): Promise<FinalExecutionOutcome>;
/**
* @param newAccountId NEAR account name to be created
* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/
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
*/
deleteAccount(beneficiaryId: string): Promise<FinalExecutionOutcome>;
/**
* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/
deployContract(data: Uint8Array): Promise<FinalExecutionOutcome>;
/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @param args Any arguments to the contract method, wrapped in JSON
* @param data The compiled contract code
* @param gas An amount of yoctoⓃ attached to cover the gas cost of this function call
* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
*/
functionCall(contractId: string, methodName: string, args: any, gas?: BN, amount?: BN): Promise<FinalExecutionOutcome>;
/**
* @param publicKey A public key to be associated with the contract
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @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.
*/
addKey(publicKey: string | PublicKey, contractId?: string, methodName?: string, amount?: BN): Promise<FinalExecutionOutcome>;
/**
* @param publicKey The public key to be deleted
* @returns {Promise<FinalExecutionOutcome>}
*/
deleteKey(publicKey: string | PublicKey): Promise<FinalExecutionOutcome>;
/**
* @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>;
private validateArgs;
/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code
* @param args Any arguments to the view contract method, wrapped in JSON
* @returns {Promise<any>}
*/
viewFunction(contractId: string, methodName: string, args: any): Promise<any>;
/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
*/
getAccessKeys(): Promise<any>;
/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
*/
getAccountDetails(): Promise<any>;
}

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

// Default value is set to equal to max_prepaid_gas as discussed here:
// https://github.com/nearprotocol/nearlib/pull/191#discussion_r369671912
// https://github.com/near/near-api-js/pull/191#discussion_r369671912
const DEFAULT_FUNC_CALL_GAS = new bn_js_1.default('10000000000000000');

@@ -30,2 +30,5 @@ // Default number of retries before giving up on a transactioin.

}
/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
*/
class Account {

@@ -39,5 +42,13 @@ constructor(connection, accountId) {

}
/**
* Helper function when getting the state of a NEAR account
* @returns Promise<void>
*/
async fetchState() {
this._state = await this.connection.provider.query(`account/${this.accountId}`, '');
}
/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
*/
async state() {

@@ -52,2 +63,7 @@ await this.ready;

}
/**
* @param txHash The transaction hash to retry
* @param accountId The NEAR account sending the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async retryTxResult(txHash, accountId) {

@@ -68,2 +84,7 @@ let result;

}
/**
* @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>}
*/
async signAndSendTransaction(receiverId, actions) {

@@ -122,2 +143,8 @@ await this.ready;

}
/**
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param data The compiled contract code
* @returns {Promise<Account>}
*/
async createAndDeployContract(contractId, publicKey, data, amount) {

@@ -129,5 +156,15 @@ const accessKey = transaction_1.fullAccessKey();

}
/**
* @param receiverId NEAR account receiving Ⓝ
* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendMoney(receiverId, amount) {
return this.signAndSendTransaction(receiverId, [transaction_1.transfer(amount)]);
}
/**
* @param newAccountId NEAR account name to be created
* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/
async createAccount(newAccountId, publicKey, amount) {

@@ -137,8 +174,25 @@ const accessKey = transaction_1.fullAccessKey();

}
/**
* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
* @returns void
*/
async deleteAccount(beneficiaryId) {
return this.signAndSendTransaction(this.accountId, [transaction_1.deleteAccount(beneficiaryId)]);
}
/**
* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/
async deployContract(data) {
return this.signAndSendTransaction(this.accountId, [transaction_1.deployContract(data)]);
}
/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @param args Any arguments to the contract method, wrapped in JSON
* @param data The compiled contract code
* @param gas An amount of yoctoⓃ attached to cover the gas cost of this function call
* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
*/
async functionCall(contractId, methodName, args, gas, amount) {

@@ -149,3 +203,10 @@ args = args || {};

}
// TODO: expand this API to support more options.
/**
* @param publicKey A public key to be associated with the contract
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @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.
*/
async addKey(publicKey, contractId, methodName, amount) {

@@ -161,5 +222,14 @@ let accessKey;

}
/**
* @param publicKey The public key to be deleted
* @returns {Promise<FinalExecutionOutcome>}
*/
async deleteKey(publicKey) {
return this.signAndSendTransaction(this.accountId, [transaction_1.deleteKey(key_pair_1.PublicKey.from(publicKey))]);
}
/**
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
async stake(publicKey, amount) {

@@ -173,2 +243,8 @@ return this.signAndSendTransaction(this.accountId, [transaction_1.stake(amount, key_pair_1.PublicKey.from(publicKey))]);

}
/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code
* @param args Any arguments to the view contract method, wrapped in JSON
* @returns {Promise<any>}
*/
async viewFunction(contractId, methodName, args) {

@@ -183,3 +259,5 @@ args = args || {};

}
/// Returns array of {access_key: AccessKey, public_key: PublicKey} items.
/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
*/
async getAccessKeys() {

@@ -195,2 +273,6 @@ const response = await this.connection.provider.query(`access_key/${this.accountId}`, '');

}
/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
*/
async getAccountDetails() {

@@ -197,0 +279,0 @@ // TODO: update the response value to return all the different keys, not just app keys.

import { Provider } from './providers';
import { Signer } from './signer';
/**
* Connects an account to a given network via a given provider
*/
export declare class Connection {

@@ -8,3 +11,6 @@ readonly networkId: string;

constructor(networkId: string, provider: Provider, signer: Signer);
/**
* @param config Contains connection info details
*/
static fromConfig(config: any): Connection;
}

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

const signer_1 = require("./signer");
/**
* @param config Contains connection info details
* @returns {Provider}
*/
function getProvider(config) {

@@ -14,2 +18,6 @@ switch (config.type) {

}
/**
* @param config Contains connection info details
* @returns {Signer}
*/
function getSigner(config) {

@@ -25,2 +33,5 @@ switch (config.type) {

}
/**
* Connects an account to a given network via a given provider
*/
class Connection {

@@ -32,2 +43,5 @@ constructor(networkId, provider, signer) {

}
/**
* @param config Contains connection info details
*/
static fromConfig(config) {

@@ -34,0 +48,0 @@ const provider = getProvider(config.provider);

import { Account } from './account';
/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
*/
export declare class Contract {

@@ -3,0 +6,0 @@ readonly account: Account;

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

const errors_1 = require("./utils/errors");
/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
*/
class Contract {

@@ -44,2 +47,7 @@ constructor(account, contractId, options) {

exports.Contract = Contract;
/**
* Validation on arguments being a big number from bn.js
* Throws if an argument is not in BN format or otherwise invalid
* @param argMap
*/
function validateBNLike(argMap) {

@@ -46,0 +54,0 @@ const bnLike = 'number, decimal string or BN';

@@ -7,10 +7,45 @@ import { KeyStore } from './keystore';

constructor(localStorage?: any, prefix?: string);
/**
* Sets a local storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void>;
/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
getKey(networkId: string, accountId: string): Promise<KeyPair>;
/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
removeKey(networkId: string, accountId: string): Promise<void>;
/**
* Removes all items from local storage
*/
clear(): Promise<void>;
/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
getNetworks(): Promise<string[]>;
/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
getAccounts(networkId: string): Promise<string[]>;
/**
* Helper function to retrieve a local storage key
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the storage keythat's sought
* @returns {string} An example might be: `nearlib:keystore:near-friend:default`
*/
private storageKeyForSecretKey;
private storageKeys;
}

@@ -12,5 +12,17 @@ "use strict";

}
/**
* Sets a local storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId, accountId, keyPair) {
this.localStorage.setItem(this.storageKeyForSecretKey(networkId, accountId), keyPair.toString());
}
/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId, accountId) {

@@ -23,5 +35,13 @@ const value = this.localStorage.getItem(this.storageKeyForSecretKey(networkId, accountId));

}
/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId, accountId) {
this.localStorage.removeItem(this.storageKeyForSecretKey(networkId, accountId));
}
/**
* Removes all items from local storage
*/
async clear() {

@@ -34,2 +54,6 @@ for (const key of this.storageKeys()) {

}
/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
async getNetworks() {

@@ -45,2 +69,7 @@ const result = new Set();

}
/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId) {

@@ -58,2 +87,8 @@ const result = new Array();

}
/**
* Helper function to retrieve a local storage key
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the storage keythat's sought
* @returns {string} An example might be: `nearlib:keystore:near-friend:default`
*/
storageKeyForSecretKey(networkId, accountId) {

@@ -60,0 +95,0 @@ return `${this.prefix}${accountId}:${networkId}`;

@@ -9,8 +9,37 @@ import { KeyStore } from './keystore';

constructor();
/**
* Sets an in-memory storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void>;
/**
* Gets a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
getKey(networkId: string, accountId: string): Promise<KeyPair>;
/**
* Removes a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
removeKey(networkId: string, accountId: string): Promise<void>;
/**
* Sets all in-memory keys to empty objects
*/
clear(): Promise<void>;
/**
* Get the network(s) from in-memory storage
* @returns {Promise<string[]>}
*/
getNetworks(): Promise<string[]>;
/**
* Gets the account(s) from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
getAccounts(networkId: string): Promise<string[]>;
}

@@ -13,5 +13,17 @@ "use strict";

}
/**
* Sets an in-memory storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId, accountId, keyPair) {
this.keys[`${accountId}:${networkId}`] = keyPair.toString();
}
/**
* Gets a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId, accountId) {

@@ -24,8 +36,20 @@ const value = this.keys[`${accountId}:${networkId}`];

}
/**
* Removes a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId, accountId) {
delete this.keys[`${accountId}:${networkId}`];
}
/**
* Sets all in-memory keys to empty objects
*/
async clear() {
this.keys = {};
}
/**
* Get the network(s) from in-memory storage
* @returns {Promise<string[]>}
*/
async getNetworks() {

@@ -39,2 +63,7 @@ const result = new Set();

}
/**
* Gets the account(s) from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId) {

@@ -41,0 +70,0 @@ const result = new Array();

@@ -12,8 +12,37 @@ import { KeyStore } from './keystore';

constructor(keyStores: KeyStore[]);
/**
* Sets a storage item to the first index of a key store array
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void>;
/**
* Gets a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
getKey(networkId: string, accountId: string): Promise<KeyPair>;
/**
* Removes a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
removeKey(networkId: string, accountId: string): Promise<void>;
/**
* Removes all items from each key store
*/
clear(): Promise<void>;
/**
* Get the network(s) from the array of key stores
* @returns {Promise<string[]>}
*/
getNetworks(): Promise<string[]>;
/**
* Gets the account(s) from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
getAccounts(networkId: string): Promise<string[]>;
}

@@ -15,5 +15,17 @@ "use strict";

}
/**
* Sets a storage item to the first index of a key store array
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId, accountId, keyPair) {
this.keyStores[0].setKey(networkId, accountId, keyPair);
}
/**
* Gets a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId, accountId) {

@@ -28,2 +40,7 @@ for (const keyStore of this.keyStores) {

}
/**
* Removes a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId, accountId) {

@@ -34,2 +51,5 @@ for (const keyStore of this.keyStores) {

}
/**
* Removes all items from each key store
*/
async clear() {

@@ -40,2 +60,6 @@ for (const keyStore of this.keyStores) {

}
/**
* Get the network(s) from the array of key stores
* @returns {Promise<string[]>}
*/
async getNetworks() {

@@ -50,2 +74,7 @@ const result = new Set();

}
/**
* Gets the account(s) from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId) {

@@ -52,0 +81,0 @@ const result = new Set();

@@ -8,9 +8,38 @@ import { KeyPair } from '../utils/key_pair';

constructor(keyDir: string);
/**
* Sets a storage item in a file, unencrypted
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void>;
/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
getKey(networkId: string, accountId: string): Promise<KeyPair>;
/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
removeKey(networkId: string, accountId: string): Promise<void>;
/**
* Removes all items from local storage
*/
clear(): Promise<void>;
private getKeyFilePath;
/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
getNetworks(): Promise<string[]>;
/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
getAccounts(networkId: string): Promise<string[]>;
}

@@ -54,2 +54,8 @@ "use strict";

}
/**
* Sets a storage item in a file, unencrypted
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId, accountId, keyPair) {

@@ -60,2 +66,8 @@ await ensureDir(`${this.keyDir}/${networkId}`);

}
/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId, accountId) {

@@ -69,2 +81,7 @@ // Find key / account id.

}
/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId, accountId) {

@@ -75,2 +92,5 @@ if (await exists(this.getKeyFilePath(networkId, accountId))) {

}
/**
* Removes all items from local storage
*/
async clear() {

@@ -86,2 +106,6 @@ for (const network of await this.getNetworks()) {

}
/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
async getNetworks() {

@@ -95,2 +119,7 @@ const files = await readdir(this.keyDir);

}
/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId) {

@@ -97,0 +126,0 @@ if (!await exists(`${this.keyDir}/${networkId}`)) {

@@ -24,3 +24,3 @@ import BN from 'bn.js';

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

@@ -27,0 +27,0 @@ * @param options

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

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

@@ -59,0 +59,0 @@ * @param options

@@ -10,10 +10,54 @@ import { Provider, FinalExecutionOutcome, NodeStatusResult, BlockId, BlockResult, ChunkId, ChunkResult } from './provider';

constructor(url?: string);
/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
*/
getNetwork(): Promise<Network>;
/**
* Gets the RPC's status
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @returns {Promise<NodeStatusResult>}
*/
status(): Promise<NodeStatusResult>;
/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#send-transaction-wait-until-done)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome>;
/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome>;
/**
* Query the RPC as [shown in the docs](https://docs.nearprotocol.com/docs/interaction/rpc#query)
* @param path Path parameter for the RPC (ex. "contract/my_token")
* @param data Data parameter (ex. "", "AQ4", or whatever is needed)
*/
query(path: string, data: string): Promise<any>;
/**
* Query for block info from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
block(blockId: BlockId): Promise<BlockResult>;
/**
* 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.nearprotocol.com/docs/interaction/rpc#chunk)
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/
chunk(chunkId: ChunkId): Promise<ChunkResult>;
/**
* Directly call the RPC specifying the method and params
* @param method RPC method
* @param params Parameters to the method
*/
sendJsonRpc(method: string, params: any[]): Promise<any>;
}

@@ -16,2 +16,6 @@ "use strict";

}
/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
*/
async getNetwork() {

@@ -23,5 +27,16 @@ return {

}
/**
* Gets the RPC's status
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @returns {Promise<NodeStatusResult>}
*/
async status() {
return this.sendJsonRpc('status', []);
}
/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#send-transaction-wait-until-done)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendTransaction(signedTransaction) {

@@ -31,5 +46,17 @@ const bytes = signedTransaction.encode();

}
/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatus(txHash, accountId) {
return this.sendJsonRpc('tx', [serialize_1.base_encode(txHash), accountId]).then(provider_1.adaptTransactionResult);
}
/**
* Query the RPC as [shown in the docs](https://docs.nearprotocol.com/docs/interaction/rpc#query)
* @param path Path parameter for the RPC (ex. "contract/my_token")
* @param data Data parameter (ex. "", "AQ4", or whatever is needed)
*/
async query(path, data) {

@@ -42,8 +69,25 @@ const result = await this.sendJsonRpc('query', [path, data]);

}
/**
* Query for block info from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
async block(blockId) {
return this.sendJsonRpc('block', [blockId]);
}
/**
* 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.nearprotocol.com/docs/interaction/rpc#chunk)
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/
async chunk(chunkId) {
return this.sendJsonRpc('chunk', [chunkId]);
}
/**
* Directly call the RPC specifying the method and params
* @param method RPC method
* @param params Parameters to the method
*/
async sendJsonRpc(method, params) {

@@ -50,0 +94,0 @@ const request = {

@@ -46,3 +46,3 @@ {

"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {} for operation costing {}",
"NotEnoughAllowance": "Access Key {:?}:{} does not have enough balance {{balance}} for transaction costing {{cost}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{allowance}} for transaction costing {{cost}}",
"Expired": "Transaction has expired",

@@ -49,0 +49,0 @@ "DeleteAccountStaking": "Account {{account_id}} is staking and can not be deleted",

@@ -14,3 +14,3 @@ import { Signature, PublicKey } from './utils/key_pair';

* @param accountId accountId to retrieve from.
* @param networkId network for this accountId.
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/

@@ -22,3 +22,3 @@ abstract getPublicKey(accountId?: string, networkId?: string): Promise<PublicKey>;

* @param accountId accountId to use for signing.
* @param networkId network for this accontId.
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/

@@ -33,5 +33,23 @@ abstract signMessage(message: Uint8Array, accountId?: string, networkId?: string): Promise<Signature>;

constructor(keyStore: KeyStore);
/**
* Creates a public key for the account given
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>}
*/
createKey(accountId: string, networkId: string): Promise<PublicKey>;
/**
* Gets the existing public key for a given account
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>} Returns the public key or null if not found
*/
getPublicKey(accountId?: string, networkId?: string): Promise<PublicKey>;
/**
* @param message A message to be signed, typically a serialized transaction
* @param accountId the NEAR account signing the message
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<Signature>}
*/
signMessage(message: Uint8Array, accountId?: string, networkId?: string): Promise<Signature>;
}

@@ -22,2 +22,8 @@ "use strict";

}
/**
* Creates a public key for the account given
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>}
*/
async createKey(accountId, networkId) {

@@ -28,2 +34,8 @@ const keyPair = key_pair_1.KeyPair.fromRandom('ed25519');

}
/**
* Gets the existing public key for a given account
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>} Returns the public key or null if not found
*/
async getPublicKey(accountId, networkId) {

@@ -36,2 +48,8 @@ const keyPair = await this.keyStore.getKey(networkId, accountId);

}
/**
* @param message A message to be signed, typically a serialized transaction
* @param accountId the NEAR account signing the message
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<Signature>}
*/
async signMessage(message, accountId, networkId) {

@@ -38,0 +56,0 @@ const hash = new Uint8Array(js_sha256_1.default.sha256.array(message));

@@ -81,2 +81,5 @@ /// <reference types="node" />

}
/**
* Contains a list of the valid transaction Actions available with this API
*/
export declare class Action extends Enum {

@@ -83,0 +86,0 @@ createAccount: CreateAccount;

@@ -101,2 +101,5 @@ "use strict";

exports.SignedTransaction = SignedTransaction;
/**
* Contains a list of the valid transaction Actions available with this API
*/
class Action extends enums_1.Enum {

@@ -182,2 +185,9 @@ }

exports.createTransaction = createTransaction;
/**
* Signs a given transaction from an account with given keys, applied to the given network
* @param transaction The Transaction object to sign
* @param signer The {Signer} object that assists with signing keys
* @param accountId The human-readable NEAR account name
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/
async function signTransactionObject(transaction, signer, accountId, networkId) {

@@ -184,0 +194,0 @@ const message = serialize_1.serialize(exports.SCHEMA, transaction);

@@ -16,2 +16,3 @@ import BN from 'bn.js';

* @param fracDigits number of fractional digits to preserve in formatted string. Balance is rounded to match given number of digits.
* @returns Value in Ⓝ
*/

@@ -24,3 +25,4 @@ export declare function formatNearAmount(balance: string, fracDigits?: number): string;

* @param amt decimal string (potentially fractional) denominated in NEAR.
* @returns The parsed yoctoⓃ amount or null if no amount was passed in
*/
export declare function parseNearAmount(amt?: string): string | null;

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

* @param fracDigits number of fractional digits to preserve in formatted string. Balance is rounded to match given number of digits.
* @returns Value in Ⓝ
*/

@@ -50,2 +51,3 @@ function formatNearAmount(balance, fracDigits = exports.NEAR_NOMINATION_EXP) {

* @param amt decimal string (potentially fractional) denominated in NEAR.
* @returns The parsed yoctoⓃ amount or null if no amount was passed in
*/

@@ -66,11 +68,31 @@ function parseNearAmount(amt) {

exports.parseNearAmount = parseNearAmount;
/**
* Removes commas from the input
* @param amount A value or amount that may contain commas
* @returns string The cleaned value
*/
function cleanupAmount(amount) {
return amount.replace(/,/g, '').trim();
}
/**
* Removes .000… from an input
* @param value A value that may contain trailing zeroes in the decimals place
* @returns string The value without the trailing zeros
*/
function trimTrailingZeroes(value) {
return value.replace(/\.?0*$/, '');
}
/**
* Removes leading zeroes from an input
* @param value A value that may contain leading zeroes
* @returns string The value without the leading zeroes
*/
function trimLeadingZeroes(value) {
return value.replace(/^0+/, '');
}
/**
* Returns a human-readable value with commas
* @param value A value that may not contain commas
* @returns string A value with commas
*/
function formatWithCommas(value) {

@@ -77,0 +99,0 @@ const pattern = /(-?\d+)(\d{3})/;

@@ -26,2 +26,6 @@ import { Assignable } from './enums';

abstract getPublicKey(): PublicKey;
/**
* @param curve Name of elliptical curve, case-insensitive
* @returns Random KeyPair based on the curve
*/
static fromRandom(curve: string): KeyPair;

@@ -28,0 +32,0 @@ static fromString(encodedKey: string): KeyPair;

@@ -54,2 +54,6 @@ "use strict";

class KeyPair {
/**
* @param curve Name of elliptical curve, case-insensitive
* @returns Random KeyPair based on the curve
*/
static fromRandom(curve) {

@@ -56,0 +60,0 @@ switch (curve.toUpperCase()) {

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

exports.formatError = formatError;
/**
* Walks through defined schema returning error(s) recursively
* @param errorObj The error to be parsed
* @param schema A defined schema in JSON mapping to the RPC errors
* @param result An object used in recursion or called directly
* @param typeName The human-readable error type name as defined in the JSON mapping
*/
function walkSubtype(errorObj, schema, result, typeName) {

@@ -71,7 +78,15 @@ let error;

}
/**
* Helper function determining if the argument is an object
* @param n Value to check
*/
function isObject(n) {
return Object.prototype.toString.call(n) === '[object Object]';
}
/**
* Helper function determining if the argument is a string
* @param n Value to check
*/
function isString(n) {
return Object.prototype.toString.call(n) === '[object String]';
}

@@ -31,14 +31,20 @@ import { Account } from './account';

* Redirects current page to the wallet authentication page.
* @param {string} contractId contract ID of the application
* @param {string} title name of the application
* @param {string} successUrl url to redirect on success
* @param {string} failureUrl url to redirect on failure
* @param contractId The NEAR account where the contract is deployed
* @param title Name of the application that will appear as requesting access in Wallet
* @param successUrl Optional url to redirect upon success
* @param failureUrl Optional url to redirect upon failure
*
* @example
* walletAccount.requestSignIn(
* myContractId,
* title,
* onSuccessHref,
* onFailureHref);
* account-with-deploy-contract,
* "Guest Book",
* "https://example.com/success.html",
* "https://example.com/error.html");
*/
requestSignIn(contractId: string, title: string, successUrl: string, failureUrl: string): Promise<void>;
requestSignIn(contractId: string, title: string, successUrl?: string, failureUrl?: string): Promise<void>;
/**
* Requests the user to quickly sign for a transaction or batch of transactions
* @param transactions Array of Transaction objects that will be requested to sign
* @param callbackUrl The url to navigate to after the user is prompted to sign
*/
requestSignTransactions(transactions: Transaction[], callbackUrl?: string): Promise<void>;

@@ -49,2 +55,7 @@ /**

_completeSignInWithAccessKey(): Promise<void>;
/**
*
* @param accountId The NEAR account owning the given public key
* @param publicKey The public key being set to the key store
*/
_moveKeyFromTempToPermanent(accountId: string, publicKey: string): Promise<void>;

@@ -57,2 +68,5 @@ /**

signOut(): void;
/**
* Returns the current connected wallet account
*/
account(): ConnectedWalletAccount;

@@ -68,5 +82,18 @@ }

protected signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome>;
/**
* Check if given access key allows the function call or method attempted in transaction
* @param accessKey Array of {access_key: AccessKey, public_key: PublicKey} items
* @param receiverId The NEAR account attempting to have access
* @param actions The action(s) needed to be checked for access
*/
accessKeyMatchesTransaction(accessKey: any, receiverId: string, actions: Action[]): Promise<boolean>;
/**
* Helper function returning the access key (if it exists) to the receiver that grants the designated permission
* @param receiverId The NEAR account seeking the access key for a transaction
* @param actions The action(s) sought to gain access to
* @param localKey A local public key provided to check for access
* @returns Promise<any>
*/
accessKeyForTransaction(receiverId: string, actions: Action[], localKey?: PublicKey): Promise<any>;
}
export {};

@@ -43,12 +43,13 @@ "use strict";

* Redirects current page to the wallet authentication page.
* @param {string} contractId contract ID of the application
* @param {string} title name of the application
* @param {string} successUrl url to redirect on success
* @param {string} failureUrl url to redirect on failure
* @param contractId The NEAR account where the contract is deployed
* @param title Name of the application that will appear as requesting access in Wallet
* @param successUrl Optional url to redirect upon success
* @param failureUrl Optional url to redirect upon failure
*
* @example
* walletAccount.requestSignIn(
* myContractId,
* title,
* onSuccessHref,
* onFailureHref);
* account-with-deploy-contract,
* "Guest Book",
* "https://example.com/success.html",
* "https://example.com/error.html");
*/

@@ -71,2 +72,7 @@ async requestSignIn(contractId, title, successUrl, failureUrl) {

}
/**
* Requests the user to quickly sign for a transaction or batch of transactions
* @param transactions Array of Transaction objects that will be requested to sign
* @param callbackUrl The url to navigate to after the user is prompted to sign
*/
async requestSignTransactions(transactions, callbackUrl) {

@@ -104,2 +110,7 @@ const currentUrl = new URL(window.location.href);

}
/**
*
* @param accountId The NEAR account owning the given public key
* @param publicKey The public key being set to the key store
*/
async _moveKeyFromTempToPermanent(accountId, publicKey) {

@@ -119,2 +130,5 @@ const keyPair = await this._keyStore.getKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + publicKey);

}
/**
* Returns the current connected wallet account
*/
account() {

@@ -174,2 +188,8 @@ if (!this._connectedAccount) {

}
/**
* Check if given access key allows the function call or method attempted in transaction
* @param accessKey Array of {access_key: AccessKey, public_key: PublicKey} items
* @param receiverId The NEAR account attempting to have access
* @param actions The action(s) needed to be checked for access
*/
async accessKeyMatchesTransaction(accessKey, receiverId, actions) {

@@ -187,3 +207,6 @@ const { access_key: { permission } } = accessKey;

const [{ functionCall }] = actions;
return functionCall && (allowedMethods.length === 0 || allowedMethods.includes(functionCall.methodName));
return functionCall &&
functionCall.deposit.toString() === "0" && // TODO: Should support charging amount smaller than allowance?
(allowedMethods.length === 0 || allowedMethods.includes(functionCall.methodName));
// TODO: Handle cases when allowance doesn't have enough to pay for gas
}

@@ -194,2 +217,9 @@ }

}
/**
* Helper function returning the access key (if it exists) to the receiver that grants the designated permission
* @param receiverId The NEAR account seeking the access key for a transaction
* @param actions The action(s) sought to gain access to
* @param localKey A local public key provided to check for access
* @returns Promise<any>
*/
async accessKeyForTransaction(receiverId, actions, localKey) {

@@ -196,0 +226,0 @@ const accessKeys = await this.getAccessKeys();

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

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

"main": "lib/index.js",
"browser": "lib/browser-index.js",
"types": "lib/index.d.ts",

@@ -53,3 +54,3 @@ "dependencies": {

"dist": "yarn browserify && yarn doc",
"browserify": "browserify browser-exports.js -i node-fetch -i http -i https -o dist/nearlib.js && browserify browser-exports.js -i node-fetch -g uglifyify -o dist/nearlib.min.js",
"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",

@@ -64,3 +65,3 @@ "prepublish": "not-in-install && (yarn build && yarn browserify) || in-install",

"fix": "eslint test --fix && eslint src/**/*.ts --fix",
"doc": "typedoc --out docs/nearlib --theme docusaurus src/ --hideBreadcrumbs",
"doc": "typedoc src/",
"prefuzz": "yarn build",

@@ -72,3 +73,3 @@ "fuzz": "jsfuzz test/fuzz/borsh-roundtrip.js test/fuzz/corpus/"

{
"path": "dist/nearlib.min.js",
"path": "dist/near-api-js.min.js",
"maxSize": "85kB"

@@ -75,0 +76,0 @@ }

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

nearlib is a JavaScript/TypeScript library for development of DApps on NEAR platform.
near-api-js is a JavaScript/TypeScript library for development of DApps on NEAR platform.

@@ -45,3 +45,3 @@ ## Install dependencies

1. [Change hash for the commit with errors in the nearcore](https://github.com/nearprotocol/nearlib/blob/master/gen_error_types.js#L7-L9)
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`

@@ -48,0 +48,0 @@ 3. `yarn fix` fix any issues with linter.

@@ -8,3 +8,3 @@ import BN from 'bn.js';

/**
* Account creator provides interface to specific implementation to acutally create account.
* Account creator provides an interface for implementations to actually create accounts
*/

@@ -25,2 +25,8 @@ export abstract class AccountCreator {

/**
* Creates an account using a masterAccount, meaning the new account is created from an existing account
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
async createAccount(newAccountId: string, publicKey: PublicKey): Promise<void> {

@@ -41,2 +47,9 @@ await this.masterAccount.createAccount(newAccountId, publicKey, this.initialBalance);

/**
* Creates an account using a helperUrl
* This is [hosted here](https://helper.nearprotocol.com) or set up locally with the [near-contract-helper](https://github.com/nearprotocol/near-contract-helper) repository
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/
async createAccount(newAccountId: string, publicKey: PublicKey): Promise<void> {

@@ -43,0 +56,0 @@ await fetchJson(`${this.helperUrl}/account`, JSON.stringify({ newAccountId, newAccountPublicKey: publicKey.toString() }));

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

// Default value is set to equal to max_prepaid_gas as discussed here:
// https://github.com/nearprotocol/nearlib/pull/191#discussion_r369671912
// https://github.com/near/near-api-js/pull/191#discussion_r369671912
const DEFAULT_FUNC_CALL_GAS = new BN('10000000000000000');

@@ -42,2 +42,5 @@

/**
* More information on [the Account spec](https://nomicon.io/DataStructures/Account.html)
*/
export class Account {

@@ -58,2 +61,6 @@ readonly connection: Connection;

/**
* Helper function when getting the state of a NEAR account
* @returns Promise<void>
*/
async fetchState(): Promise<void> {

@@ -63,2 +70,6 @@ this._state = await this.connection.provider.query(`account/${this.accountId}`, '');

/**
* Returns the state of a NEAR account
* @returns {Promise<AccountState>}
*/
async state(): Promise<AccountState> {

@@ -75,2 +86,7 @@ await this.ready;

/**
* @param txHash The transaction hash to retry
* @param accountId The NEAR account sending the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
private async retryTxResult(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {

@@ -92,2 +108,7 @@ let result;

/**
* @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>}
*/
protected async signAndSendTransaction(receiverId: string, actions: Action[]): Promise<FinalExecutionOutcome> {

@@ -157,2 +178,8 @@ await this.ready;

/**
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add while signing and sending the transaction
* @param data The compiled contract code
* @returns {Promise<Account>}
*/
async createAndDeployContract(contractId: string, publicKey: string | PublicKey, data: Uint8Array, amount: BN): Promise<Account> {

@@ -165,2 +192,7 @@ const accessKey = fullAccessKey();

/**
* @param receiverId NEAR account receiving Ⓝ
* @param amount Amount to send in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendMoney(receiverId: string, amount: BN): Promise<FinalExecutionOutcome> {

@@ -170,2 +202,7 @@ return this.signAndSendTransaction(receiverId, [transfer(amount)]);

/**
* @param newAccountId NEAR account name to be created
* @param publicKey A public key created from the masterAccount
* @returns {Promise<FinalExecutionOutcome>}
*/
async createAccount(newAccountId: string, publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome> {

@@ -176,2 +213,6 @@ const accessKey = fullAccessKey();

/**
* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
* @returns void
*/
async deleteAccount(beneficiaryId: string) {

@@ -181,2 +222,6 @@ return this.signAndSendTransaction(this.accountId, [deleteAccount(beneficiaryId)]);

/**
* @param data The compiled contract code
* @returns {Promise<FinalExecutionOutcome>}
*/
async deployContract(data: Uint8Array): Promise<FinalExecutionOutcome> {

@@ -186,2 +231,11 @@ return this.signAndSendTransaction(this.accountId, [deployContract(data)]);

/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @param args Any arguments to the contract method, wrapped in JSON
* @param data The compiled contract code
* @param gas An amount of yoctoⓃ attached to cover the gas cost of this function call
* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
* @returns {Promise<FinalExecutionOutcome>}
*/
async functionCall(contractId: string, methodName: string, args: any, gas?: BN, amount?: BN): Promise<FinalExecutionOutcome> {

@@ -193,3 +247,10 @@ args = args || {};

// TODO: expand this API to support more options.
/**
* @param publicKey A public key to be associated with the contract
* @param contractId NEAR account where the contract is deployed
* @param methodName The method name on the contract as it is written in the contract code
* @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.
*/
async addKey(publicKey: string | PublicKey, contractId?: string, methodName?: string, amount?: BN): Promise<FinalExecutionOutcome> {

@@ -205,2 +266,6 @@ let accessKey;

/**
* @param publicKey The public key to be deleted
* @returns {Promise<FinalExecutionOutcome>}
*/
async deleteKey(publicKey: string | PublicKey): Promise<FinalExecutionOutcome> {

@@ -210,2 +275,7 @@ return this.signAndSendTransaction(this.accountId, [deleteKey(PublicKey.from(publicKey))]);

/**
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
* @returns {Promise<FinalExecutionOutcome>}
*/
async stake(publicKey: string | PublicKey, amount: BN): Promise<FinalExecutionOutcome> {

@@ -221,2 +291,8 @@ return this.signAndSendTransaction(this.accountId, [stake(amount, PublicKey.from(publicKey))]);

/**
* @param contractId NEAR account where the contract is deployed
* @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code
* @param args Any arguments to the view contract method, wrapped in JSON
* @returns {Promise<any>}
*/
async viewFunction(contractId: string, methodName: string, args: any): Promise<any> {

@@ -232,3 +308,5 @@ args = args || {};

/// Returns array of {access_key: AccessKey, public_key: PublicKey} items.
/**
* @returns array of {access_key: AccessKey, public_key: PublicKey} items.
*/
async getAccessKeys(): Promise<any> {

@@ -245,2 +323,6 @@ const response = await this.connection.provider.query(`access_key/${this.accountId}`, '');

/**
* Returns account details in terms of authorized apps and transactions
* @returns {Promise<any>}
*/
async getAccountDetails(): Promise<any> {

@@ -247,0 +329,0 @@ // TODO: update the response value to return all the different keys, not just app keys.

import { Provider, JsonRpcProvider } from './providers';
import { Signer, InMemorySigner } from './signer';
/**
* @param config Contains connection info details
* @returns {Provider}
*/
function getProvider(config: any): Provider {

@@ -13,2 +17,6 @@ switch (config.type) {

/**
* @param config Contains connection info details
* @returns {Signer}
*/
function getSigner(config: any): Signer {

@@ -25,2 +33,5 @@ switch (config.type) {

/**
* Connects an account to a given network via a given provider
*/
export class Connection {

@@ -37,2 +48,5 @@ readonly networkId: string;

/**
* @param config Contains connection info details
*/
static fromConfig(config: any): Connection {

@@ -39,0 +53,0 @@ const provider = getProvider(config.provider);

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

/**
* Defines a smart contract on NEAR including the mutable and non-mutable methods
*/
export class Contract {

@@ -44,2 +47,7 @@ readonly account: Account;

/**
* Validation on arguments being a big number from bn.js
* Throws if an argument is not in BN format or otherwise invalid
* @param argMap
*/
function validateBNLike(argMap: { [name: string]: any }) {

@@ -46,0 +54,0 @@ const bnLike = 'number, decimal string or BN';

@@ -16,2 +16,8 @@ import { KeyStore } from './keystore';

/**
* Sets a local storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void> {

@@ -21,2 +27,8 @@ this.localStorage.setItem(this.storageKeyForSecretKey(networkId, accountId), keyPair.toString());

/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId: string, accountId: string): Promise<KeyPair> {

@@ -30,2 +42,7 @@ const value = this.localStorage.getItem(this.storageKeyForSecretKey(networkId, accountId));

/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId: string, accountId: string): Promise<void> {

@@ -35,2 +52,5 @@ this.localStorage.removeItem(this.storageKeyForSecretKey(networkId, accountId));

/**
* Removes all items from local storage
*/
async clear(): Promise<void> {

@@ -44,2 +64,6 @@ for (const key of this.storageKeys()) {

/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
async getNetworks(): Promise<string[]> {

@@ -56,2 +80,7 @@ const result = new Set<string>();

/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId: string): Promise<string[]> {

@@ -70,2 +99,8 @@ const result = new Array<string>();

/**
* Helper function to retrieve a local storage key
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the storage keythat's sought
* @returns {string} An example might be: `nearlib:keystore:near-friend:default`
*/
private storageKeyForSecretKey(networkId: string, accountId: string): string {

@@ -72,0 +107,0 @@ return `${this.prefix}${accountId}:${networkId}`;

@@ -15,2 +15,8 @@ import { KeyStore } from './keystore';

/**
* Sets an in-memory storage item
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void> {

@@ -20,2 +26,8 @@ this.keys[`${accountId}:${networkId}`] = keyPair.toString();

/**
* Gets a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId: string, accountId: string): Promise<KeyPair> {

@@ -29,2 +41,7 @@ const value = this.keys[`${accountId}:${networkId}`];

/**
* Removes a key from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId: string, accountId: string): Promise<void> {

@@ -34,2 +51,5 @@ delete this.keys[`${accountId}:${networkId}`];

/**
* Sets all in-memory keys to empty objects
*/
async clear(): Promise<void> {

@@ -39,2 +59,6 @@ this.keys = {};

/**
* Get the network(s) from in-memory storage
* @returns {Promise<string[]>}
*/
async getNetworks(): Promise<string[]> {

@@ -49,2 +73,7 @@ const result = new Set<string>();

/**
* Gets the account(s) from in-memory storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId: string): Promise<string[]> {

@@ -51,0 +80,0 @@ const result = new Array<string>();

@@ -18,2 +18,8 @@ import { KeyStore } from './keystore';

/**
* Sets a storage item to the first index of a key store array
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void> {

@@ -23,2 +29,8 @@ this.keyStores[0].setKey(networkId, accountId, keyPair);

/**
* Gets a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId: string, accountId: string): Promise<KeyPair> {

@@ -33,3 +45,8 @@ for (const keyStore of this.keyStores) {

}
/**
* Removes a key from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId: string, accountId: string): Promise<void> {

@@ -40,3 +57,6 @@ for (const keyStore of this.keyStores) {

}
/**
* Removes all items from each key store
*/
async clear(): Promise<void> {

@@ -47,3 +67,7 @@ for (const keyStore of this.keyStores) {

}
/**
* Get the network(s) from the array of key stores
* @returns {Promise<string[]>}
*/
async getNetworks(): Promise<string[]> {

@@ -58,3 +82,8 @@ const result = new Set<string>();

}
/**
* Gets the account(s) from the array of key stores
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId: string): Promise<string[]> {

@@ -61,0 +90,0 @@ const result = new Set<string>();

@@ -62,2 +62,8 @@ import fs from 'fs';

/**
* Sets a storage item in a file, unencrypted
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/
async setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise<void> {

@@ -69,2 +75,8 @@ await ensureDir(`${this.keyDir}/${networkId}`);

/**
* Gets a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/
async getKey(networkId: string, accountId: string): Promise<KeyPair> {

@@ -79,2 +91,7 @@ // Find key / account id.

/**
* Removes a key from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/
async removeKey(networkId: string, accountId: string): Promise<void> {

@@ -86,2 +103,5 @@ if (await exists(this.getKeyFilePath(networkId, accountId))) {

/**
* Removes all items from local storage
*/
async clear(): Promise<void> {

@@ -99,2 +119,6 @@ for (const network of await this.getNetworks()) {

/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/
async getNetworks(): Promise<string[]> {

@@ -109,2 +133,7 @@ const files: string[] = await readdir(this.keyDir);

/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns{Promise<string[]>}
*/
async getAccounts(networkId: string): Promise<string[]> {

@@ -111,0 +140,0 @@ if (!await exists(`${this.keyDir}/${networkId}`)) {

@@ -59,3 +59,3 @@

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

@@ -62,0 +62,0 @@ * @param options

@@ -25,2 +25,6 @@ import {

/**
* Get the current network (ex. test, beta, etc…)
* @returns {Promise<Network>}
*/
async getNetwork(): Promise<Network> {

@@ -33,2 +37,7 @@ return {

/**
* Gets the RPC's status
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @returns {Promise<NodeStatusResult>}
*/
async status(): Promise<NodeStatusResult> {

@@ -38,2 +47,8 @@ return this.sendJsonRpc('status', []);

/**
* Sends a signed transaction to the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#send-transaction-wait-until-done)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/
async sendTransaction(signedTransaction: SignedTransaction): Promise<FinalExecutionOutcome> {

@@ -44,2 +59,9 @@ const bytes = signedTransaction.encode();

/**
* Gets a transaction's status from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#status)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatus(txHash: Uint8Array, accountId: string): Promise<FinalExecutionOutcome> {

@@ -49,2 +71,7 @@ return this.sendJsonRpc('tx', [base_encode(txHash), accountId]).then(adaptTransactionResult);

/**
* Query the RPC as [shown in the docs](https://docs.nearprotocol.com/docs/interaction/rpc#query)
* @param path Path parameter for the RPC (ex. "contract/my_token")
* @param data Data parameter (ex. "", "AQ4", or whatever is needed)
*/
async query(path: string, data: string): Promise<any> {

@@ -58,2 +85,8 @@ const result = await this.sendJsonRpc('query', [path, data]);

/**
* Query for block info from the RPC
* See [docs for more info](https://docs.nearprotocol.com/docs/interaction/rpc#block)
* @param blockId Block hash or height
* @returns {Promise<BlockResult>}
*/
async block(blockId: BlockId): Promise<BlockResult> {

@@ -63,2 +96,8 @@ return this.sendJsonRpc('block', [blockId]);

/**
* 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.nearprotocol.com/docs/interaction/rpc#chunk)
* @param chunkId Hash of a chunk ID or shard ID
* @returns {Promise<ChunkResult>}
*/
async chunk(chunkId: ChunkId): Promise<ChunkResult> {

@@ -68,2 +107,7 @@ return this.sendJsonRpc('chunk', [chunkId]);

/**
* Directly call the RPC specifying the method and params
* @param method RPC method
* @param params Parameters to the method
*/
async sendJsonRpc(method: string, params: any[]): Promise<any> {

@@ -70,0 +114,0 @@ const request = {

@@ -46,3 +46,3 @@ {

"NotEnoughBalance": "Sender {{signer_id}} does not have enough balance {} for operation costing {}",
"NotEnoughAllowance": "Access Key {:?}:{} does not have enough balance {{balance}} for transaction costing {{cost}}",
"NotEnoughAllowance": "Access Key {account_id}:{public_key} does not have enough balance {{allowance}} for transaction costing {{cost}}",
"Expired": "Transaction has expired",

@@ -49,0 +49,0 @@ "DeleteAccountStaking": "Account {{account_id}} is staking and can not be deleted",

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

* @param accountId accountId to retrieve from.
* @param networkId network for this accountId.
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/

@@ -27,3 +27,3 @@ abstract async getPublicKey(accountId?: string, networkId?: string): Promise<PublicKey>;

* @param accountId accountId to use for signing.
* @param networkId network for this accontId.
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/

@@ -44,2 +44,8 @@ abstract async signMessage(message: Uint8Array, accountId?: string, networkId?: string): Promise<Signature>;

/**
* Creates a public key for the account given
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>}
*/
async createKey(accountId: string, networkId: string): Promise<PublicKey> {

@@ -51,2 +57,8 @@ const keyPair = KeyPair.fromRandom('ed25519');

/**
* Gets the existing public key for a given account
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<PublicKey>} Returns the public key or null if not found
*/
async getPublicKey(accountId?: string, networkId?: string): Promise<PublicKey> {

@@ -60,2 +72,8 @@ const keyPair = await this.keyStore.getKey(networkId, accountId);

/**
* @param message A message to be signed, typically a serialized transaction
* @param accountId the NEAR account signing the message
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
* @returns {Promise<Signature>}
*/
async signMessage(message: Uint8Array, accountId?: string, networkId?: string): Promise<Signature> {

@@ -62,0 +80,0 @@ const hash = new Uint8Array(sha256.sha256.array(message));

@@ -113,2 +113,5 @@ import sha256 from 'js-sha256';

/**
* Contains a list of the valid transaction Actions available with this API
*/
export class Action extends Enum {

@@ -203,2 +206,9 @@ createAccount: CreateAccount;

/**
* Signs a given transaction from an account with given keys, applied to the given network
* @param transaction The Transaction object to sign
* @param signer The {Signer} object that assists with signing keys
* @param accountId The human-readable NEAR account name
* @param networkId The targeted network. (ex. default, devnet, betanet, etc…)
*/
async function signTransactionObject(transaction: Transaction, signer: Signer, accountId?: string, networkId?: string): Promise<[Uint8Array, SignedTransaction]> {

@@ -205,0 +215,0 @@ const message = serialize(SCHEMA, transaction);

@@ -26,2 +26,3 @@ import BN from 'bn.js';

* @param fracDigits number of fractional digits to preserve in formatted string. Balance is rounded to match given number of digits.
* @returns Value in Ⓝ
*/

@@ -51,2 +52,3 @@ export function formatNearAmount(balance: string, fracDigits: number = NEAR_NOMINATION_EXP): string {

* @param amt decimal string (potentially fractional) denominated in NEAR.
* @returns The parsed yoctoⓃ amount or null if no amount was passed in
*/

@@ -65,2 +67,7 @@ export function parseNearAmount(amt?: string): string | null {

/**
* Removes commas from the input
* @param amount A value or amount that may contain commas
* @returns string The cleaned value
*/
function cleanupAmount(amount: string): string {

@@ -70,2 +77,7 @@ return amount.replace(/,/g, '').trim();

/**
* Removes .000… from an input
* @param value A value that may contain trailing zeroes in the decimals place
* @returns string The value without the trailing zeros
*/
function trimTrailingZeroes(value: string): string {

@@ -75,2 +87,7 @@ return value.replace(/\.?0*$/, '');

/**
* Removes leading zeroes from an input
* @param value A value that may contain leading zeroes
* @returns string The value without the leading zeroes
*/
function trimLeadingZeroes(value: string): string {

@@ -80,2 +97,7 @@ return value.replace(/^0+/, '');

/**
* Returns a human-readable value with commas
* @param value A value that may not contain commas
* @returns string A value with commas
*/
function formatWithCommas(value: string): string {

@@ -82,0 +104,0 @@ const pattern = /(-?\d+)(\d{3})/;

@@ -67,2 +67,6 @@ import nacl from 'tweetnacl';

/**
* @param curve Name of elliptical curve, case-insensitive
* @returns Random KeyPair based on the curve
*/
static fromRandom(curve: string): KeyPair {

@@ -69,0 +73,0 @@ switch (curve.toUpperCase()) {

@@ -26,2 +26,9 @@

/**
* Walks through defined schema returning error(s) recursively
* @param errorObj The error to be parsed
* @param schema A defined schema in JSON mapping to the RPC errors
* @param result An object used in recursion or called directly
* @param typeName The human-readable error type name as defined in the JSON mapping
*/
function walkSubtype(errorObj, schema, result, typeName) {

@@ -58,2 +65,6 @@ let error;

/**
* Helper function determining if the argument is an object
* @param n Value to check
*/
function isObject(n) {

@@ -63,4 +74,8 @@ return Object.prototype.toString.call(n) === '[object Object]';

/**
* Helper function determining if the argument is a string
* @param n Value to check
*/
function isString(n) {
return Object.prototype.toString.call(n) === '[object String]';
}

@@ -61,14 +61,15 @@ import { Account } from './account';

* Redirects current page to the wallet authentication page.
* @param {string} contractId contract ID of the application
* @param {string} title name of the application
* @param {string} successUrl url to redirect on success
* @param {string} failureUrl url to redirect on failure
* @param contractId The NEAR account where the contract is deployed
* @param title Name of the application that will appear as requesting access in Wallet
* @param successUrl Optional url to redirect upon success
* @param failureUrl Optional url to redirect upon failure
*
* @example
* walletAccount.requestSignIn(
* myContractId,
* title,
* onSuccessHref,
* onFailureHref);
* account-with-deploy-contract,
* "Guest Book",
* "https://example.com/success.html",
* "https://example.com/error.html");
*/
async requestSignIn(contractId: string, title: string, successUrl: string, failureUrl: string) {
async requestSignIn(contractId: string, title: string, successUrl?: string, failureUrl?: string) {
if (this.getAccountId() || await this._keyStore.getKey(this._networkId, this.getAccountId())) {

@@ -91,2 +92,7 @@ return Promise.resolve();

/**
* Requests the user to quickly sign for a transaction or batch of transactions
* @param transactions Array of Transaction objects that will be requested to sign
* @param callbackUrl The url to navigate to after the user is prompted to sign
*/
async requestSignTransactions(transactions: Transaction[], callbackUrl?: string) {

@@ -128,2 +134,7 @@ const currentUrl = new URL(window.location.href);

/**
*
* @param accountId The NEAR account owning the given public key
* @param publicKey The public key being set to the key store
*/
async _moveKeyFromTempToPermanent(accountId: string, publicKey: string) {

@@ -145,2 +156,5 @@ const keyPair = await this._keyStore.getKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + publicKey);

/**
* Returns the current connected wallet account
*/
account() {

@@ -209,2 +223,8 @@ if (!this._connectedAccount) {

/**
* Check if given access key allows the function call or method attempted in transaction
* @param accessKey Array of {access_key: AccessKey, public_key: PublicKey} items
* @param receiverId The NEAR account attempting to have access
* @param actions The action(s) needed to be checked for access
*/
async accessKeyMatchesTransaction(accessKey, receiverId: string, actions: Action[]): Promise<boolean> {

@@ -223,3 +243,6 @@ const { access_key: { permission } } = accessKey;

const [{ functionCall }] = actions;
return functionCall && (allowedMethods.length === 0 || allowedMethods.includes(functionCall.methodName));
return functionCall &&
functionCall.deposit.toString() === "0" && // TODO: Should support charging amount smaller than allowance?
(allowedMethods.length === 0 || allowedMethods.includes(functionCall.methodName));
// TODO: Handle cases when allowance doesn't have enough to pay for gas
}

@@ -232,2 +255,9 @@ }

/**
* Helper function returning the access key (if it exists) to the receiver that grants the designated permission
* @param receiverId The NEAR account seeking the access key for a transaction
* @param actions The action(s) sought to gain access to
* @param localKey A local public key provided to check for access
* @returns Promise<any>
*/
async accessKeyForTransaction(receiverId: string, actions: Action[], localKey?: PublicKey): Promise<any> {

@@ -234,0 +264,0 @@ const accessKeys = await this.getAccessKeys();

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

@@ -25,4 +25,4 @@

test('make function call using access key', async() => {
const keyPair = nearlib.utils.KeyPair.fromRandom('ed25519');
await workingAccount.addKey(keyPair.getPublicKey(), contractId, '', 10000000);
const keyPair = nearApi.utils.KeyPair.fromRandom('ed25519');
await workingAccount.addKey(keyPair.getPublicKey(), contractId, '', '100000000000000000000');

@@ -37,3 +37,3 @@ // Override in the key store the workingAccount key to the given access key.

test('remove access key no longer works', async() => {
const keyPair = nearlib.utils.KeyPair.fromRandom('ed25519');
const keyPair = nearApi.utils.KeyPair.fromRandom('ed25519');
let publicKey = keyPair.getPublicKey();

@@ -54,7 +54,7 @@ await workingAccount.addKey(publicKey, contractId, '', 400000);

test('view account details after adding access keys', async() => {
const keyPair = nearlib.utils.KeyPair.fromRandom('ed25519');
const keyPair = nearApi.utils.KeyPair.fromRandom('ed25519');
await workingAccount.addKey(keyPair.getPublicKey(), contractId, '', 1000000000);
const contract2 = await testUtils.deployContract(workingAccount, 'test_contract2_' + Date.now());
const keyPair2 = nearlib.utils.KeyPair.fromRandom('ed25519');
const keyPair2 = nearApi.utils.KeyPair.fromRandom('ed25519');
await workingAccount.addKey(keyPair2.getPublicKey(), contract2.contractId, '', 2000000000);

@@ -80,3 +80,3 @@

test('loading account after adding a full key', async() => {
const keyPair = nearlib.utils.KeyPair.fromRandom('ed25519');
const keyPair = nearApi.utils.KeyPair.fromRandom('ed25519');
// wallet calls this with an empty string for contract id and method

@@ -83,0 +83,0 @@ await workingAccount.addKey(keyPair.getPublicKey(), '', '');

const nearlib = require('../lib/index');
const nearApi = require('../lib/index');
const testUtils = require('./test-utils');

@@ -32,3 +32,3 @@ const fs = require('fs');

await workingAccount.createAccount(newAccountName, newAccountPublicKey, testUtils.INITIAL_BALANCE);
const newAccount = new nearlib.Account(nearjs.connection, newAccountName);
const newAccount = new nearApi.Account(nearjs.connection, newAccountName);
const state = await newAccount.state();

@@ -51,3 +51,3 @@ expect(state.amount).toEqual(testUtils.INITIAL_BALANCE.toString());

await sender.deleteAccount(receiver.accountId);
const reloaded = new nearlib.Account(sender.connection, sender);
const reloaded = new nearApi.Account(sender.connection, sender);
await expect(reloaded.state()).rejects.toThrow();

@@ -94,3 +94,3 @@ });

await workingAccount.createAndDeployContract(contractId, newPublicKey, data, testUtils.INITIAL_BALANCE);
contract = new nearlib.Contract(workingAccount, contractId, {
contract = new nearApi.Contract(workingAccount, contractId, {
viewMethods: ['hello', 'getValue', 'getAllKeys', 'returnHiWithLogs'],

@@ -122,3 +122,3 @@ changeMethods: ['setValue', 'generateLogs', 'triggerAssert', 'testSetRemove']

const result2 = await workingAccount.functionCall(contractId, 'setValue', { value: setCallValue });
expect(nearlib.providers.getTransactionLastResult(result2)).toEqual(setCallValue);
expect(nearApi.providers.getTransactionLastResult(result2)).toEqual(setCallValue);
expect(await workingAccount.viewFunction(contractId, 'getValue', {})).toEqual(setCallValue);

@@ -200,3 +200,3 @@ });

test('can have view methods only', async () => {
const contract = new nearlib.Contract(workingAccount, contractId, {
const contract = new nearApi.Contract(workingAccount, contractId, {
viewMethods: ['hello'],

@@ -208,3 +208,3 @@ });

test('can have change methods only', async () => {
const contract = new nearlib.Contract(workingAccount, contractId, {
const contract = new nearApi.Contract(workingAccount, contractId, {
changeMethods: ['hello'],

@@ -211,0 +211,0 @@ });

@@ -10,2 +10,16 @@ module.exports = function getConfig(env) {

};
case 'devnet':
return {
networkId: 'devnet',
nodeUrl: 'https://rpc.devnet.nearprotocol.com',
walletUrl: 'https://wallet.devnet.nearprotocol.com',
helperUrl: 'https://helper.devnet.nearprotocol.com',
};
case 'betanet':
return {
networkId: 'betanet',
nodeUrl: 'https://rpc.betanet.nearprotocol.com',
walletUrl: 'https://wallet.betanet.nearprotocol.com',
helperUrl: 'https://helper.betanet.nearprotocol.com',
};
case 'local':

@@ -18,8 +32,2 @@ return {

case 'test':
return {
networkId: 'local',
nodeUrl: 'http://localhost:3030',
masterAccount: 'test.near',
};
case 'test-remote':
case 'ci':

@@ -31,6 +39,6 @@ return {

};
case 'ci-staging':
case 'ci-betanet':
return {
networkId: 'shared-test-staging',
nodeUrl: 'http://staging-shared-test.nearprotocol.com:3030',
nodeUrl: 'http://rpc.ci-betanet.nearprotocol.com',
masterAccount: 'test.near',

@@ -37,0 +45,0 @@ };

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

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
exports.fuzz = input => {
try {
const deserialized = nearlib.utils.serialize.deserialize(nearlib.transactions.SCHEMA, nearlib.transactions.Transaction, input);
const serialized = nearlib.utils.serialize.serialize(nearlib.transactions.SCHEMA, deserialized);
const deserialized = nearApi.utils.serialize.deserialize(nearApi.transactions.SCHEMA, nearApi.transactions.Transaction, input);
const serialized = nearApi.utils.serialize.serialize(nearApi.transactions.SCHEMA, deserialized);
if (!serialized.equals(input)) {

@@ -12,3 +12,3 @@ console.log(`Mismatching output:\n${serialized.toString('hex')}\nand input:\n${input.toString('hex')}`);

} catch(e) {
if (e instanceof nearlib.utils.serialize.BorshError) {
if (e instanceof nearApi.utils.serialize.BorshError) {
// Do nothing

@@ -15,0 +15,0 @@ } else {

const nearlib = require('../lib/index');
const nearApi = require('../lib/index');
const { sha256 } = require('js-sha256');
test('test sign and verify', async () => {
const keyPair = new nearlib.utils.key_pair.KeyPairEd25519('26x56YPzPDro5t2smQfGcYAPy3j7R2jB2NUb7xKbAGK23B6x4WNQPh3twb6oDksFov5X8ts5CtntUNbpQpAKFdbR');
const keyPair = new nearApi.utils.key_pair.KeyPairEd25519('26x56YPzPDro5t2smQfGcYAPy3j7R2jB2NUb7xKbAGK23B6x4WNQPh3twb6oDksFov5X8ts5CtntUNbpQpAKFdbR');
expect(keyPair.publicKey.toString()).toEqual('ed25519:AYWv9RAN1hpSQA4p1DLhCNnpnNXwxhfH9qeHN8B4nJ59');
const message = new Uint8Array(sha256.array('message'));
const signature = keyPair.sign(message);
expect(nearlib.utils.serialize.base_encode(signature.signature)).toEqual('26gFr4xth7W9K7HPWAxq3BLsua8oTy378mC1MYFiEXHBBpeBjP8WmJEJo8XTBowetvqbRshcQEtBUdwQcAqDyP8T');
expect(nearApi.utils.serialize.base_encode(signature.signature)).toEqual('26gFr4xth7W9K7HPWAxq3BLsua8oTy378mC1MYFiEXHBBpeBjP8WmJEJo8XTBowetvqbRshcQEtBUdwQcAqDyP8T');
});
test('test sign and verify with random', async () => {
const keyPair = nearlib.utils.key_pair.KeyPairEd25519.fromRandom();
const keyPair = nearApi.utils.key_pair.KeyPairEd25519.fromRandom();
const message = new Uint8Array(sha256.array('message'));

@@ -21,3 +21,3 @@ const signature = keyPair.sign(message);

test('test from secret', async () => {
const keyPair = new nearlib.utils.key_pair.KeyPairEd25519('5JueXZhEEVqGVT5powZ5twyPP8wrap2K7RdAYGGdjBwiBdd7Hh6aQxMP1u3Ma9Yanq1nEv32EW7u8kUJsZ6f315C');
const keyPair = new nearApi.utils.key_pair.KeyPairEd25519('5JueXZhEEVqGVT5powZ5twyPP8wrap2K7RdAYGGdjBwiBdd7Hh6aQxMP1u3Ma9Yanq1nEv32EW7u8kUJsZ6f315C');
expect(keyPair.publicKey.toString()).toEqual('ed25519:EWrekY1deMND7N3Q7Dixxj12wD7AVjFRt2H9q21QHUSW');

@@ -27,9 +27,9 @@ });

test('convert to string', async () => {
const keyPair = nearlib.utils.key_pair.KeyPairEd25519.fromRandom();
const newKeyPair = nearlib.utils.key_pair.KeyPair.fromString(keyPair.toString());
const keyPair = nearApi.utils.key_pair.KeyPairEd25519.fromRandom();
const newKeyPair = nearApi.utils.key_pair.KeyPair.fromString(keyPair.toString());
expect(newKeyPair.secretKey).toEqual(keyPair.secretKey);
const keyString = 'ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw';
const keyPair2 = nearlib.utils.key_pair.KeyPair.fromString(keyString);
const keyPair2 = nearApi.utils.key_pair.KeyPair.fromString(keyString);
expect(keyPair2.toString()).toEqual(keyString);
});

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

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
const BrowserLocalStorageKeyStore = nearlib.keyStores.BrowserLocalStorageKeyStore;
const BrowserLocalStorageKeyStore = nearApi.keyStores.BrowserLocalStorageKeyStore;

@@ -5,0 +5,0 @@ describe('Browser keystore', () => {

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

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
const InMemoryKeyStore = nearlib.keyStores.InMemoryKeyStore;
const InMemoryKeyStore = nearApi.keyStores.InMemoryKeyStore;

@@ -5,0 +5,0 @@ describe('In-memory keystore', () => {

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
const KeyPair = nearlib.utils.KeyPairEd25519;
const KeyPair = nearApi.utils.KeyPairEd25519;

@@ -6,0 +6,0 @@ const NETWORK_ID_SINGLE_KEY = 'singlekeynetworkid';

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

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
const KeyPair = nearlib.utils.KeyPairEd25519;
const KeyPair = nearApi.utils.KeyPairEd25519;
const MergeKeyStore = nearlib.keyStores.MergeKeyStore;
const InMemoryKeyStore = nearlib.keyStores.InMemoryKeyStore;
const MergeKeyStore = nearApi.keyStores.MergeKeyStore;
const InMemoryKeyStore = nearApi.keyStores.InMemoryKeyStore;

@@ -8,0 +8,0 @@ describe('Merge keystore', () => {

const rimraf = require('util').promisify(require('rimraf'));
const nearlib = require('../../lib/index');
const UnencryptedFileSystemKeyStore = nearlib.keyStores.UnencryptedFileSystemKeyStore;
const nearApi = require('../../lib/index');
const UnencryptedFileSystemKeyStore = nearApi.keyStores.UnencryptedFileSystemKeyStore;
const { ensureDir } = require('../test-utils');

@@ -7,0 +7,0 @@

const nearlib = require('../lib/index');
const nearApi = require('../lib/index');
const withProvider = (fn) => {
const config = Object.assign(require('./config')(process.env.NODE_ENV || 'test'));
const provider = new nearlib.providers.JsonRpcProvider(config.nodeUrl);
const provider = new nearApi.providers.JsonRpcProvider(config.nodeUrl);
return () => fn(provider);

@@ -12,3 +12,3 @@ };

let response = await provider.status();
expect(response.chain_id).toContain('test-chain');
expect(response.chain_id).toBeTruthy();
}));

@@ -49,3 +49,3 @@

};
expect(nearlib.providers.getTransactionLastResult(result)).toEqual({});
expect(nearApi.providers.getTransactionLastResult(result)).toEqual({});
});

@@ -62,3 +62,3 @@

};
expect(nearlib.providers.getTransactionLastResult(result)).toEqual(null);
expect(nearApi.providers.getTransactionLastResult(result)).toEqual(null);
});
const fs = require('fs');
const nearlib = require('../lib/index');
const nearApi = require('../lib/index');
class Test extends nearlib.utils.enums.Assignable {
class Test extends nearApi.utils.enums.Assignable {
}

@@ -11,4 +11,4 @@

const schema = new Map([[Test, {kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]);
let buf = nearlib.utils.serialize.serialize(schema, value);
let new_value = nearlib.utils.serialize.deserialize(schema, Test, buf);
let buf = nearApi.utils.serialize.serialize(schema, value);
let new_value = nearApi.utils.serialize.deserialize(schema, Test, buf);
expect(new_value.x).toEqual(255);

@@ -21,20 +21,20 @@ expect(new_value.y.toString()).toEqual('20');

test('serialize and sign multi-action tx', async() => {
const keyStore = new nearlib.keyStores.InMemoryKeyStore();
const keyPair = nearlib.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw');
const keyStore = new nearApi.keyStores.InMemoryKeyStore();
const keyPair = nearApi.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw');
await keyStore.setKey('test', 'test.near', keyPair);
const publicKey = keyPair.publicKey;
const actions = [
nearlib.transactions.createAccount(),
nearlib.transactions.deployContract(new Uint8Array([1, 2, 3])),
nearlib.transactions.functionCall('qqq', new Uint8Array([1, 2, 3]), 1000, 1000000),
nearlib.transactions.transfer(123),
nearlib.transactions.stake(1000000, publicKey),
nearlib.transactions.addKey(publicKey, nearlib.transactions.functionCallAccessKey('zzz', ['www'], null)),
nearlib.transactions.deleteKey(publicKey),
nearlib.transactions.deleteAccount('123')
nearApi.transactions.createAccount(),
nearApi.transactions.deployContract(new Uint8Array([1, 2, 3])),
nearApi.transactions.functionCall('qqq', new Uint8Array([1, 2, 3]), 1000, 1000000),
nearApi.transactions.transfer(123),
nearApi.transactions.stake(1000000, publicKey),
nearApi.transactions.addKey(publicKey, nearApi.transactions.functionCallAccessKey('zzz', ['www'], null)),
nearApi.transactions.deleteKey(publicKey),
nearApi.transactions.deleteAccount('123')
];
const blockHash = nearlib.utils.serialize.base_decode('244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM');
let [hash, { transaction }] = await nearlib.transactions.signTransaction('123', 1, actions, blockHash, new nearlib.InMemorySigner(keyStore), 'test.near', 'test');
expect(nearlib.utils.serialize.base_encode(hash)).toEqual('Fo3MJ9XzKjnKuDuQKhDAC6fra5H2UWawRejFSEpPNk3Y');
const serialized = nearlib.utils.serialize.serialize(nearlib.transactions.SCHEMA, transaction);
const blockHash = nearApi.utils.serialize.base_decode('244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM');
let [hash, { transaction }] = await nearApi.transactions.signTransaction('123', 1, actions, blockHash, new nearApi.InMemorySigner(keyStore), 'test.near', 'test');
expect(nearApi.utils.serialize.base_encode(hash)).toEqual('Fo3MJ9XzKjnKuDuQKhDAC6fra5H2UWawRejFSEpPNk3Y');
const serialized = nearApi.utils.serialize.serialize(nearApi.transactions.SCHEMA, transaction);
expect(serialized.toString('hex')).toEqual('09000000746573742e6e656172000f56a5f028dfc089ec7c39c1183b321b4d8f89ba5bec9e1762803cc2491f6ef80100000000000000030000003132330fa473fd26901df296be6adc4cc4df34d040efa2435224b6986910e630c2fef608000000000103000000010203020300000071717103000000010203e80300000000000040420f00000000000000000000000000037b0000000000000000000000000000000440420f00000000000000000000000000000f56a5f028dfc089ec7c39c1183b321b4d8f89ba5bec9e1762803cc2491f6ef805000f56a5f028dfc089ec7c39c1183b321b4d8f89ba5bec9e1762803cc2491f6ef800000000000000000000030000007a7a7a010000000300000077777706000f56a5f028dfc089ec7c39c1183b321b4d8f89ba5bec9e1762803cc2491f6ef80703000000313233');

@@ -45,8 +45,8 @@ });

const actions = [
nearlib.transactions.transfer(1),
nearApi.transactions.transfer(1),
];
const blockHash = nearlib.utils.serialize.base_decode('244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM');
return nearlib.transactions.createTransaction(
const blockHash = nearApi.utils.serialize.base_decode('244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM');
return nearApi.transactions.createTransaction(
'test.near',
nearlib.utils.PublicKey.fromString('Anu7LYDfpLtkP7E16LT9imXF694BdQaa9ufVkQiwTQxC'),
nearApi.utils.PublicKey.fromString('Anu7LYDfpLtkP7E16LT9imXF694BdQaa9ufVkQiwTQxC'),
'whatever.near',

@@ -64,3 +64,3 @@ 1,

const deserialized = nearlib.transactions.Transaction.decode(serialized);
const deserialized = nearApi.transactions.Transaction.decode(serialized);
expect(deserialized.encode()).toEqual(serialized);

@@ -70,4 +70,4 @@ });

async function createKeyStore() {
const keyStore = new nearlib.keyStores.InMemoryKeyStore();
const keyPair = nearlib.utils.KeyPair.fromString('ed25519:3hoMW1HvnRLSFCLZnvPzWeoGwtdHzke34B2cTHM8rhcbG3TbuLKtShTv3DvyejnXKXKBiV7YPkLeqUHN1ghnqpFv');
const keyStore = new nearApi.keyStores.InMemoryKeyStore();
const keyPair = nearApi.utils.KeyPair.fromString('ed25519:3hoMW1HvnRLSFCLZnvPzWeoGwtdHzke34B2cTHM8rhcbG3TbuLKtShTv3DvyejnXKXKBiV7YPkLeqUHN1ghnqpFv');
await keyStore.setKey('test', 'test.near', keyPair);

@@ -82,3 +82,3 @@ return keyStore;

const deserialized = nearlib.transactions.SignedTransaction.decode(serialized);
const deserialized = nearApi.transactions.SignedTransaction.decode(serialized);
expect(deserialized.encode()).toEqual(serialized);

@@ -91,3 +91,3 @@ }

let [, signedTx] = await nearlib.transactions.signTransaction(transaction.receiverId, transaction.nonce, transaction.actions, transaction.blockHash, new nearlib.InMemorySigner(keyStore), 'test.near', 'test');
let [, signedTx] = await nearApi.transactions.signTransaction(transaction.receiverId, transaction.nonce, transaction.actions, transaction.blockHash, new nearApi.InMemorySigner(keyStore), 'test.near', 'test');

@@ -101,3 +101,3 @@ verifySignedTransferTx(signedTx);

let [, signedTx] = await nearlib.transactions.signTransaction(transaction, new nearlib.InMemorySigner(keyStore), 'test.near', 'test');
let [, signedTx] = await nearApi.transactions.signTransaction(transaction, new nearApi.InMemorySigner(keyStore), 'test.near', 'test');

@@ -115,5 +115,5 @@ verifySignedTransferTx(signedTx);

const data = Buffer.from(testDefinition.data, 'hex');
const type = Array.from(nearlib.transactions.SCHEMA.keys()).find(key => key.name === testDefinition.type);
const deserialized = nearlib.utils.serialize.deserialize(nearlib.transactions.SCHEMA, type, data);
const serialized = nearlib.utils.serialize.serialize(nearlib.transactions.SCHEMA, deserialized);
const type = Array.from(nearApi.transactions.SCHEMA.keys()).find(key => key.name === testDefinition.type);
const deserialized = nearApi.utils.serialize.deserialize(nearApi.transactions.SCHEMA, type, data);
const serialized = nearApi.utils.serialize.serialize(nearApi.transactions.SCHEMA, deserialized);
expect(serialized).toEqual(data);

@@ -120,0 +120,0 @@ });

const nearlib = require('../lib/index');
const nearApi = require('../lib/index');
test('test no key', async() => {
const signer = new nearlib.InMemorySigner(new nearlib.keyStores.InMemoryKeyStore());
const signer = new nearApi.InMemorySigner(new nearApi.keyStores.InMemoryKeyStore());
await expect(signer.signMessage('message', 'user', 'network')).rejects.toThrow(/Key for user not found in network/);
});
const fs = require('fs').promises;
const BN = require('bn.js');
const nearlib = require('../lib/index');
const nearApi = require('../lib/index');

@@ -13,4 +13,4 @@ const networkId = 'unittest';

async function setUpTestConnection() {
const keyStore = new nearlib.keyStores.InMemoryKeyStore();
await keyStore.setKey(networkId, testAccountName, nearlib.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw'));
const keyStore = new nearApi.keyStores.InMemoryKeyStore();
await keyStore.setKey(networkId, testAccountName, nearApi.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw'));
const config = Object.assign(require('./config')(process.env.NODE_ENV || 'test'), {

@@ -21,3 +21,3 @@ networkId: networkId,

return nearlib.connect(config);
return nearApi.connect(config);
}

@@ -35,3 +35,3 @@

await masterAccount.createAccount(newAccountName, newPublicKey, options.amount);
return new nearlib.Account(masterAccount.connection, newAccountName);
return new nearApi.Account(masterAccount.connection, newAccountName);
}

@@ -43,3 +43,3 @@

await workingAccount.createAndDeployContract(contractId, newPublicKey, data, options.amount);
return new nearlib.Contract(workingAccount, contractId, {
return new nearApi.Contract(workingAccount, contractId, {
viewMethods: ['getValue', 'getLastResult'],

@@ -46,0 +46,0 @@ changeMethods: ['setValue', 'callPromise']

// Unit tests for simple util code
const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');

@@ -31,3 +31,3 @@ jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;

`('formatNearAmount($balance, $fracDigits) returns $expected', ({ balance, fracDigits, expected }) => {
expect(nearlib.utils.format.formatNearAmount(balance, fracDigits)).toEqual(expected);
expect(nearApi.utils.format.formatNearAmount(balance, fracDigits)).toEqual(expected);
});

@@ -51,3 +51,3 @@

`('parseNearAmount($amt) returns $expected', ({ amt, expected }) => {
expect(nearlib.utils.format.parseNearAmount(amt)).toEqual(expected);
expect(nearApi.utils.format.parseNearAmount(amt)).toEqual(expected);
});

@@ -57,3 +57,3 @@

expect(() => {
nearlib.utils.format.parseNearAmount('0.0000080990999998370878871');
nearApi.utils.format.parseNearAmount('0.0000080990999998370878871');
}).toThrowError(

@@ -60,0 +60,0 @@ 'Cannot parse \'0.0000080990999998370878871\' as NEAR amount'

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

const nearlib = require('../../lib/index');
const nearApi = require('../../lib/index');
const {

@@ -15,3 +15,3 @@ parseRpcError,

formatError
} = nearlib.utils.rpc_errors;
} = nearApi.utils.rpc_errors;
describe('rpc-errors', () => {

@@ -18,0 +18,0 @@ test('test AccountAlreadyExists error', async () => {

const url = require('url');
const localStorage = require('localstorage-memory');
const BN = require('bn.js');
let newUrl;
let lastRedirectUrl;
let lastTransaction;
global.window = {

@@ -11,3 +13,3 @@ localStorage

};
const nearlib = require('../lib/index');
const nearApi = require('../lib/index');

@@ -17,3 +19,3 @@ let history;

let walletConnection;
let keyStore = new nearlib.keyStores.InMemoryKeyStore();
let keyStore = new nearApi.keyStores.InMemoryKeyStore();
beforeEach(() => {

@@ -27,6 +29,7 @@ nearFake = {

connection: {
signer: new nearlib.InMemorySigner(keyStore)
networkId: 'networkId',
signer: new nearApi.InMemorySigner(keyStore)
}
};
newUrl = null;
lastRedirectUrl = null;
history = [];

@@ -37,3 +40,3 @@ Object.assign(global.window, {

assign(url) {
newUrl = url;
lastRedirectUrl = url;
}

@@ -45,3 +48,3 @@ },

});
walletConnection = new nearlib.WalletConnection(nearFake);
walletConnection = new nearApi.WalletConnection(nearFake);
});

@@ -59,3 +62,3 @@

expect(accounts[0]).toMatch(/^pending_key.+/);
expect(url.parse(newUrl, true)).toMatchObject({
expect(url.parse(lastRedirectUrl, true)).toMatchObject({
protocol: 'http:',

@@ -74,3 +77,3 @@ host: 'example.com',

it('can complete sign in', async () => {
const keyPair = nearlib.KeyPair.fromRandom('ed25519');
const keyPair = nearApi.KeyPair.fromRandom('ed25519');
global.window.location.href = `http://example.com/location?account_id=near.account&public_key=${keyPair.publicKey}`;

@@ -89,10 +92,10 @@ await keyStore.setKey('networkId', 'pending_key' + keyPair.publicKey, keyPair);

const BLOCK_HASH = '244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM';
const blockHash = nearlib.utils.serialize.base_decode(BLOCK_HASH);
const blockHash = nearApi.utils.serialize.base_decode(BLOCK_HASH);
function createTransferTx() {
const actions = [
nearlib.transactions.transfer(1),
nearApi.transactions.transfer(1),
];
return nearlib.transactions.createTransaction(
return nearApi.transactions.createTransaction(
'test.near',
nearlib.utils.PublicKey.fromString('Anu7LYDfpLtkP7E16LT9imXF694BdQaa9ufVkQiwTQxC'),
nearApi.utils.PublicKey.fromString('Anu7LYDfpLtkP7E16LT9imXF694BdQaa9ufVkQiwTQxC'),
'whatever.near',

@@ -107,3 +110,3 @@ 1,

expect(url.parse(newUrl, true)).toMatchObject({
expect(url.parse(lastRedirectUrl, true)).toMatchObject({
protocol: 'http:',

@@ -118,7 +121,22 @@ host: 'example.com',

it('requests transaction signing automatically when there is no local key', async () => {
// TODO: Refactor copy-pasted common setup code
let keyPair = nearlib.KeyPair.fromRandom('ed25519');
function parseTransactionsFromUrl(urlToParse) {
const parsedUrl = url.parse(urlToParse, true);
expect(parsedUrl).toMatchObject({
protocol: 'http:',
host: 'example.com',
query: {
callbackUrl: 'http://example.com/location'
}
});
const transactions = parsedUrl.query.transactions.split(',')
.map(txBase64 => nearApi.utils.serialize.deserialize(
nearApi.transactions.SCHEMA,
nearApi.transactions.Transaction,
Buffer.from(txBase64, 'base64')));
return transactions;
}
function setupWalletConnectionForSigning({ allKeys, accountAccessKeys }) {
walletConnection._authData = {
allKeys: [ 'no_such_access_key', keyPair.publicKey.toString() ],
allKeys: allKeys,
accountId: 'signer.near'

@@ -132,12 +150,21 @@ };

if (path === 'access_key/signer.near') {
return { keys: [{
access_key: {
nonce: 1,
permission: 'FullAccess'
},
public_key: keyPair.publicKey.toString()
}] };
return { keys: accountAccessKeys };
}
if (path.startsWith('access_key/signer.near')) {
const [,,publicKey] = path.split('/');
for (let accessKey of accountAccessKeys) {
if (accessKey.public_key === publicKey) {
return accessKey;
}
}
}
fail(`Unexpected query: ${path} ${data}`);
},
sendTransaction(signedTransaction) {
lastTransaction = signedTransaction;
return {
transaction_outcome: { outcome: { logs: [] } },
receipts_outcome: []
};
},
status() {

@@ -151,5 +178,19 @@ return {

};
}
it('requests transaction signing automatically when there is no local key', async () => {
let keyPair = nearApi.KeyPair.fromRandom('ed25519');
setupWalletConnectionForSigning({
allKeys: [ 'no_such_access_key', keyPair.publicKey.toString() ],
accountAccessKeys: [{
access_key: {
nonce: 1,
permission: 'FullAccess'
},
public_key: keyPair.publicKey.toString()
}]
});
try {
await walletConnection.account().signAndSendTransaction('receiver.near', [nearlib.transactions.transfer(1)]);
await walletConnection.account().signAndSendTransaction('receiver.near', [nearApi.transactions.transfer(1)]);
fail('expected to throw');

@@ -160,16 +201,3 @@ } catch (e) {

const parsedUrl = url.parse(newUrl, true);
expect(parsedUrl).toMatchObject({
protocol: 'http:',
host: 'example.com',
query: {
callbackUrl: 'http://example.com/location'
}
});
const transactions = parsedUrl.query.transactions.split(',')
.map(txBase64 => nearlib.utils.serialize.deserialize(
nearlib.transactions.SCHEMA,
nearlib.transactions.Transaction,
Buffer.from(txBase64, 'base64')));
const transactions = parseTransactionsFromUrl(lastRedirectUrl);
expect(transactions).toHaveLength(1);

@@ -190,1 +218,79 @@ expect(transactions[0]).toMatchObject({

});
it('requests transaction signing automatically when function call has attached deposit', async () => {
let localKeyPair = nearApi.KeyPair.fromRandom('ed25519');
let walletKeyPair = nearApi.KeyPair.fromRandom('ed25519');
setupWalletConnectionForSigning({
allKeys: [ walletKeyPair.publicKey.toString() ],
accountAccessKeys: [{
access_key: {
nonce: 1,
permission: {
FunctionCall: {
allowance: '1000000000',
receiver_id: 'receiver.near',
method_names: []
}
}
},
public_key: localKeyPair.publicKey.toString()
}, {
access_key: {
nonce: 1,
permission: 'FullAccess'
},
public_key: walletKeyPair.publicKey.toString()
}]
});
keyStore.setKey('networkId', 'signer.near', localKeyPair);
try {
await walletConnection.account().signAndSendTransaction('receiver.near', [
nearApi.transactions.functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('1'))
]);
fail('expected to throw');
} catch (e) {
expect(e.message).toEqual('Failed to redirect to sign transaction');
}
const transactions = parseTransactionsFromUrl(lastRedirectUrl);
expect(transactions).toHaveLength(1);
});
it('can sign transaction locally when function call has no attached deposit', async () => {
let localKeyPair = nearApi.KeyPair.fromRandom('ed25519');
setupWalletConnectionForSigning({
allKeys: [ /* no keys in wallet needed */ ],
accountAccessKeys: [{
access_key: {
nonce: 1,
permission: {
FunctionCall: {
allowance: '1000000000',
receiver_id: 'receiver.near',
method_names: []
}
}
},
public_key: localKeyPair.publicKey.toString()
}]
});
keyStore.setKey('networkId', 'signer.near', localKeyPair);
await walletConnection.account().signAndSendTransaction('receiver.near', [
nearApi.transactions.functionCall('someMethod', new Uint8Array(), new BN('1'), new BN('0'))
]);
// NOTE: Transaction gets signed without wallet in this test
expect(lastTransaction).toMatchObject({
transaction: {
receiverId: 'receiver.near',
signerId: 'signer.near',
actions: [{
functionCall: {
methodName: 'someMethod',
}
}]
}
});
});

@@ -28,3 +28,16 @@ {

"src/index.ts",
]
"src/browser-index.ts",
],
"typedocOptions": {
"out": "docs/near-api-js",
"theme": "docusaurus",
"skipSidebar": true,
"hideBreadcrumbs": true,
"hideSources": true,
"ignoreCompilerErrors": true,
"excludePrivate": true,
"excludeProtected": true,
"excludeExternals": true,
"stripInternal": true
}
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc