GithubHelp home page GithubHelp logo

near / near-sdk-js Goto Github PK

View Code? Open in Web Editor NEW
192.0 10.0 65.0 95.56 MB

Tools for building NEAR smart contracts in JavaScript

Home Page: https://near.github.io/near-sdk-js/

License: MIT License

C 11.20% JavaScript 37.42% TypeScript 51.38%
near near-protocol sdk smart-contract-tools

near-sdk-js's Introduction

NEAR JavaScript SDK

Version Documentation License: LICENSE License: LICENSE

A JavaScript library for writing NEAR smart contracts.

Prerequisites

  • node >=14 <16.6.0 || >16.6.0
  • pnpm >=7

Quick Start

Use create-near-app to quickly get started writing smart contracts in JavaScript on NEAR.

npx create-near-app

This will scaffold a basic template for you 😎

Documentation

Contributing

If you are interested in contributing, please look at the contributing guidelines.

License

This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE and LICENSE-APACHE for details.

near-sdk-js's People

Contributors

ailisp avatar armujahid avatar austinabell avatar austinbaggio avatar bellard avatar benkurrek avatar bucanero avatar chaotictempest avatar davidm-d avatar derektbrown avatar fospring avatar gagdiez avatar idea404 avatar itegulov avatar matiasbenary avatar maxhr avatar near-bulldozer[bot] avatar nsejim avatar nujabes403 avatar olyno avatar osalkanovic avatar petarvujovic98 avatar sandoche avatar springchiu avatar think-in-universe avatar thisisjoshford avatar volovyks avatar vunderkind avatar waynenilsen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

near-sdk-js's Issues

Could not load 'examples/hello_near.js'

I'm currently running on an M1 Max Chip and have installed the prerequisites using the following commands:
1. arch -arm64 brew install wget
2. arch -arm64 brew install cmake
3. arch -arm64 brew install make

I then ran the setup script followed by the build script:

  • ./setup.sh
  • ./build.sh

Following the instructions for running on testnet, I then ran the following command./builder.sh examples/hello_near.js which threw an error saying
Could not load 'examples/hello_near.js'

I also tried running ./builder.sh examples/low_level/hello_near.js but the error was the same.

`panic` incorrect signature

Takes a message when there is no message with this host function. Might be misleading for developers

Edit: seems internally this expects a string and then if empty uses the panic. A bit of a strange assumption. Feel free to close, but I don't see the benefit in this

Automatic `Object.assign` calls when deserializing collections

super.deserialize()
this.records.keys = Object.assign(new Vector, this.records.keys)
this.records.values = Object.assign(new Vector, this.records.values)
this.records = Object.assign(new UnorderedMap, this.records)
this.uniqueValues = Object.assign(new LookupSet, this.uniqueValues)

Is an example of the code I'm referring to. I'm wondering why this can't happen within the deserialize function, or if this is documented somewhere?

jsvmCallRaw inconsistent serialization

jsvmCallRaw

near-sdk-js/src/api.js

Lines 201 to 203 in 37965b8

export function jsvmCallRaw(contractName, method, args) {
env.jsvm_call(contractName, method, JSON.stringify(args), 0)
return env.read_register(0)
is a bit misleading because it still serializes args as JSON. The difference between jsvmCall is that it doesn't deserialize the JSON, so to be symmetric with this and to allow a lower-level interface that can be expanded on to allow more than just JSON, this needs to be changed to just accept bytes.

This will be a breaking change, but better that it comes in sooner than later. It is a misleading name and functionality.

Switch APIs of internal collection functions to indicate private

Not sure what the convention is for obfuscating the functions from developers, but functions like serializeIndex, deserializeIndex should be more clear that they shouldn't be used.

I don't think there is any reason why they need to be exposed so either moving them out of the class so they aren't exposed or prefixing with _ or internal should probably be done.

yarn install in `tests/` or `example/` circularly include near-sdk-js/tests and examples

Every time I change something in SDK and rebuild examples, I yarn build in root directory and remove the near-sdk-js dependency from tests/ or examples/, then re-add near-sdk-js to package.json and redo yarn to make near-sdk-js update. (If just run yarn in tests/ or examples/ doesn't take the changes). However, yarn install in tests/ or example/ appears to circularly include near-sdk-js/tests and examples and result in 500K+ dependencies in yarn link dependency step, very slow, and after a few times, ~/.cache/yarn increase to more than 200 GB

I also tried yarn link near-sdk-js, but near-sdk-js cli seems not working with this symlinked path.

@volovyk-s What is your workflow if you update something on sdk-js ts files and use the change in examples? Is it better?

Not a function panic using wasm approach

I've ported over the standalone branch into my own JS game (found here) and I've got it correctly building the wasm file. I can deploy the file on-chain but I cannot interact with it without getting a Smart contract panicked: not a function\n error.

The way I enabled wasm support is by simply copying over the builder.sh script found in the standalone branch (file found here in the SDK repo and here in my game repo). The steps to reproduce is to simply go through the wasm version of my README (readme found here).

This error happens for both view and call functions. An example is shown in the transaction below: https://explorer.testnet.near.org/transactions/4gieFzFqr8QUsqD7P6rEGSAPsvkHqe9GVvjEBDysakcG

Insufficient deposit for storage

I’m getting a super strange error that I can’t seem to debug… I’m going through and finishing up a gnarly frontend for my game (which is basically finished at this point) and I’m at the point where everything works until you try and make the winning move.

Once you make the winning move, the smart contract panics and says “Smart contract panicked: insufficient deposit for storage”. I’m not adding anything to the state of the contract in this case and I have no clue why it could be throwing this error message… This is a link to what code is being executed in the winning case and this is a link to the transaction.

It looks like the panic is happening within the jsvm contract in the function deduct_cost which gets executed within a storage_write. I'm confused because the only thing i'm changing in this case is that I'm switching a boolean from true to false but the boolean already lives in the state of the contract so this shouldn't take up any excess storage...

Standalone flag

The current near-sdk build command creates a wasm file to be deployed in the js-vm. We should give users the option of creating the a standalone wasm file as well.

This could be done adding a --standalone flag to near-sdk build. In this way near-sdk build --standalone would create a wasm file ready to deploy in the classic NEAR blockchain.

jsvm_value_return does not return value when there's deposit refund

I recently discovered this problem. jsvm_value_return and underlying value_return doesn't work when there is refund in storage deposit. This is because storage deposit refund will lead to transaction returns a promise, and value return is overwritten. And jsvm does refund storage deposit whenever more than required storage deposit is attached, or contract call free some space. Will figure out a solution.

initFunction in deploy_js_contract?

While digging through the C code, I couldn't find how to do initFunction anywhere when calling into deploy_js_contract. Correct me if I'm wrong, but it's only assuming input(1) is code bytes. Is there a different input method I'm overlooking? I'm only seeing that we're making a separate call into the init function via call_js_contract. If it's only done through call_js_contract, we should incorporate it into deploy_js_contract otherwise people can potentially be frontrunned where someone else called into the init function before the owner of the contract gets a chance to

How to supply gas into cross contract call?

Not seeing a way to supply the prepaid gas into a cross contract call anywhere in near.jsvmCall. This should be similar to how the RS SDK does it: https://github.com/near/near-sdk-rs/blob/6555ec593c9185898b7d9d51cf2c884b9e237722/examples/factory-contract/low-level/src/lib.rs

Is the enclave doing something different where cross contract calls don't need gas? That would be strange behavior and would feel like it's unintended if someone were to supply a gas amount but not know how much ends up getting used for the cross contract call.

Additionally, if work is needed here, we might need to consider adding the weighted gas API as well or leave some room to add it in the future. cc @austinabell

Remove `len` and `isEmpty` methods from collections

I can't seem to find the equivalents with JS libraries. For example Array to our Vector exposes length field as a number, but then doesn't have either of those functions.

Removing would make it so that this doesn't have to be maintained if this ever wanted to be removed in the future.

Change `Bytes` from `string` alias to avoid misuse

Somewhat related to #78 but the issue currently is that someone can pass any string into any function that accepts Bytes. This is a foot gun because it will cause bugs.

Uncertain if the jsvm panics if it encounters a value >8bits (since strings are utf16), but regardless it causes a crash at runtime or UB to the developer.

Intuitively, and this might not be ideal but to take a guess, Bytes would be a class that can be constructed by multiple types but validated that it's bytes and maybe the inputs are Bytes | Uint8Array since Uint8Array seems like it would be a common type from libraries.

Alternatively only accepting Bytes and forcing developers to be more explicit with what they pass in. Likely

near-sdk-js/src/utils.js

Lines 17 to 24 in 37965b8

export function bytes(strOrU8Array) {
if (typeof strOrU8Array == "string") {
return checkStringIsBytes(strOrU8Array)
} else if (strOrU8Array instanceof Uint8Array) {
return u8ArrayToBytes(strOrU8Array)
}
throw new Error('bytes: expected string or Uint8Array')
}
would be the logic used by the constructor of bytes.

Figure out a way to unit test collections

quickjs doesn't support require, so cannot conditionally require mocked host functions to test collections

We don’t have to have this before the first release, but certain collections' functionality need at least being tested indirectly by examples

Unable to build project folder

I navigated to the near-sdk-js/examples/project folder and I ran npm i which worked with no problems. I then ran the build script ./build.sh and got the following output:

 ./build.sh

index.js → build/project.js...
 <span class="error">[!]</span> (plugin babel) Error: <span class="error">[BABEL]</span>: Cannot find package '@babel/types' imported from /Users/benjaminkurrek/Desktop/work/near/near-sdk-js/sdk/near-bindgen-exporter.js (While processing: /Users/benjaminkurrek/Desktop/work/near/near-sdk-js/sdk/near-bindgen-exporter.js)
 index.js
 Error <span class="error">[PLUGIN_ERROR]</span>: <span class="error">[BABEL]</span>: Cannot find package '@babel/types' imported from /Users/benjaminkurrek/Desktop/work/near/near-sdk-js/sdk/near-bindgen-exporter.js (While processing: /Users/benjaminkurrek/Desktop/work/near/near-sdk-js/sdk/near-bindgen-exporter.js)
 at new NodeError (node:internal/errors:371:5)
 at packageResolve (node:internal/modules/esm/resolve:884:9)
 at moduleResolve (node:internal/modules/esm/resolve:929:18)
 at defaultResolve (node:internal/modules/esm/resolve:1044:11)
 at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
 at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
 at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
 at link (node:internal/modules/esm/module_job:75:36)

I tried deleting node_modules and yarn.lock and running an npm i once again but I had no luck.

I also tried running npm run build which threw the same error

I'm running an M1 MAX

Storage interface should be bytes, not strings

Forcing string usage for all storage interactions like storage read, write, register reads is inefficient because it requires data to be stringified in some way (JSON, base64) which is very space inefficient and won't scale well.

Low-level options, that pass slices of bytes should be provided to enable people to use things like borsh or some binary encoding protocol that's more efficient.

The string APIs can still be built on top of these for convenience, but it seems more useful to provide a higher-level API that serializes objects as JSON, for example

u8ArrayToString creates invalid utf8 strings

Since it's unchecked, the strings created by it will be invalid strings. Unsure if this is lossy if JS keeps the internal bytes, but this seems unsafe to do.

The issue seems to be also if you're trying to parse a non unicode/utf8 character for the other side of this conversion that there will be an overflow. Unsure how the jsvm handles this tested and seems this just overflows, so someone could potentially overwrite values they don't have permissions for

Make `PromiseIndex` type to avoid misuse of promise indices

Context: this is an optional and breaking suggestion

Currently, most APIs use BigInt or number | BigInt to represent the promise indices, which is very prone for misuse.

Take:

export function promiseBatchActionTransfer(promiseIndex: number | BigInt, amount: number | BigInt)

This function makes it very easy to swap the order of these and cause a bug at runtime either from unexpected behavior or a panic at runtime if the promise index does not exist.

There should be no way to manually construct a promise index, so it would be preferred if promiseCreate and other related functions returned a class/object that are only constructed by those functions. This would allow those bugs to be caught at compile time when using TS and runtime if using JS (but friendlier runtime error than if this wasn't done).

A lot of these APIs are way too easy to misuse, which will cause issues for people.

Add formatting/linting to project

Noticed there was no consistent formatting/linting included for this project and it will cause unnecessary merge conflicts. This should be enforced by the CI as well.

Encoded call serialization format

So the encoding for calls seems to be strings, separated by 0 bytes

export function encodeCall(contract, method, args) {

But there isn't anything preventing javascript from having a 0 byte in any of these strings (afaik) so someone could just include a zero byte in the string to break the parsing of this. I'm unsure about the implications because I can't seem to easily find where this format is decoded, so if someone could point me in that direction it would be helpful.

To me, a question may be why this format is not versioned to allow things to change in the future. Reasons this could potentially change are:

  • having each serialized bytes length prefixed to avoid ambiguity (mentioned above)
  • Allowing contracts to be called by an index where they are stored – avoiding unnecessary calldata for optimization
  • Switch args serialization from JSON to optimize, or switch the format of this JSON as @volovyk-s is currently exploring

to name a few. Adding a version byte at the start will allow these changes to be handled without hard-breaking existing functionality.

Remove external utilities from SDK API

Low confidence suggestion:

near-sdk-js/src/utils.js

Lines 17 to 19 in f03eb1a

export function encodeCall(contract, method, args) {
return Buffer.concat([Buffer.from(contract), Buffer.from([0]), Buffer.from(method), Buffer.from([0]), Buffer.from(JSON.stringify(args))])
}

Probably shouldn't be exposed from the SDK API because it is just a utility used externally from the contract and can't even be used from within because Buffer is not available from the rollup generated code.

This might be a foot gun for developers if they see this within the SDK. Doesn't seem to be used anyway or exported though, so this might just be as simple as removing the code

collections requiring keys and values be serialized to strings

This is unintuitive for developers, since it's unclear strings exactly are required without any type indications, but also it's a very limiting API.

Ideally, for functions available, my suggestion (opinionated) is to have low-level functions such as getRaw, pushRaw, replaceRaw along with other core interfaces possibly under another class and then build these high-level APIs on top of that with some convenience such as JSON stringifying keys and values.

The main problem is string should not be the key and value type of these structures because it will be too far from the js std library equivalents

TypeScript support tracking issue

Scoping this out, seems totally possible for this lib to be converted to typescript.

Unsure of the overhead of allowing contracts to be ts since it seems the pattern is to just use this library, but this is what the path seems to look like:

  • Switch near-sdk-js to typescript (#82)
  • Add support into JS CLI to build typescript contracts? (this one is a bit unclear because there is some convoluted logic in there)
  • Switch some or all examples to TS

Options for adding support to SDK CLI to build typescript contracts intuitively to me are:

  • Conditionally use the typescript plugin for rollup to be able to compile ts contract file
    • This would require checking the input file name for the type to be able to include typescript plugin or not – maybe both index.js and index.ts are checked for existence? Otherwise, someone doing ts contracts will just have to specify the source argument to the ts file.
  • Modify CLI to compile the TS contract file to ESM JS and use that file in the rollup
  • Don't change any tooling, developers can compile ts to JS themselves and just update the source argument to this file

Issues with `Linux-x86_64-qjsc`: Permission denied

I had issues with Linux-x86_64-qjsc during npm run build on Centos 7, Nodejs 14.7:

Error: Command failed: ./node_modules/near-sdk-js/res/Linux-x86_64-qjsc -c -m -o build/status-message.h -N code build/status-message.js
/bin/sh: ./node_modules/near-sdk-js/res/Linux-x86_64-qjsc: Permission denied

    at ChildProcess.exithandler (child_process.js:390:12)
    at ChildProcess.emit (events.js:400:28)
    at maybeClose (internal/child_process.js:1055:16)
    at Socket.<anonymous> (internal/child_process.js:441:11)
    at Socket.emit (events.js:400:28)
    at Pipe.<anonymous> (net.js:675:12) {
  killed: false,
  code: 126,
  signal: null,
  cmd: './node_modules/near-sdk-js/res/Linux-x86_64-qjsc -c -m -o build/status-message.h -N code build/status-message.js',
  stdout: '',
  stderr: '/bin/sh: ./node_modules/near-sdk-js/res/Linux-x86_64-qjsc: Permission denied\n'
}

chmod +x ./node_modules/near-sdk-js/res/Linux-x86_64-qjsc resolved my problem.

Rename near-sdk bin to near-sdk-js

Currently, the binary is called near-sdk, which I think can be confusing once installed in a computer, specially since we have more than one SDK.

I suggest to rename it to near-sdk-js. I will modify it and make a PR implementing the suggested change.

Add JS commands to CLI for JS SDK

Options:

  1. New JS CLI commands -> Deprecate JS CLI -> Re-implement as RS CLI extension.
  2. Standalone binary that will become RS CLI extension once it's released.
  3. Option 2 + extension system in JS CLI.

https://near--inc.slack.com/archives/C036BC1UR0A/p1652156537509259

Decision:

Solution 1 - add new commands to JS CLI. We decided this for ease of implementation. It is likely we will re-implement in the Rust CLI when we invest in that longer term.

Acceptance Criteria

Support the following 5 calls

  • call
  • view
  • view-state
  • deploy
  • dev-deploy

with the format: js-call, js-view, js-deploy. . .

Extra Context

The above matches the EVM pattern: evm-call evm-view evm-deploy

Warning from use of experimental decorators

Experimental decorators might scare of a new to NEAR, or more junior developer. Not sure what the alternatives are to remove or suppress this warning from the SDK so the developer doesn't see it.

(method) StatusMessage.set_greeting(message: any): void Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.ts(1219) No quick fixes available

Using VSCode with JS linter

Hide exposed utility functions in collections

Some utility functions, which should not be exposed publicly, should just be converted into internal functions to avoid confusion and make this change less breaking in the future.

Offending functions:

serializeIndex(index) {
let data = new Uint32Array([index])
let array = new Uint8Array(data.buffer)
return u8ArrayToBytes(array)
}
deserializeIndex(rawIndex) {
let array = bytesToU8Array(rawIndex)
let data = new Uint32Array(array.buffer)
return data[0]
}
getIndexRaw(key) {
let indexLookup = this.keyIndexPrefix + key
let indexRaw = near.jsvmStorageRead(indexLookup)
return indexRaw
}

serializeIndex(index) {
let data = new Uint32Array([index])
let array = new Uint8Array(data.buffer)
return u8ArrayToBytes(array)
}
deserializeIndex(rawIndex) {
let array = bytesToU8Array(rawIndex)
let data = new Uint32Array(array.buffer)
return data[0]
}

https://github.com/near/near-sdk-js/blob/master/src/collections/vector.js#L23-L28

Getting `unreachable` opcode error when calling into jsvm.testnet

I'm trying to make a call into jsvm.testnet on the example status message contract and getting this error:

❯ near call jsvm.testnet call_js_contract
--accountId instanton.testnet
--args $(node near-sdk-js/encode_call.js instanton.testnet init '')
--base64

Scheduling a call: jsvm.testnet.call_js_contract(aW5zdGFudG9uLnRlc3RuZXQAaW5pdAA=)
Doing account.functionCall()
Receipt: 3F6XonmvVDs8mFeGXxVcn1W17PnH416WD8uYgmt7j5Hu
Failure [jsvm.testnet]: Error: {"index":0,"kind":{"ExecutionError":"WebAssembly trap: An unreachable opcode was executed."}}
ServerTransactionError: {"index":0,"kind":{"ExecutionError":"WebAssembly trap: An unreachable opcode was executed."}}
at Object.parseResultError (/Users/tensor/space/near-cli-js/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29)
at Account.signAndSendTransactionV2 (/Users/tensor/space/near-cli-js/node_modules/near-api-js/lib/account.js:160:36)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async scheduleFunctionCall (/Users/tensor/space/near-cli-js/commands/call.js:57:38)
at async Object.handler (/Users/tensor/space/near-cli-js/utils/exit-on-error.js:52:9) {
type: 'FunctionCallError',
context: undefined,
index: 0,
kind:

{ ExecutionError: 'WebAssembly trap: An unreachable opcode was executed.' }

,
transaction_outcome: {
block_hash: '6Fboj3nZsE6NNLNYWXDJAC8qkLGUfFXpX4r6ZRaTL6sp',
id: 'A4nZ5XtcUptfppbggrJkKrpEmNb69KayQRZWQvRkimTs',
outcome:

{ executor_id: 'instanton.testnet', gas_burnt: 2428008201426, logs: [], metadata: [Object], receipt_ids: [Array], status: [Object], tokens_burnt: '242800820142600000000' }

,
proof: [ [Object], [Object], [Object] ]
}
}

@ailisp any ideas what this could be?

Allow prefix to be bytes in collections

There seems to be an implicit bias towards these collections indexing with a string, but this is somewhat limiting because the range of values is somewhat unclear and hard to use if someone wanted to keep prefixes minimal.

Ideally, prefixes and indexing were all done in bytes, so there wasn't a reliance on strings

JS SDK Should Auto-Convert camelCase to snake_case for Function Names

Introduction

During last DevRel working session, Benji pointed out that the names inconsistencies between JS and Rust for functions will lead to inconsistent naming for logic that is performed on chain.

e.g.:
nft_mint for a Rust contract vs. nftMint for a JS contract

Problem

dApps that listen to data on-chain searching for specific function names will miss data. Some dApps might be built foundationally on the assumption of this being consistent.

Solution

JS SDK auto-converts naming for view and call methods from camelCase or whatever case to snake_case to keep consistency with existing function naming for the ecosystem.

Remove need for redundant reads/writes for `UnorderedMap`

Seems like the implementation was taken from the old Rust SDK algorithm. The inefficiency is that it stores a mapping of key to index, one vector for keys and one for vector.

So for every read/write, you are charging basically twice for each read/write since they are separated instead of just being one vector of key/value tuples (<span class="error">[string, string]</span>). This is an easy optimization but is state-breaking.

The second inefficiency is having to do two storage reads when retrieving any value because the indices are stored in a separate lookup. This is also inefficient because you do swap_removes when removing entries, and this means that two different storage reads need to be charged for this operation.

The optimized version (which may not be perfect, but what we decided to go with) is here https://github.com/near/near-sdk-rs/blob/1a39f1e2406517ee93bc4efb0b859751297e645d/near-sdk/src/store/unordered_map/mod.rs. The FreeList type that is used isn't required, but removes the requirement of having to swap_remove values.

My recommendation would be to optimize this sooner than later before it starts being used in prod, or else you will be stuck with this inefficiency to avoid making state-breaking changes (like we are with the collection this algo was taken from).

Transfer $NEAR in JS contract

The current near-sdk-js APIs don't support performing actions with Promise.

But it's a common requirement that the contract needs to transfer $NEAR from the current contract to another account. (e.g. new Promise(account_id).transfer(amount)). Do we plan to support that?

I understand the complexity. because we only have virtual JS contracts in the JSVM, we may need to track the received / sent $NEAR with the virtual JS contract accounts.

A relevant question is to track the attached_deposit sent to the JS contract when executing call_js_contract.

"undefined" instead of undefined

if value is not available, jsvmStorageRead() return s "undefined" (as a string), instead of JS native undefined.
It breaks the logic like:

const res = near.jsvmStorageRead(...)

if (res) { // <-- `true` instead of `false`
// do something
}

Rollup fails witn Node v16.6.0

We should understand why this is happening and fix the bug or set supported versions of Node. Works fine with Node v16.14.2

`GLIBC_2.29' not found

Hi,

I ran:

near-sdk build contract/index.js

With the following contract:

import { NearBindgen, NearContract, call, view } from 'near-sdk-js';

// The @NearBindgen decorator allows this code to compile to Base64.
@NearBindgen
class MyContract extends NearContract {
  constructor() {
    //execute the NEAR Contract's constructor
    super();
    this.my_greeting = 'Hello Web3 World!';
  }

  // @call indicates that this is a 'change method' or a function
  // that changes state on the blockchain. Change methods cost gas.
  // For more info -> https://docs.near.org/docs/concepts/gas
  @call
  set_greeting({ message }) {
    env.log(`Saving greeting ${message}`);
    this.my_greeting = message;
  }

  // @view indicates a 'view method' or a function that returns
  // the current values stored on the blockchain. View calls are free
  // and do not cost gas.
  @view
  view_greeting() {
    env.log(`The current greeting is ${this.my_greeting}`);
    return this.my_greeting;
  }
}

With the sdk version 0.4.0-2 and Node.js version v17.9.1 I got this error:

> near-sdk build contract/index.js

Building contract/index.js contract...
Creating build directory...
mkdir -p build

Creating build/contract.js file with Rollup...
Near bindgen export done
Creating build/contract.h file with QJSC...
node_modules/near-sdk-js/cli/deps/qjsc -c -m -o build/contract.h -N code build/contract.js
near-sdk build [source] [target]

Build NEAR JS Smart-contract

Positionals:
  source  Contract to build                   [string] [default: "src/index.js"]
  target  Target file path and name    [string] [default: "build/contract.wasm"]

Options:
  --version  Show version number                                       [boolean]
  --help     Show help                                                 [boolean]

Error: Command failed: node_modules/near-sdk-js/cli/deps/qjsc -c -m -o build/contract.h -N code build/contract.js
node_modules/near-sdk-js/cli/deps/qjsc: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (required by node_modules/near-sdk-js/cli/deps/qjsc)

    at ChildProcess.exithandler (node:child_process:398:12)
    at ChildProcess.emit (node:events:527:28)
    at maybeClose (node:internal/child_process:1090:16)
    at Socket.<anonymous> (node:internal/child_process:449:11)
    at Socket.emit (node:events:527:28)
    at Pipe.<anonymous> (node:net:715:12) {
  code: 1,
  killed: false,
  signal: null,
  cmd: 'node_modules/near-sdk-js/cli/deps/qjsc -c -m -o build/contract.h -N code build/contract.js',
  stdout: '',
  stderr: "node_modules/near-sdk-js/cli/deps/qjsc: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (required by node_modules/near-sdk-js/cli/deps/qjsc)\n"
}
 ELIFECYCLE  Command failed with exit code 1.

I am running this on WSL2

init() calls

Now we need to call

// Init the contract
    await onCall.call(onCall, 'init', {});

after each deployment. It is not the best UX, we can get some inspiration in SDK RS (default implementations).

Can't return Object from function

I can't seem to return an object from my function. This is the code I have right now where boardState is:

this.boardState = {
 "row1": 1,
 "row2": 2,
 "row3": 3,
 "row4": 4,
 "row5": 5
 }
/*
 get the current state of the smart contract. This includes:
 full board state, player 1, 2, current turn, whether the game is active or not.
 */
 @view
 getState() {
 env.log("Get state called!")
 for (const row in this.boardState) {
 env.log(`$

 {row} 

: $

 {this.boardState[row]} 

`);
 }
 env.log(`player one: $

 {this.playerOne} 

`);
 env.log(`player two: $

 {this.playerTwo} 

`);
 env.log(`current turn: $

 {this.currentTurn} 

`);
 env.log(`game active: $

 {this.isGameActive} 

`);

 return this.boardState;
 }

Here is an example transaction: https://explorer.testnet.near.org/transactions/F4j71D9f5G6yvHRgvAyLzd5TsLzRpUYyQvZQDM3tMLjp

The object isn't being returned for some reason. A link to my repo can be found here

`@NearBindgen` is tightly coupled with build tool

I was experimenting with writing an extension for the near-sdk-js library when I discovered this file, which appears to add the code that actually interacts with the JSVM. Unfortunately, this logic is:

  • Not particularly easy to read or even find
  • Adding functionality to @NearBindgen which is not in its definition, i.e. @NearBindgen does more than you would believe if you only read its definition
  • Forcing projects to use a particular build tool configuration

I think it would be significantly better for JSVM contracts to simply be ECMAScript modules, where exported functions are the contract's public interface.

Delete near.panic()

near.panic('Message') is doing exactly the same as throw new Error('message'). Let's delete near.panic('Message'), mentions that this env.panic() API is not used and refactor examples/tests.

Add/Improve error handling

Currently, a lot of errors or safety checks aren't being handled properly. This issue documents a few of them so we can track progress. This is not exhaustively all of them, so add more as they come in:

  • deploy: if fed incorrect bytes will do nothing, and later when calling into the contract will get opcode error such as this issue: #22

`near-sdk-js` not working on Windows

As reported by developers, near-sdk-js is not working on Windows, e.g. build contract to base64

image

We'd better make the "build" command also work well on Windows.

Testing may still be an issue since sandbox is not working on Windows so far.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.