Socket
Socket
Sign inDemoInstall

near-sdk-js

Package Overview
Dependencies
Maintainers
2
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

near-sdk-js - npm Package Compare versions

Comparing version 0.5.0-1 to 0.5.0

9

lib/api.d.ts
import { Bytes } from "./utils";
import { PromiseResult } from "./types";
export declare function log(...params: any[]): void;

@@ -20,5 +19,5 @@ export declare function signerAccountId(): string;

export declare function ecrecover(hash: Bytes, sig: Bytes, v: number, malleabilityFlag: number): Bytes | null;
export declare function panicUtf8(msg: string): never;
export declare function logUtf8(msg: string): void;
export declare function logUtf16(msg: string): void;
export declare function panicUtf8(msg: Bytes): never;
export declare function logUtf8(msg: Bytes): void;
export declare function logUtf16(msg: Bytes): void;
export declare function storageRead(key: Bytes): Bytes | null;

@@ -54,3 +53,3 @@ export declare function storageHasKey(key: Bytes): boolean;

export declare function promiseResultsCount(): bigint;
export declare function promiseResult(resultIdx: number | bigint): Bytes | PromiseResult.NotReady | PromiseResult.Failed;
export declare function promiseResult(resultIdx: number | bigint): Bytes;
export declare function promiseReturn(promiseIdx: number | bigint): void;

@@ -57,0 +56,0 @@ export declare function storageWrite(key: Bytes, value: Bytes): boolean;

@@ -143,3 +143,2 @@ import { PromiseResult } from "./types";

export function valueReturn(value) {
log('valueReturn');
env.value_return(value);

@@ -200,12 +199,8 @@ }

}
else if (status == PromiseResult.Failed ||
status == PromiseResult.NotReady) {
return status;
}
else {
throw Error(`Unexpected return code: ${status}`);
throw Error(`Promise result ${status == PromiseResult.Failed ? "Failed" :
status == PromiseResult.NotReady ? "NotReady" : status}`);
}
}
export function promiseReturn(promiseIdx) {
log('promiseReturn');
env.promise_return(promiseIdx);

@@ -212,0 +207,0 @@ }

