New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

nearlib

Package Overview
Dependencies
Maintainers
4
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nearlib - npm Package Compare versions

Comparing version 0.3.5 to 0.4.0

test/promise.test.js

17

account.js

@@ -8,2 +8,4 @@ const bs58 = require('bs58');

* Near account and account related operations.
* @example
* const account = new Account(nearjs.nearClient);
*/

@@ -21,2 +23,8 @@ class Account {

* @param {string} originatorAccountId existing account on the blockchain to use for transferring tokens into the new account
* @example
* const createAccountResponse = await account.createAccount(
* mainTestAccountName,
* keyWithRandomSeed.getPublicKey(),
* 1000,
* aliceAccountName);
*/

@@ -57,2 +65,7 @@ async createAccount (newAccountId, publicKey, amount, originator) {

* @param {string} originatorAccountId existing account on the blockchain to use for transferring tokens into the new account
* @example
* const createAccountResponse = await account.createAccountWithRandomKey(
* newAccountName,
* amount,
* aliceAccountName);
*/

@@ -71,4 +84,6 @@ async createAccountWithRandomKey (newAccountId, amount, originatorAccountId) {

/**
*
* Returns an existing account with a given `accountId`
* @param {string} accountId id of the account to look up
* @example
* const viewAccountResponse = await account.viewAccount(existingAccountId);
*/

@@ -75,0 +90,0 @@ async viewAccount (accountId) {

@@ -7,2 +7,3 @@ # API

- [require](#require)
- [KeyPair](#keypair)

@@ -12,13 +13,20 @@ - [Parameters](#parameters)

- [getSecretKey](#getsecretkey)
- [Examples](#examples)
- [fromRandomSeed](#fromrandomseed)
- [Examples](#examples-1)
- [encodeBufferInBs58](#encodebufferinbs58)
- [Parameters](#parameters-1)
- [Examples](#examples-2)
- [Account](#account)
- [Parameters](#parameters-2)
- [Examples](#examples-3)
- [createAccount](#createaccount)
- [Parameters](#parameters-3)
- [Examples](#examples-4)
- [createAccountWithRandomKey](#createaccountwithrandomkey)
- [Parameters](#parameters-4)
- [Examples](#examples-5)
- [viewAccount](#viewaccount)
- [Parameters](#parameters-5)
- [Examples](#examples-6)
- [Near](#near)

@@ -28,15 +36,40 @@ - [Parameters](#parameters-6)

- [Parameters](#parameters-7)
- [Examples](#examples-7)
- [scheduleFunctionCall](#schedulefunctioncall)
- [Parameters](#parameters-8)
- [Examples](#examples-8)
- [deployContract](#deploycontract)
- [Parameters](#parameters-9)
- [Examples](#examples-9)
- [getTransactionStatus](#gettransactionstatus)
- [Parameters](#parameters-10)
- [Examples](#examples-10)
- [waitForTransactionResult](#waitfortransactionresult)
- [Parameters](#parameters-11)
- [Examples](#examples-11)
- [loadContract](#loadcontract)
- [Parameters](#parameters-12)
- [Examples](#examples-12)
- [createDefaultConfig](#createdefaultconfig)
- [Parameters](#parameters-13)
- [Examples](#examples-13)
- [WalletAccount](#walletaccount)
- [Parameters](#parameters-14)
- [Examples](#examples-14)
- [isSignedIn](#issignedin)
- [Examples](#examples-15)
- [getAccountId](#getaccountid)
- [Examples](#examples-16)
- [requestSignIn](#requestsignin)
- [Parameters](#parameters-15)
- [Examples](#examples-17)
- [signOut](#signout)
- [Examples](#examples-18)
- [signTransactionBody](#signtransactionbody)
- [Parameters](#parameters-16)
## require
Wallet based account and signer that uses external wallet through the iframe to signs transactions.
## KeyPair

@@ -59,2 +92,14 @@

#### Examples
```javascript
// Passing existing key into a function to store in local storage
async setKey(accountId, key) {
window.localStorage.setItem(
BrowserLocalStorageKeystore.storageKeyForPublicKey(accountId), key.getPublicKey());
window.localStorage.setItem(
BrowserLocalStorageKeystore.storageKeyForSecretKey(accountId), key.getSecretKey());
}
```
### fromRandomSeed

@@ -64,2 +109,13 @@

#### Examples
```javascript
const keyWithRandomSeed = await KeyPair.fromRandomSeed();
keyWithRandomSeed.getPublicKey()
// returns [PUBLIC_KEY]
keyWithRandomSeed.getSecretKey()
// returns [SECRET_KEY]
```
### encodeBufferInBs58

@@ -73,2 +129,8 @@

#### Examples
```javascript
KeyPair.encodeBufferInBs58(key.publicKey)
```
## Account

@@ -82,2 +144,8 @@

### Examples
```javascript
const account = new Account(nearjs.nearClient);
```
### createAccount

@@ -95,2 +163,12 @@

#### Examples
```javascript
const createAccountResponse = await account.createAccount(
mainTestAccountName,
keyWithRandomSeed.getPublicKey(),
1000,
aliceAccountName);
```
### createAccountWithRandomKey

@@ -107,4 +185,15 @@

#### Examples
```javascript
const createAccountResponse = await account.createAccountWithRandomKey(
newAccountName,
amount,
aliceAccountName);
```
### viewAccount
Returns an existing account with a given `accountId`
#### Parameters

@@ -114,2 +203,8 @@

#### Examples
```javascript
const viewAccountResponse = await account.viewAccount(existingAccountId);
```
## Near

@@ -133,2 +228,11 @@

#### Examples
```javascript
const viewFunctionResponse = await near.callViewFunction(
contractAccountId,
methodName,
args);
```
### scheduleFunctionCall

@@ -149,2 +253,13 @@

#### Examples
```javascript
const scheduleResult = await near.scheduleFunctionCall(
0,
aliceAccountName,
contractName,
'setValue', // this is the function defined in a wasm file that we are calling
setArgs);
```
### deployContract

@@ -156,9 +271,13 @@

- `originator`
- `contractId`
- `wasmByteArray`
- `sender` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** account id of the sender
- `contractAccountId` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** account id of the contract
- `wasmArray` **[Uint8Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)** wasm binary
#### Examples
```javascript
const response = await nearjs.deployContract(contractName, data);
```
### getTransactionStatus

@@ -172,2 +291,9 @@

#### Examples
```javascript
// get the result of a transaction status call
const result = (await this.getTransactionStatus(transactionHash)).result
```
### waitForTransactionResult

@@ -187,2 +313,8 @@

#### Examples
```javascript
const result = await this.waitForTransactionResult(transactionHash);
```
### loadContract

@@ -208,2 +340,13 @@

#### Examples
```javascript
// this example would be a counter app with a contract that contains the incrementCounter and decrementCounter methods
window.contract = await near.loadContract(config.contractName, {
viewMethods: ["getCounter"],
changeMethods: ["incrementCounter", "decrementCounter"],
sender: nearlib.dev.myAccountId
});
```
Returns **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** object with methods corresponding to given contract methods.

@@ -218,1 +361,88 @@

- `nodeUrl` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** url of the near node to connect to (optional, default `'http://localhost:3030'`)
#### Examples
```javascript
Near.createDefaultConfig();
```
## WalletAccount
Wallet based account and signer that uses external wallet through the iframe to sign transactions.
### Parameters
- `appKeyPrefix`
- `walletBaseUrl` (optional, default `'https://wallet.nearprotocol.com'`)
### Examples
```javascript
// if importing WalletAccount directly
const walletAccount = new WalletAccount(contractName, walletBaseUrl)
// if importing in all of nearLib and calling from variable
const walletAccount = new nearlib.WalletAccount(contractName, walletBaseUrl)
// To access wallet globally use:
window.walletAccount = new nearlib.WalletAccount(config.contractName, walletBaseUrl);
```
### isSignedIn
Returns true, if this WalletAccount is authorized with the wallet.
#### Examples
```javascript
walletAccount.isSignedIn();
```
### getAccountId
Returns authorized Account ID.
#### Examples
```javascript
walletAccount.getAccountId();
```
### requestSignIn
Redirects current page to the wallet authentication page.
#### Parameters
- `contract_id` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** contract ID of the application
- `title` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** name of the application
- `success_url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** url to redirect on success
- `failure_url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** url to redirect on failure
#### Examples
```javascript
walletAccount.requestSignIn(
myContractId,
title,
onSuccessHref,
onFailureHref);
```
### signOut
Sign out from the current account
#### Examples
```javascript
walletAccount.signOut();
```
### signTransactionBody
Sign a transaction body. If the key for senderAccountId is not present,
this operation will fail.
#### Parameters
- `body` **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `senderAccountId` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**

2

dev.js

@@ -73,3 +73,3 @@ const nearlib = require('./');

get myAccountId() {
return window.localStorage.getItem(storageAccountIdKey);
return this.deps.storage.localStorage.getItem(storageAccountIdKey);
},

@@ -76,0 +76,0 @@ /**

@@ -22,2 +22,7 @@ const createError = require('http-errors');

* @param {NearClient} nearClient
* @example
* const nearClient = new nearlib.NearClient(
* walletAccount,
* new nearlib.LocalNodeConnection(config.nodeUrl));
* const near = new nearlib.Near(nearClient);
*/

@@ -31,2 +36,4 @@ constructor(nearClient) {

* @param {string} nodeUrl url of the near node to connect to
* @example
* Near.createDefaultConfig();
*/

@@ -45,2 +52,7 @@ static createDefaultConfig(nodeUrl = 'http://localhost:3030') {

* @param {object} args arguments to pass to the method
* @example
* const viewFunctionResponse = await near.callViewFunction(
* contractAccountId,
* methodName,
* args);
*/

@@ -61,3 +73,3 @@ async callViewFunction(contractAccountId, methodName, args) {

const json = JSON.parse(Buffer.from(response.result).toString());
return json.result;
return json;
}

@@ -73,2 +85,9 @@

* @param {object} args arguments to pass to the method
* @example
* const scheduleResult = await near.scheduleFunctionCall(
* 0,
* aliceAccountName,
* contractName,
* 'setValue', // this is the function defined in a wasm file that we are calling
* setArgs);
*/

@@ -114,2 +133,4 @@ async scheduleFunctionCall(amount, originator, contractId, methodName, args) {

* @param {Uint8Array} wasmArray wasm binary
* @example
* const response = await nearjs.deployContract(contractName, data);
*/

@@ -145,2 +166,5 @@ async deployContract(contractId, wasmByteArray) {

* @param {string} transactionHash unique identifier of the transaction
* @example
* // get the result of a transaction status call
* const result = (await this.getTransactionStatus(transactionHash)).result
*/

@@ -164,2 +188,4 @@ async getTransactionStatus(transactionHash) {

* @param {string} options.contractAccountId specifies contract ID for better logs and error messages
* @example
* const result = await this.waitForTransactionResult(transactionHash);
*/

@@ -214,3 +240,9 @@ async waitForTransactionResult(transactionResponseOrHash, options = {}) {

* @returns {object} object with methods corresponding to given contract methods.
*
* @example
* // this example would be a counter app with a contract that contains the incrementCounter and decrementCounter methods
* window.contract = await near.loadContract(config.contractName, {
* viewMethods: ["getCounter"],
* changeMethods: ["incrementCounter", "decrementCounter"],
* sender: nearlib.dev.myAccountId
* });
*/

@@ -217,0 +249,0 @@ async loadContract(contractAccountId, options) {

{
"name": "nearlib",
"description": "Javascript library to interact with near blockchain",
"version": "0.3.5",
"version": "0.4.0",
"repository": {

@@ -34,5 +34,5 @@ "type": "git",

"fix": "eslint . --fix",
"doc": "documentation readme near.js account.js signing/key_pair.js -f md --shallow --section=API --readme-file=API.md"
"doc": "documentation readme near.js account.js wallet-account.js signing/key_pair.js -f md --shallow --section=API --readme-file=API.md"
},
"author": "Evguenia Degtiareva"
}

@@ -29,2 +29,10 @@

* Get the secret key.
* @example
* // Passing existing key into a function to store in local storage
* async setKey(accountId, key) {
* window.localStorage.setItem(
* BrowserLocalStorageKeystore.storageKeyForPublicKey(accountId), key.getPublicKey());
* window.localStorage.setItem(
* BrowserLocalStorageKeystore.storageKeyForSecretKey(accountId), key.getSecretKey());
* }
*/

@@ -37,2 +45,9 @@ getSecretKey() {

* Generate a new keypair from a random seed
* @example
* const keyWithRandomSeed = await KeyPair.fromRandomSeed();
* keyWithRandomSeed.getPublicKey()
* // returns [PUBLIC_KEY]
*
* keyWithRandomSeed.getSecretKey()
* // returns [SECRET_KEY]
*/

@@ -50,2 +65,4 @@ static async fromRandomSeed() {

* @param {Buffer} buffer
* @example
* KeyPair.encodeBufferInBs58(key.publicKey)
*/

@@ -52,0 +69,0 @@ static encodeBufferInBs58(buffer) {

const { Account, KeyPair, Near, InMemoryKeyStore } = require('../');
const { aliceAccountName, newAccountCodeHash, storageAccountIdKey, createFakeStorage, sleep } = require('./test-utils');
const dev = require('../dev');
const fs = require('fs');
const aliceAccountName = 'alice.near';
// every new account has this codehash
const newAccountCodeHash = 'GKot5hBsd81kMupNCXHaqbhv3huEbxAFMLnpcX2hniwn';
const storageAccountIdKey = 'dev_near_user';
let nearjs;

@@ -13,2 +10,5 @@ let account;

beforeAll(async () => {
// To avoid nonce collisions with promise test on alice
await sleep(1000);
keyStore = new InMemoryKeyStore();

@@ -235,3 +235,3 @@ const storage = createFakeStorage();

expect(logs[0]).toEqual(`[${contractName}]: LOG: log before assert`);
expect(logs[1]).toMatch(new RegExp(`^\\[${contractName}\\]: ABORT: "expected to fail" filename: "main.ts" line: \\d+ col: \\d+$`));
expect(logs[1]).toMatch(new RegExp(`^\\[${contractName}\\]: ABORT: "expected to fail" filename: "../out/main.ts" line: \\d+ col: \\d+$`));
expect(logs[2]).toEqual(`[${contractName}]: Runtime error: wasm async call execution failed with error: Wasmer(CallError(Runtime(User { msg: "Error: AssertFailed" })))`);

@@ -246,242 +246,3 @@ });

describe('with promises', () => {
let contract, contract1, contract2;
let oldLog;
let logs;
let contractName = 'test_' + Date.now();
let contractName1 = 'test_' + Math.random();
let contractName2 = 'test_' + Math.random();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
const deploy = async (contractName) => {
const keyWithRandomSeed = await KeyPair.fromRandomSeed();
const createAccountResponse = await account.createAccount(
contractName,
keyWithRandomSeed.getPublicKey(),
10,
aliceAccountName);
await nearjs.waitForTransactionResult(createAccountResponse);
keyStore.setKey(contractName, keyWithRandomSeed);
const data = [...fs.readFileSync('../tests/hello.wasm')];
await nearjs.waitForTransactionResult(
await nearjs.deployContract(contractName, data));
return await nearjs.loadContract(contractName, {
sender: aliceAccountName,
viewMethods: ['getLastResult'],
changeMethods: ['callPromise']
});
};
beforeAll(async () => {
// See README.md for details about this contract source code location.
contract = await deploy(contractName);
contract1 = await deploy(contractName1);
contract2 = await deploy(contractName2);
});
beforeEach(async () => {
oldLog = console.log;
logs = [];
console.log = function() {
logs.push(Array.from(arguments).join(' '));
};
});
afterEach(async () => {
console.log = oldLog;
});
// -> means async call
// => means callback
test('single promise, no callback (A->B)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: null,
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult = await contract1.getLastResult();
expect(lastResult).toEqual({
rs: [],
n: contractName1,
});
});
test('single promise with callback (A->B=>A)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult1 = await contract1.getLastResult();
expect(lastResult1).toEqual({
rs: [],
n: contractName1,
});
const lastResult = await contract.getLastResult();
expect(lastResult).toEqual({
rs: [{
ok: true,
r: lastResult1,
}],
n: contractName,
});
});
test('two promises, no callbacks (A->B->C)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callPromise",
args: {
receiver: contractName2,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: null,
callbackArgs: null,
callbackAdditionalMana: 0,
},
additionalMana: 1,
callback: null,
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult2 = await contract2.getLastResult();
expect(lastResult2).toEqual({
rs: [],
n: contractName2,
});
});
test('two promises, with two callbacks (A->B->C=>B=>A)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callPromise",
args: {
receiver: contractName2,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
},
additionalMana: 2,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult2 = await contract2.getLastResult();
expect(lastResult2).toEqual({
rs: [],
n: contractName2,
});
const lastResult1 = await contract1.getLastResult();
expect(lastResult1).toEqual({
rs: [{
ok: true,
r: lastResult2,
}],
n: contractName1,
});
const lastResult = await contract.getLastResult();
expect(lastResult).toEqual({
rs: [{
ok: true,
r: lastResult1,
}],
n: contractName,
});
});
test('cross contract call with callbacks (A->B->A=>B=>A)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callPromise",
args: {
receiver: contractName,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
},
additionalMana: 2,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult1 = await contract1.getLastResult();
expect(lastResult1).toEqual({
rs: [{
ok: true,
r: {
rs: [],
n: contractName,
},
}],
n: contractName1,
});
const lastResult = await contract.getLastResult();
expect(lastResult).toEqual({
rs: [{
ok: true,
r: lastResult1,
}],
n: contractName,
});
});
test('2 promises with 1 skipped callbacks (A->B->C=>A)', async () => {
const result = await contract.callPromise({args: {
receiver: contractName1,
methodName: "callPromise",
args: {
receiver: contractName2,
methodName: "callbackWithName",
args: null,
additionalMana: 0,
callback: null,
callbackArgs: null,
callbackAdditionalMana: 0,
},
additionalMana: 1,
callback: "callbackWithName",
callbackArgs: null,
callbackAdditionalMana: 0,
}});
expect(result.status).toBe('Completed');
const lastResult2 = await contract2.getLastResult();
expect(lastResult2).toEqual({
rs: [],
n: contractName2,
});
const lastResult = await contract.getLastResult();
expect(lastResult).toEqual({
rs: [{
ok: true,
r: lastResult2,
}],
n: contractName,
});
});
});
// Generate some unique string with a given prefix using the alice nonce.
// Generate some unique string with a given prefix using the alice nonce.
const generateUniqueString = async (prefix) => {

@@ -491,19 +252,1 @@ const viewAccountResponse = await account.viewAccount(aliceAccountName);

};
const createFakeStorage = function() {
let store = {};
return {
getItem: function(key) {
return store[key];
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key) {
delete store[key];
}
};
};

@@ -15,2 +15,12 @@ /**

/**
* Wallet based account and signer that uses external wallet through the iframe to sign transactions.
* @example
* // if importing WalletAccount directly
* const walletAccount = new WalletAccount(contractName, walletBaseUrl)
* // if importing in all of nearLib and calling from variable
* const walletAccount = new nearlib.WalletAccount(contractName, walletBaseUrl)
* // To access wallet globally use:
* window.walletAccount = new nearlib.WalletAccount(config.contractName, walletBaseUrl);
*/
class WalletAccount {

@@ -31,2 +41,7 @@

/**
* Returns true, if this WalletAccount is authorized with the wallet.
* @example
* walletAccount.isSignedIn();
*/
isSignedIn() {

@@ -36,2 +51,7 @@ return !!this._authData.accountId;

/**
* Returns authorized Account ID.
* @example
* walletAccount.getAccountId();
*/
getAccountId() {

@@ -41,2 +61,15 @@ return this._authData.accountId || '';

/**
* Redirects current page to the wallet authentication page.
* @param {string} contract_id contract ID of the application
* @param {string} title name of the application
* @param {string} success_url url to redirect on success
* @param {string} failure_url url to redirect on failure
* @example
* walletAccount.requestSignIn(
* myContractId,
* title,
* onSuccessHref,
* onFailureHref);
*/
requestSignIn(contract_id, title, success_url, failure_url) {

@@ -52,3 +85,7 @@ const currentUrl = new URL(window.location.href);

}
/**
* Sign out from the current account
* @example
* walletAccount.signOut();
*/
signOut() {

@@ -55,0 +92,0 @@ this._authData = {};

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

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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc