Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Env usage localized in api.js #73

Merged
merged 6 commits into from
Jun 2, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions examples/cross-contract-call/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ class OnCall extends NearContract {

@call
set_person_on_call(accountId) {
env.log(`Trying to set ${accountId} on-call`)
near.log(`Trying to set ${accountId} on-call`)
const status = near.jsvmCall('status-message.test.near', 'get_status', [accountId])
env.log(`${accountId} status is ${status}`)
near.log(`${accountId} status is ${status}`)
if (status === 'AVAILABLE') {
this.personOnCall = accountId
env.log(`${accountId} set on-call`)
near.log(`${accountId} set on-call`)
} else {
env.log(`${accountId} can not be set on-call`)
near.log(`${accountId} can not be set on-call`)
}
}

@view
person_on_call() {
env.log(`Returning person on-call: ${this.personOnCall}`)
near.log(`Returning person on-call: ${this.personOnCall}`)
return this.personOnCall
}
}
3 changes: 0 additions & 3 deletions examples/low-level/bignum.js

This file was deleted.

41 changes: 13 additions & 28 deletions examples/low-level/counter.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,24 @@
import * as near from '../../src/api'

export function get_num() {
let hasRead = env.jsvm_storage_read("a", 0)
if (hasRead != 0)
env.jsvm_value_return(env.read_register(0))
else
env.jsvm_value_return("0")
let res = near.jsvmStorageRead("a")
return res ? res : "0"
}

export function increment() {
let n
let hasRead = env.jsvm_storage_read("a", 0)
if (hasRead != 0) {
n = env.read_register(0)
n = Number(n)+1
} else {
n = 1
}
let log_message = "Increased number to " + n
env.jsvm_storage_write("a", String(n), 0)
env.log(log_message)
let n = near.jsvmStorageRead("a")
n = n ? Number(n) + 1 : 1
near.jsvmStorageWrite("a", String(n))
near.log("Increased number to " + n)
}

export function decrement() {
let n
let hasRead = env.jsvm_storage_read("a", 0)
if (hasRead != 0) {
n = env.read_register(0)
n = Number(n)-1
} else {
n = 1
}
let log_message = "Decreased number to " + n
env.jsvm_storage_write("a", String(n), 0)
env.log(log_message)
let n = near.jsvmStorageRead("a")
n = n ? Number(n) - 1 : 1
near.jsvmStorageWrite("a", String(n))
near.log("Decreased number to " + n)
}

export function reset() {
env.jsvm_storage_write("a", "0", 0)
near.jsvmStorageWrite("a", "0")
}
3 changes: 0 additions & 3 deletions examples/low-level/debug_log.js

This file was deleted.

9 changes: 0 additions & 9 deletions examples/low-level/enclave_cross_contract.js

This file was deleted.

45 changes: 0 additions & 45 deletions examples/low-level/enclave_storage.js

This file was deleted.

17 changes: 0 additions & 17 deletions examples/low-level/hello_enclave.js

This file was deleted.

3 changes: 0 additions & 3 deletions examples/low-level/hello_near.js

This file was deleted.

53 changes: 10 additions & 43 deletions examples/low-level/nft.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,18 @@
import * as near from '../../src/api'

const MAX_SUPPLY = 10
const TOTAL_SUPPLY = 'c'

export function mint_to() {
let tokenId
let hasRead = env.jsvm_storage_read(TOTAL_SUPPLY, 0)
if (hasRead != 0) {
tokenId = Number(env.read_register(0))+1
} else {
tokenId = 1
}
let tokenId = near.jsvmStorageRead(TOTAL_SUPPLY)
tokenId = tokenId ? Number(tokenId) + 1 : 1
if (tokenId > MAX_SUPPLY) {
throw new Error('Maximum token limit reached')
}
env.jsvm_args(0)
let input = env.read_register(0)
let parsedInput = JSON.parse(input)
let owner_id = parsedInput['owner']
env.jsvm_storage_write(TOTAL_SUPPLY, tokenId.toString(), 0)
env.jsvm_storage_write('token_to_owner_' + tokenId, owner_id, 0)
env.log(`Minted NFT ${tokenId} to ${owner_id}`)
env.jsvm_value_return(tokenId.toString())
}


// What we want, a user friendly high-level API like this one:
// * class based
// * arguments and return are auto converted from env.input() and env.value_return
// * class properties are auto load and save to blockchain state
/*
@NearBindgen
class MyNFT {
constructor(maxSupply) {
this.maxSupply = maxSupply
this.totalSupply = 0
this.tokenOwner = new LookupMap('token_to_owner_')
}

mintTo(owner) {
if (this.totalSupply < this.maxSupply) {
this.totalSupply++
} else {
throw new Error('Maximum token limit reached')
}
let tokenId = this.totalSupply;
this.tokenOwner.insert(owner, tokenId);
env.log(`Minted NFT ${tokenId} to ${ownerId}`)
return tokenId
}
let input = near.jsvmArgs();
let ownerId = input['owner']
near.jsvmStorageWrite(TOTAL_SUPPLY, tokenId.toString())
near.jsvmStorageWrite('token_to_owner_' + tokenId, ownerId)
near.log(`Minted NFT ${tokenId} to ${ownerId}`)
// env.jsvm_value_return(tokenId.toString()) //TODO: Not implemented. Should we add it?
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ailisp I'm not sure what should be done with this function call. The documentation says that it is used together with env.jsvm_call(...args), but we do not have it here.

Also, something I have noticed:

export function jsvmCall(contractName, method, args) {
    env.jsvm_call(contractName, method, JSON.stringify(args), 0)
    return JSON.parse(env.read_register(0) || 'null')
}

In this function we are using env.read_register(...args), not env.jsvm_value_return().

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ailisp I'm not sure what should be done with this function call. The documentation says that it is used together with env.jsvm_call(...args), but we do not have it here.

My bad on describing the behavior. jsvm_value_return does: 1) store the return in a C static variable, so if this were called by another contract, that contract can retrieve this info. 2) plus the normal host function value_return.

This contract doesn't call other contract so there's no jsvm_call, but this contract could be called by another contract. Therefore, for any JS contract, jsvm_value_return should always be used instead of value_return.

In this function we are using env.read_register(...args), not env.jsvm_value_return().

env.jsvm_call saves the the return (if there were jsvm_value_return in the call) in both a C static variable and the given register:

// this is the env.jsvm_call
static JSValue near_jsvm_call(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
  // ...
  jsvm_call(contract_name_len, (char *)contract_name_ptr, method_name_len, (char *)method_name_ptr, arguments_len, (char *)arguments_ptr, true); // inside jsvm_call, if there's a jsvm_value_return, it saves call return to a static variable and also call host's value_return
  jsvm_call_returns(&call_ret, &ret_len, GET); // get the return from that static variable
  write_register(register_id, ret_len, (uint64_t)call_ret); // save to given register
  // ...
}

If we just want to return the value to runtime, jsvm_value_return(value) would do that. If we want to further process this value, we need to read it from register (e.g. in jsvmCall)

}
*/
4 changes: 2 additions & 2 deletions examples/status-message-collections/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ class StatusMessage extends NearContract {
@call
set_status(message) {
let account_id = near.signerAccountId()
env.log(`${account_id} set_status with message ${message}`)
near.log(`${account_id} set_status with message ${message}`)
this.records.set(account_id, message)
this.uniqueValues.set(message)
}

@view
get_status(account_id) {
env.log(`get_status for account_id ${account_id}`)
near.log(`get_status for account_id ${account_id}`)
return this.records.get(account_id)
}

Expand Down
4 changes: 2 additions & 2 deletions examples/status-message/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ class StatusMessage extends NearContract {
@call
set_status(message) {
let account_id = near.signerAccountId()
env.log(`${account_id} set_status with message ${message}`)
near.log(`${account_id} set_status with message ${message}`)
this.records[account_id] = message
}

@view
get_status(account_id) {
env.log(`get_status for account_id ${account_id}`)
near.log(`get_status for account_id ${account_id}`)
return this.records[account_id] || null
}
}
Expand Down
6 changes: 3 additions & 3 deletions examples/template/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {NearContract, NearBindgen, call, view} from 'near-sdk-js'
import {NearContract, NearBindgen, near, call, view} from 'near-sdk-js'
import {isUndefined} from 'lodash-es'

@NearBindgen
Expand All @@ -11,7 +11,7 @@ class Counter extends NearContract {
@call
increase(n=1) {
this.count += n
env.log(`Counter increased to ${this.count}`)
near.log(`Counter increased to ${this.count}`)
}

@call
Expand All @@ -23,7 +23,7 @@ class Counter extends NearContract {
} else {
this.count -= n
}
env.log(`Counter decreased to ${this.count}`)
near.log(`Counter decreased to ${this.count}`)
}

@view
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
],
"license": "(MIT AND Apache-2.0)",
"scripts": {
"test": "cd tests && yarn && yarn build && yarn test && cd .."
"test": "cd tests && yarn rebuild && yarn test && cd .."
},
"bin": {
"near-sdk": "cli/cli.js"
Expand Down
4 changes: 4 additions & 0 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const U64_MAX = 2n**64n - 1n
const EVICTED_REGISTER = U64_MAX - 1n

export function log(message) {
env.log(message)
}

export function signerAccountId() {
env.signer_account_id(0)
return env.read_register(0)
Expand Down
15 changes: 8 additions & 7 deletions src/near-contract.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import * as near from './api'

export class NearContract {
deserialize() {
let hasRead = env.jsvm_storage_read('STATE', 0)
if (hasRead != 0) {
let state = env.read_register(0)
let state = near.jsvmStorageRead('STATE');
if (state) {
Object.assign(this, JSON.parse(state))
} else
} else {
throw new Error('Contract state is empty')
}
}

serialize() {
env.jsvm_storage_write('STATE', JSON.stringify(this), 0)
near.jsvmStorageWrite('STATE', JSON.stringify(this));
}

static deserializeArgs() {
env.jsvm_args(0)
let args = env.read_register(0)
let args = near.jsvmArgs();
return JSON.parse(args || '[]')
}

Expand Down
1 change: 1 addition & 0 deletions tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"type": "module",
"scripts": {
"build": "./build.sh",
"rebuild": "rm -rf node_modules && rm -rf build && yarn && yarn build",
"test": "ava"
},
"author": "Near Inc <hello@nearprotocol.com>",
Expand Down
Loading