import { Bytes } from "../utils";
import { Vector } from "./vector";
import { LookupMap } from "./lookup-map";
export declare class UnorderedMap {
readonly prefix: Bytes;
readonly keyIndexPrefix: Bytes;
readonly keys: Vector;
readonly values: Vector;
readonly values: LookupMap;
constructor(prefix: Bytes);
get length(): number;
private set length(value);
isEmpty(): boolean;

@@ -24,3 +23,3 @@ get(key: Bytes): unknown | null;

private keys;
private values;
private map;
constructor(unorderedMap: UnorderedMap);

@@ -27,0 +26,0 @@ next(): {

@@ -1,114 +0,66 @@

import * as near from "../api";
import { u8ArrayToBytes, bytesToU8Array } from "../utils";
import { Vector, VectorIterator } from "./vector";
import { LookupMap } from "./lookup-map";
const ERR_INCONSISTENT_STATE = "The collection is an inconsistent state. Did previous smart contract execution terminate unexpectedly?";
function serializeIndex(index) {
let data = new Uint32Array([index]);
let array = new Uint8Array(data.buffer);
return u8ArrayToBytes(array);
}
function deserializeIndex(rawIndex) {
let array = bytesToU8Array(rawIndex);
let data = new Uint32Array(array.buffer);
return data[0];
}
function getIndexRaw(keyIndexPrefix, key) {
let indexLookup = keyIndexPrefix + JSON.stringify(key);
let indexRaw = near.storageRead(indexLookup);
return indexRaw;
}
export class UnorderedMap {
constructor(prefix) {
this.prefix = prefix;
this.keyIndexPrefix = prefix + "i";
let indexKey = prefix + "k";
let indexValue = prefix + "v";
this.keys = new Vector(indexKey);
this.values = new Vector(indexValue);
this.keys = new Vector(prefix + 'u'); // intentional different prefix with old UnorderedMap
this.values = new LookupMap(prefix + 'm');
}
get length() {
let keysLen = this.keys.length;
let valuesLen = this.values.length;
if (keysLen != valuesLen) {
throw new Error(ERR_INCONSISTENT_STATE);
}
return keysLen;
}
// noop, called by deserialize
set length(_l) { }
isEmpty() {
let keysIsEmpty = this.keys.isEmpty();
let valuesIsEmpty = this.values.isEmpty();
if (keysIsEmpty != valuesIsEmpty) {
throw new Error(ERR_INCONSISTENT_STATE);
}
return keysIsEmpty;
}
get(key) {
let indexRaw = getIndexRaw(this.keyIndexPrefix, key);
if (indexRaw) {
let index = deserializeIndex(indexRaw);
let value = this.values.get(index);
if (value) {
return value;
}
else {
throw new Error(ERR_INCONSISTENT_STATE);
}
let valueAndIndex = this.values.get(key);
if (valueAndIndex === null) {
return null;
}
return null;
let value = valueAndIndex[0];
return value;
}
set(key, value) {
let indexLookup = this.keyIndexPrefix + JSON.stringify(key);
let indexRaw = near.storageRead(indexLookup);
if (indexRaw) {
let index = deserializeIndex(indexRaw);
return this.values.replace(index, value);
let valueAndIndex = this.values.get(key);
if (valueAndIndex !== null) {
let oldValue = valueAndIndex[0];
valueAndIndex[0] = value;
this.values.set(key, valueAndIndex);
return oldValue;
}
else {
let nextIndex = this.length;
let nextIndexRaw = serializeIndex(nextIndex);
near.storageWrite(indexLookup, nextIndexRaw);
this.keys.push(key);
this.values.push(value);
let nextIndex = this.length;
this.keys.push(key);
this.values.set(key, [value, nextIndex]);
return null;
}
remove(key) {
let oldValueAndIndex = this.values.remove(key);
if (oldValueAndIndex === null) {
return null;
}
}
remove(key) {
let indexLookup = this.keyIndexPrefix + JSON.stringify(key);
let indexRaw = near.storageRead(indexLookup);
if (indexRaw) {
if (this.length == 1) {
// If there is only one element then swap remove simply removes it without
// swapping with the last element.
near.storageRemove(indexLookup);
let index = oldValueAndIndex[1];
if (this.keys.swapRemove(index) === null) {
throw new Error(ERR_INCONSISTENT_STATE);
}
// the last key is swapped to key[index], the corresponding [value, index] need update
if (this.keys.length > 0 && index != this.keys.length) {
// if there is still elements and it was not the last element
let swappedKey = this.keys.get(index);
let swappedValueAndIndex = this.values.get(swappedKey);
if (swappedValueAndIndex === null) {
throw new Error(ERR_INCONSISTENT_STATE);
}
else {
// If there is more than one element then swap remove swaps it with the last
// element.
let lastKey = this.keys.get(this.length - 1);
if (!lastKey) {
throw new Error(ERR_INCONSISTENT_STATE);
}
near.storageRemove(indexLookup);
// If the removed element was the last element from keys, then we don't need to
// reinsert the lookup back.
if (lastKey != key) {
let lastLookupKey = this.keyIndexPrefix + JSON.stringify(lastKey);
near.storageWrite(lastLookupKey, indexRaw);
}
}
let index = deserializeIndex(indexRaw);
this.keys.swapRemove(index);
return this.values.swapRemove(index);
this.values.set(swappedKey, [swappedValueAndIndex[0], index]);
}
return null;
return oldValueAndIndex[0];
}
clear() {
for (let key of this.keys) {
let indexLookup = this.keyIndexPrefix + JSON.stringify(key);
near.storageRemove(indexLookup);
// Set instead of remove to avoid loading the value from storage.
this.values.set(key, null);
}
this.keys.clear();
this.values.clear();
}

@@ -136,10 +88,7 @@ toArray() {

let map = new UnorderedMap(data.prefix);
// reconstruct UnorderedMap
map.length = data.length;
// reconstruct keys Vector
map.keys = new Vector(data.prefix + "k");
map.keys = new Vector(data.prefix + "u");
map.keys.length = data.keys.length;
// reconstruct values Vector
map.values = new Vector(data.prefix + "v");
map.values.length = data.values.length;
// reconstruct values LookupMap
map.values = new LookupMap(data.prefix + "m");
return map;

@@ -151,12 +100,15 @@ }

this.keys = new VectorIterator(unorderedMap.keys);
this.values = new VectorIterator(unorderedMap.values);
this.map = unorderedMap.values;
}
next() {
let key = this.keys.next();
let value = this.values.next();
if (key.done != value.done) {
throw new Error(ERR_INCONSISTENT_STATE);
let value;
if (!key.done) {
value = this.map.get(key.value);
if (value === null) {
throw new Error(ERR_INCONSISTENT_STATE);
}
}
return { value: [key.value, value.value], done: key.done };
return { value: [key.value, value ? value[0] : value], done: key.done };
}
}

@@ -9,3 +9,2 @@ import { Bytes } from "../utils";

get length(): number;
private set length(value);
isEmpty(): boolean;

@@ -12,0 +11,0 @@ contains(element: unknown): boolean;

@@ -25,4 +25,2 @@ import * as near from "../api";

}
// noop, called by deserialize
set length(_l) { }
isEmpty() {

@@ -106,4 +104,2 @@ return this.elements.isEmpty();

let set = new UnorderedSet(data.prefix);
// reconstruct UnorderedSet
set.length = data.length;
// reconstruct Vector

@@ -110,0 +106,0 @@ let elementsPrefix = data.prefix + "e";

{
"name": "near-sdk-js",
"version": "0.5.0-1",
"version": "0.5.0",
"description": "High Level JavaScript SDK for building smart contracts on NEAR",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

@@ -32,2 +32,5 @@ # NEAR JavaScript SDK

## Test
We recommend to use near-workspaces to write tests for your smart contracts. See any of the examples for how tests are setup and written.
## Error Handling in NEAR-SDK-JS

@@ -45,5 +48,2 @@

## Test
We recommend to use near-workspaces to write tests for your smart contracts. See any of the examples for how tests are setup and written.
## NEAR-SDK-JS API Reference

@@ -68,4 +68,4 @@

NEAR-SDK-JS is written in TypeScript, so every API function has a type specified by signature that looks familiar to JavaScript/TypeScript Developers. Two types in the signature need a special attention:
- Most of the API take `BigInt` instead of Number as type. This because JavaScript Number cannot hold 64 bit and 128 bit integer without losing precision.
- `Bytes` in both arguments and return represent a byte buffer, internally it's a JavaScript String Object. Any binary data `0x00-0xff` is stored as the char '\x00-\xff'. This is because QuickJS doesn't have ArrayBuffer in C API.
- Most of the API take `bigint` instead of Number as type. This because JavaScript Number cannot hold 64 bit and 128 bit integer without losing precision.
- `Bytes` in both arguments and return represent a byte buffer, internally it's a JavaScript String Object. Any binary data `0x00-0xff` is stored as the char '\x00-\xff'. This is because QuickJS doesn't have Uint8Array in C API.
- To ensure correctness, every `Bytes` argument need to be pass in with the `bytes()` function to runtime type check it's indeed a `Bytes`.

@@ -77,12 +77,12 @@ - If `Bytes` is too long that `bytes()` can cause gas limit problem, such as in factory contract, represents the content of contract to be deployed. In this case you can precheck and guarantee the correctness of the content and use without `bytes()`.

```
function currentAccountId(): String;
function signerAccountId(): String;
function currentAccountId(): string;
function signerAccountId(): string;
function signerAccountPk(): Bytes;
function predecessorAccountId(): String;
function predecessorAccountId(): string;
function input(): Bytes;
function blockIndex(): BigInt;
function blockHeight(): BigInt;
function blockTimestamp(): BigInt;
function epochHeight(): BigInt;
function storageUsage(): BigInt
function blockIndex(): bigint;
function blockHeight(): bigint;
function blockTimestamp(): bigint;
function epochHeight(): bigint;
function storageUsage(): bigint
```

@@ -92,7 +92,7 @@

```
function accountBalance(): BigInt;
function accountLockedBalance(): BigInt;
function attachedDeposit(): BigInt;
function prepaidGas(): BigInt;
function usedGas(): BigInt;
function accountBalance(): bigint;
function accountLockedBalance(): bigint;
function attachedDeposit(): bigint;
function prepaidGas(): bigint;
function usedGas(): bigint;
```

@@ -109,3 +109,3 @@

function ripemd160(value: Bytes): Bytes;
function ecrecover(hash: Bytes, sign: Bytes, v: BigInt, malleability_flag: BigInt): Bytes | null;
function ecrecover(hash: Bytes, sign: Bytes, v: bigint, malleability_flag: bigint): Bytes | null;
```

@@ -118,5 +118,5 @@

function valueReturn(value: Bytes);
function panic(msg?: String);
function panic(msg?: string);
function panicUtf8(msg: Bytes);
function log(msg: String);
function log(msg: string);
function logUtf8(msg: Bytes);

@@ -129,7 +129,7 @@ function logUtf16(msg: Bytes);

```
function promiseCreate(account_id: String, method_name: String, arguments: Bytes, amount: BigInt, gas: BigInt): BigInt;
function promiseThen(promise_index: BigInt, account_id: String, method_name: String, arguments: Bytes, amount: BigInt, gas: BigInt): BigInt;
function promiseAnd(...promise_idx: BigInt): BigInt;
function promiseBatchCreate(account_id: String): BigInt;
function promiseBatchThen(promise_index: BigInt, account_id: String): BigInt;
function promiseCreate(account_id: string, method_name: string, arguments: Bytes, amount: bigint, gas: bigint): bigint;
function promiseThen(promise_index: bigint, account_id: string, method_name: string, arguments: Bytes, amount: bigint, gas: bigint): bigint;
function promiseAnd(...promise_idx: bigint): bigint;
function promiseBatchCreate(account_id: string): bigint;
function promiseBatchThen(promise_index: bigint, account_id: string): bigint;
```

@@ -140,11 +140,13 @@

```
function promiseBatchActionCreateAccount(promise_index: BigInt);
function promiseBatchActionDeployContract(promise_index: BigInt, code: Bytes);
function promiseBatchActionFunctionCall(promise_index: BigInt, method_name: String, arguments: Bytes, amount: BigInt, gas: BigInt);
function promiseBatchActionTransfer(promise_index: BigInt, amount: BigInt);
function promiseBatchActionStake(promise_index: BigInt, amount: BigInt, public_key: Bytes);
function promiseBatchActionAddKeyWithFullAccess(promise_index: BigInt, public_key: Bytes, nonce: BigInt);
function promiseBatchActionAddKeyWithFunctionCall(promise_index: BigInt, public_key: Bytes, nonce: BigInt, allowance: BigInt, receiver_id: String, method_names: String);
function promiseBatchActionDeleteKey(promise_index: BigInt, public_key: Bytes);
function promiseBatchActionDeleteAccount(promise_index: BigInt, beneficiary_id: String);
function promiseBatchActionCreateAccount(promise_index: bigint);
function promiseBatchActionDeployContract(promise_index: bigint, code: Bytes);
function promiseBatchActionFunctionCall(promise_index: bigint, method_name: string, arguments: Bytes, amount: bigint, gas: bigint);
function promiseBatchActionFunctionCallWeight(promise_index: bigint, method_name: string, arguments: Bytes, amount: bigint, gas: bigint, weight: bigint);
function promiseBatchActionTransfer(promise_index: bigint, amount: bigint);
function promiseBatchActionStake(promise_index: bigint, amount: bigint, public_key: Bytes);
function promiseBatchActionAddKeyWithFullAccess(promise_index: bigint, public_key: Bytes, nonce: bigint);
function promiseBatchActionAddKeyWithFunctionCall(promise_index: bigint, public_key: Bytes, nonce: bigint, allowance: bigint, receiver_id: string, method_names: string);
function promiseBatchActionDeleteKey(promise_index: bigint, public_key: Bytes);
function promiseBatchActionDeleteAccount(promise_index: bigint, beneficiary_id: string);
```

@@ -155,5 +157,5 @@

```
function promiseResultsCount(): BigInt;
function promiseResult(result_idx: BigInt, register_id: BigInt): BigInt;
function promiseReturn(promise_idx: BigInt);
function promiseResultsCount(): bigint;
function promiseResult(result_idx: bigint, register_id: bigint): bigint;
function promiseReturn(promise_idx: bigint);
```

@@ -164,6 +166,6 @@

```
function storageWrite(key: Bytes, value: Bytes, register_id: BigInt): BigInt;
function storageRead(key: Bytes, register_id: BigInt): BigInt;
function storageRemove(key: Bytes, register_id: BigInt): BigInt;
function storageHasKey(key: Bytes): BigInt;
function storageWrite(key: Bytes, value: Bytes, register_id: bigint): bigint;
function storageRead(key: Bytes, register_id: bigint): bigint;
function storageRemove(key: Bytes, register_id: bigint): bigint;
function storageHasKey(key: Bytes): bigint;
```

@@ -174,4 +176,4 @@

```
function validatorStake(account_id: String): BigInt;
function validatorTotalStake(): BigInt;
function validatorStake(account_id: string): bigint;
function validatorTotalStake(): bigint;
```

@@ -182,7 +184,37 @@

```
function altBn128G1Multiexp(value: Bytes, register_id: BigInt);
function altBn128G1Sum(value: Bytes, register_id: BigInt);
function altBn128PairingCheck(value: Bytes): BigInt;
function altBn128G1Multiexp(value: Bytes, register_id: bigint);
function altBn128G1Sum(value: Bytes, register_id: bigint);
function altBn128PairingCheck(value: Bytes): bigint;
```
### NearBindgen and other decorators
You can write a simple smart contract by only using low-level APIs, such as `near.input()`, `near.storageRead()`, etc. In this case, the API of your contract will consist of all the exported JS functions. You can find an example of such a contract [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/counter-lowlevel.js).
But if you want to build a more complex contracts with ease, you can use decorators from this SDK that will handle serialization, deserialization, and other boilerplate operations for you.
In order to do that, your contract must be a class decorated with `@NearBindgen({})`. Each method in this class with `@call({})`, `@view({})`, and `@initialize({})` decorators will become functions of your smart contract. `call` functions can change state, and `view` functions can only read it.
Your class must have a `constructor()`. You will not be able to call it, which is why it should not accept any parameters. You must declare all the parameters that you are planning to use in the constructor and set default values.
The simplest example of the contract that follows all these rules can be found [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message.js)
`NearBindgen` decorator can accept `requireInit parameter`.
```JS
@NearBindgen({ requireInit: true })
class YourContract {
...
}
```
It is `false` by default, but if you will set it to `true`, it will prevent all the `call` functions from being executed before you initialize the state of the contract.
In order to initialize the contract, you need to add functions flagged with `@initialize({})` decorator.
`@call({})` decorator can accept two parameters: `privateFunction` and `payableFunction`. They are both `false` by default.
`privateFunction: true` can restrict access to this function to the contract itself.
`payableFunction: true` will allow the function to accept payments (deposit). Without this flag, it will panic if any deposit was provided.
### Collections

@@ -424,1 +456,74 @@ A few useful on-chain persistent collections are provided. All keys, values and elements are of type `Bytes`.

```
### Highlevel Promise APIs
Within a contract class that decorated by `@Nearbindgen`, you can work a high level JavaScript class, called `NearPromise`. It's equivalently expressive as promise batch APIs but much shorter to write and can be chained like a JavaScript Promise.
In a `@call` method, you can return either a JavaScript value or a `NearPromise` object. In the later case, `@NearBindgen` will automatically `promiseReturn` it for you.
Usage:
```js
// create new promise
import {NearPromise, near} from 'near-sdk-js'
import { PublicKey } from 'near-sdk-js/lib/types'
let promise = NearPromise.new('account-to-run-promise')
// possible promise actions, choose and chain what you need:
promise.createAccount()
.transfer(1_000_000_000_000_000_000_000_000_000_000_000_000n)
.addFullAccessKey(new PublicKey(near.signerAccountPk()))
.addAccessKey(new PublicKey(near.signerAccountPk()), 250000000000000000000000n, // allowance
'receiver_account_id', 'allowed_function_names')
.stake(100000000000000000000000000000n, new PublicKey(near.signerAccountPk()))
.deployContract(includeBytes('path/to/contract.wasm'))
.functionCall('callee_contract_account_id', inputArgs,
0, // amount
2 * Math.pow(10, 13), // gas
)
.functionCallWeight(
'callee_contract_account_id', inputArgs,
0, // amount
2 * Math.pow(10, 13), // gas
1, // weight
)
.deleteKey(new PublicKey(near.signerAccountPk()))
.deleteAccount('beneficial_account_id')
return promise
```
In the case of deploy contract, `includeBytes` is a helpful build-time util. You can include the content of a wasm contract, by using `includeBytes('path/to/contract.wasm')`.
In the case of `addFullAccessKey`, `addAccessKey` and `stake`, it takes a `PublicKey` object, you can find more details about it in the Types sections below.
Besides above APIs to build something on top of an API, you can also chain promises with `.then` and `.and`, they're equivalent to promiseThen, promiseAnd:
```js
// assume promise, promise2 and promise3 are create with above APIs, with several actions added like above.
promise.and(promise2).then(promise3) // promiseAnd of [promise_id, promise2_id], then promiseThen(promise_and_id, promise3_id)
return promise
```
### Types
NEAR-SDK-JS also includes type defintions that are equivalent to that in Rust SDK / nearcore. You can browse them in near-sdk-js/src/types. Most of them are just type alias to Bytes and bigint.
#### Public Key
Public Key is representing a NEAR account's public key in a JavaScript class. You can either initiate a Public Key from binary data, or from a human readable string.
The binary data is in the same format as nearcore, but encoded in bytes. That's one byte to represent the curve type of the public key, either ed25519 (`\x00`), or secp256k1 ('\x01'), follows by the curve-specific public key data in bytes. Examples:
```js
new PublicKey(near.signerAccountPk())
new PublicKey("\x00\xeb\x7f\x5f\x11\xd1\x08\x1f\xe0\xd2\x24\xc5\x67\x36\x21\xad\xcb\x97\xd5\x13\xff\xa8\x5e\x55\xbc\x2b\x74\x4f\x0d\xb1\xe9\xf8\x1f")
new PublicKey("\x01\xf2\x56\xc6\xe6\xc8\x0b\x21\x3f\x2a\xa0\xb0\x17\x44\x23\x5d\x51\x5c\x59\x44\x35\xbe\x65\x1b\x15\x88\x3a\x10\xdd\x47\x2f\xa6\x46\xce\x62\xea\xf3\x67\x0d\xc5\xcb\x91\x00\xa0\xca\x2a\x55\xb2\xc1\x47\xc1\xe9\xa3\x8c\xe4\x28\x87\x8e\x7d\x46\xe1\xfb\x71\x4a\x99")
```
The human readable form is `ed25519:` or `secp256k1:` following base58-encoded public key. And initialize the Public Key with `PublicKey.fromString`:
```js
PublicKey.fromString('ed25519:DXkVZkHd7WUUejCK7i74uAoZWy1w9AZqshhTHxhmqHuB`)
PublicKey.fromString('secp256k1:5r22SrjrDvgY3wdQsnjgxkeAbU1VcM71FYvALEQWihjM3Xk4Be1CpETTqFccChQr4iJwDroSDVmgaWZv2AcXvYeL`)
```
Once a PublicKey object is created, it can be used in high level promise APIs that takes a public key, such as `addFullAccessKey`, `addAccessKey` and `stake`.
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