From 2e49127dfc0488da59a4ed1fea2c047f46ab5307 Mon Sep 17 00:00:00 2001 From: Georgi Tsonev <31661340+gtsonevv@users.noreply.github.com> Date: Tue, 1 Oct 2024 15:34:41 +0300 Subject: [PATCH 1/3] docs: Documentation improvements (#408) --- README.md | 1 + examples/README.md | 62 +++++++++++++++++++ examples/package.json | 48 +++++++------- .../{ => basic-updates}/basic-updates-base.js | 6 +- .../basic-updates-update.js | 4 +- .../src/{ => counter}/counter-lowlevel.js | 0 examples/src/{ => counter}/counter.js | 0 examples/src/{ => counter}/counter.ts | 0 examples/src/{ => counter}/log.ts | 0 .../cross-contract-call-loop.js | 0 .../cross-contract-call.js | 2 +- .../cross-contract-call.ts | 2 +- .../fungible-token-helper.ts | 0 .../fungible-token-lockable.js | 0 .../{ => fungible-token}/fungible-token.ts | 0 .../{standard-ft => fungible-token}/my-ft.ts | 0 .../my-nft.ts | 0 .../non-fungible-token-receiver.js | 0 .../non-fungible-token.js | 1 - .../test-approval-receiver.ts | 0 .../test-token-receiver.ts | 0 .../programmatic-update-after.ts | 0 .../programmatic-update-before.ts | 0 .../state-migration-new.ts | 0 .../state-migration-original.ts | 2 +- .../status-message-borsh.js | 0 .../status-message-collections.js | 0 .../status-message-deserialize-err.js | 0 .../status-message-migrate-add-field.js | 2 +- .../status-message-serialize-err.js | 0 .../{ => status-message}/status-message.js | 0 near-sdk-js@2.0.0-diff-1.0.0.md | 6 +- .../lib/fungible_token/core_impl.d.ts | 2 +- .../lib/fungible_token/core_impl.js | 2 +- .../src/fungible_token/core_impl.ts | 2 +- packages/near-sdk-js/README.md | 26 ++++---- 36 files changed, 112 insertions(+), 56 deletions(-) create mode 100644 examples/README.md rename examples/src/{ => basic-updates}/basic-updates-base.js (93%) rename examples/src/{ => basic-updates}/basic-updates-update.js (92%) rename examples/src/{ => counter}/counter-lowlevel.js (100%) rename examples/src/{ => counter}/counter.js (100%) rename examples/src/{ => counter}/counter.ts (100%) rename examples/src/{ => counter}/log.ts (100%) rename examples/src/{ => cross-contract-calls}/cross-contract-call-loop.js (100%) rename examples/src/{ => cross-contract-calls}/cross-contract-call.js (94%) rename examples/src/{ => cross-contract-calls}/cross-contract-call.ts (94%) rename examples/src/{ => fungible-token}/fungible-token-helper.ts (100%) rename examples/src/{ => fungible-token}/fungible-token-lockable.js (100%) rename examples/src/{ => fungible-token}/fungible-token.ts (100%) rename examples/src/{standard-ft => fungible-token}/my-ft.ts (100%) rename examples/src/{standard-nft => non-fungible-token}/my-nft.ts (100%) rename examples/src/{ => non-fungible-token}/non-fungible-token-receiver.js (100%) rename examples/src/{ => non-fungible-token}/non-fungible-token.js (99%) rename examples/src/{standard-nft => non-fungible-token}/test-approval-receiver.ts (100%) rename examples/src/{standard-nft => non-fungible-token}/test-token-receiver.ts (100%) rename examples/src/{ => programmatic-updates}/programmatic-update-after.ts (100%) rename examples/src/{ => programmatic-updates}/programmatic-update-before.ts (100%) rename examples/src/{ => state-migration}/state-migration-new.ts (100%) rename examples/src/{ => state-migration}/state-migration-original.ts (88%) rename examples/src/{ => status-message}/status-message-borsh.js (100%) rename examples/src/{ => status-message}/status-message-collections.js (100%) rename examples/src/{ => status-message}/status-message-deserialize-err.js (100%) rename examples/src/{ => status-message}/status-message-migrate-add-field.js (93%) rename examples/src/{ => status-message}/status-message-serialize-err.js (100%) rename examples/src/{ => status-message}/status-message.js (100%) diff --git a/README.md b/README.md index 1a5879d86..0d92f9ed0 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ See more in the [Anatomy of a Contract](https://docs.near.org/build/smart-contra ## Documentation +- [Learn how to use](https://github.com/near/create-near-app/tree/master/templates/contracts/ts) - [Learn by example with AgorApp](https://agorapp.dev/catalog/all?difficulty=&chains=near) - [Learn by example with NEAR Docs](https://docs.near.org/build/smart-contracts/quickstart) - Check our [detailed examples and tutorials](https://docs.near.org/tutorials/welcome) diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 000000000..02a6ce5f6 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,62 @@ +# Example Smart Contracts + +This directory contains example smart contracts that demonstrate various functionalities using the `near-sdk-js`. These examples are meant to serve as a starting point for developers looking to build smart contracts on the NEAR blockchain using JavaScript/TypeScript. + +## Overview + +The example smart contracts provided here showcase different use cases and features of the NEAR blockchain. Each contract is written in JavaScript/TypeScript and demonstrates best practices for developing secure, efficient, and scalable smart contracts. + +## Build and Test + +To build and test the smart contracts in this directory, follow the steps below: + +### Build + +To build all the smart contracts, run the following command in the root of the project: + +``` +pnpm build +``` + +### Test + +To run the tests for the example smart contracts, use the following command: + +``` +pnpm test +``` + +This command will execute the test suites associated with each smart contract, ensuring that they function as expected. + +## List of Example Smart Contracts + +The following smart contracts demonstrate various capabilities of the NEAR blockchain, using JavaScript/TypeScript. +Each example highlights specific features and serves as a practical guide for developers. + +**[basic-updates](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/basic-updates)**
+A simple smart contract that can make basic state updates. + +**[counter](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/counter)**
+A simple smart contract that demonstrates state management by implementing a basic counter with increment and decrement functionalities. + +**[cross-contract](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/cross-contract)**
+A smart contract that demonstrates how to perform cross-contract calls on the NEAR blockchain, including querying external contracts to manage on-chain interactions. + +**[fungible-token](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/fungible-token)**
+Example implementation of a Fungible Token (FT) contract using the [near-contract-standards](https://github.com/near/near-sdk-js/tree/develop/packages/near-contract-standards), including `storage_management`. + +**[non-fungible-token](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/non-fungible-token)**
+Example implementation of a Non-Fungible Token (NFT) contract using the [near-contract-standards](https://github.com/near/near-sdk-js/tree/develop/packages/near-contract-standards). + +**[programmatic-updates](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/programmatic-updates)**
+Contracts showcasing how contracts can evolve while maintaining certain logic from previous versions. + +**[state-migration](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/state-migration)**
+A smart contract that demonstrates how to handle state migration in a NEAR smart contract. + +**[status-message](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/status-message)**
+Smart contracts that record the status messages of the accounts that call the contracts. + +## Contributing + +If you find any issues or have suggestions for improvement, feel free to open an issue or submit a pull request. Contributions are welcome! diff --git a/examples/package.json b/examples/package.json index 17425b07a..f3e822520 100644 --- a/examples/package.json +++ b/examples/package.json @@ -6,36 +6,36 @@ "type": "module", "scripts": { "build": "run-s build:*", - "build:status-message": "near-sdk-js build src/status-message.js build/status-message.wasm", - "build:status-message-migrate-add-field": "near-sdk-js build src/status-message-migrate-add-field.js build/status-message-migrate-add-field.wasm", - "build:status-message-borsh": "near-sdk-js build src/status-message-borsh.js build/status-message-borsh.wasm", - "build:status-message-serialize-err": "near-sdk-js build src/status-message-serialize-err.js build/status-message-serialize-err.wasm", - "build:status-message-deserialize-err": "near-sdk-js build src/status-message-deserialize-err.js build/status-message-deserialize-err.wasm", + "build:status-message": "near-sdk-js build src/status-message/status-message.js build/status-message.wasm", + "build:status-message-migrate-add-field": "near-sdk-js build src/status-message/status-message-migrate-add-field.js build/status-message-migrate-add-field.wasm", + "build:status-message-borsh": "near-sdk-js build src/status-message/status-message-borsh.js build/status-message-borsh.wasm", + "build:status-message-serialize-err": "near-sdk-js build src/status-message/status-message-serialize-err.js build/status-message-serialize-err.wasm", + "build:status-message-deserialize-err": "near-sdk-js build src/status-message/status-message-deserialize-err.js build/status-message-deserialize-err.wasm", "build:clean-state": "near-sdk-js build src/clean-state.js build/clean-state.wasm", - "build:counter": "near-sdk-js build src/counter.js build/counter.wasm", - "build:counter-lowlevel": "near-sdk-js build src/counter-lowlevel.js build/counter-lowlevel.wasm", - "build:counter-ts": "near-sdk-js build src/counter.ts build/counter-ts.wasm", - "build:cross-contract-call": "near-sdk-js build src/status-message.js build/status-message.wasm && near-sdk-js build src/cross-contract-call.js build/cross-contract-call.wasm", - "build:cross-contract-call-ts": "near-sdk-js build src/status-message.js build/status-message.wasm && near-sdk-js build src/cross-contract-call.ts build/cross-contract-call-ts.wasm", - "build:cross-contract-call-loop": "near-sdk-js build src/counter.js build/counter.wasm && near-sdk-js build src/cross-contract-call-loop.js build/cross-contract-call-loop.wasm", - "build:fungible-token-lockable": "near-sdk-js build src/fungible-token-lockable.js build/fungible-token-lockable.wasm", - "build:fungible-token": "near-sdk-js build src/fungible-token.ts build/fungible-token.wasm && near-sdk-js build src/fungible-token-helper.ts build/fungible-token-helper.wasm", - "build:non-fungible-token": "near-sdk-js build src/non-fungible-token-receiver.js build/non-fungible-token-receiver.wasm && near-sdk-js build src/non-fungible-token.js build/non-fungible-token.wasm", - "build:status-message-collections": "near-sdk-js build src/status-message-collections.js build/status-message-collections.wasm", + "build:counter": "near-sdk-js build src/counter/counter.js build/counter.wasm", + "build:counter-lowlevel": "near-sdk-js build src/counter/counter-lowlevel.js build/counter-lowlevel.wasm", + "build:counter-ts": "near-sdk-js build src/counter/counter.ts build/counter-ts.wasm", + "build:cross-contract-call": "near-sdk-js build src/status-message/status-message.js build/status-message.wasm && near-sdk-js build src/cross-contract-calls/cross-contract-call.js build/cross-contract-call.wasm", + "build:cross-contract-call-ts": "near-sdk-js build src/status-message/status-message.js build/status-message.wasm && near-sdk-js build src/cross-contract-calls/cross-contract-call.ts build/cross-contract-call-ts.wasm", + "build:cross-contract-call-loop": "near-sdk-js build src/counter/counter.js build/counter.wasm && near-sdk-js build src/cross-contract-calls/cross-contract-call-loop.js build/cross-contract-call-loop.wasm", + "build:fungible-token-lockable": "near-sdk-js build src/fungible-token/fungible-token-lockable.js build/fungible-token-lockable.wasm", + "build:fungible-token": "near-sdk-js build src/fungible-token/fungible-token.ts build/fungible-token.wasm && near-sdk-js build src/fungible-token/fungible-token-helper.ts build/fungible-token-helper.wasm", + "build:non-fungible-token": "near-sdk-js build src/non-fungible-token/non-fungible-token-receiver.js build/non-fungible-token-receiver.wasm && near-sdk-js build src/non-fungible-token/non-fungible-token.js build/non-fungible-token.wasm", + "build:status-message-collections": "near-sdk-js build src/status-message/status-message-collections.js build/status-message-collections.wasm", "build:parking-lot": "near-sdk-js build src/parking-lot.ts build/parking-lot.wasm", - "build:programmatic-update": "near-sdk-js build src/programmatic-update-before.ts build/programmatic-update-before.wasm && near-sdk-js build src/programmatic-update-after.ts build/programmatic-update-after.wasm", + "build:programmatic-updates": "near-sdk-js build src/programmatic-updates/programmatic-update-before.ts build/programmatic-update-before.wasm && near-sdk-js build src/programmatic-updates/programmatic-update-after.ts build/programmatic-update-after.wasm", "build:nested-collections": "near-sdk-js build src/nested-collections.ts build/nested-collections.wasm", "build-nft": "run-s build:nft-*", - "build:nft-contract": "near-sdk-js build src/standard-nft/my-nft.ts build/my-nft.wasm", - "build:nft-receiver": "near-sdk-js build src/standard-nft/test-token-receiver.ts build/nft-receiver.wasm", - "build:nft-approval-receiver": "near-sdk-js build src/standard-nft/test-approval-receiver.ts build/nft-approval-receiver.wasm", - "build:ft": "near-sdk-js build src/standard-ft/my-ft.ts build/my-ft.wasm", + "build:nft-contract": "near-sdk-js build src/non-fungible-token/my-nft.ts build/my-nft.wasm", + "build:nft-receiver": "near-sdk-js build src/non-fungible-token/test-token-receiver.ts build/nft-receiver.wasm", + "build:nft-approval-receiver": "near-sdk-js build src/non-fungible-token/test-approval-receiver.ts build/nft-approval-receiver.wasm", + "build:ft": "near-sdk-js build src/fungible-token/my-ft.ts build/my-ft.wasm", "build:state-migration": "run-s build:state-migration:*", - "build:state-migration:original": "near-sdk-js build src/state-migration-original.ts build/state-migration-original.wasm", - "build:state-migration:new": "near-sdk-js build src/state-migration-new.ts build/state-migration-new.wasm", + "build:state-migration:original": "near-sdk-js build src/state-migration/state-migration-original.ts build/state-migration-original.wasm", + "build:state-migration:new": "near-sdk-js build src/state-migration/state-migration-new.ts build/state-migration-new.wasm", "build:status-deserialize-class": "near-sdk-js build src/status-deserialize-class.js build/status-deserialize-class.wasm", - "build:basic-updates-base": "near-sdk-js build src/basic-updates-base.js build/basic-updates-base.wasm", - "build:basic-updates-update": "near-sdk-js build src/basic-updates-update.js build/basic-updates-update.wasm", + "build:basic-updates-base": "near-sdk-js build src/basic-updates/basic-updates-base.js build/basic-updates-base.wasm", + "build:basic-updates-update": "near-sdk-js build src/basic-updates/basic-updates-update.js build/basic-updates-update.wasm", "test": "ava && pnpm test:counter-lowlevel && pnpm test:counter-ts", "test:nft": "ava __tests__/standard-nft/*", "test:ft": "ava __tests__/standard-ft/*", diff --git a/examples/src/basic-updates-base.js b/examples/src/basic-updates/basic-updates-base.js similarity index 93% rename from examples/src/basic-updates-base.js rename to examples/src/basic-updates/basic-updates-base.js index 52bb7317f..1e4173453 100644 --- a/examples/src/basic-updates-base.js +++ b/examples/src/basic-updates/basic-updates-base.js @@ -3,12 +3,8 @@ import { call, view, near, - migrate, Vector, - assert, - UnorderedMap, - LookupSet, - validateAccountId, ONE_NEAR + ONE_NEAR } from "near-sdk-js"; const POINT_ONE = ONE_NEAR / 10000n; diff --git a/examples/src/basic-updates-update.js b/examples/src/basic-updates/basic-updates-update.js similarity index 92% rename from examples/src/basic-updates-update.js rename to examples/src/basic-updates/basic-updates-update.js index d30738928..39dc7361b 100644 --- a/examples/src/basic-updates-update.js +++ b/examples/src/basic-updates/basic-updates-update.js @@ -1,6 +1,4 @@ -import {NearBindgen, call, view, near, migrate, Vector, assert, UnorderedMap, LookupSet, ONE_NEAR} from "near-sdk-js"; -import {MigrationDemo} from "../build/state-migration-new.js"; -import {Contract} from "../build/nested-collections.js"; +import {NearBindgen, call, view, near, migrate, Vector, assert, ONE_NEAR} from "near-sdk-js"; const POINT_ONE = ONE_NEAR / 10000n; diff --git a/examples/src/counter-lowlevel.js b/examples/src/counter/counter-lowlevel.js similarity index 100% rename from examples/src/counter-lowlevel.js rename to examples/src/counter/counter-lowlevel.js diff --git a/examples/src/counter.js b/examples/src/counter/counter.js similarity index 100% rename from examples/src/counter.js rename to examples/src/counter/counter.js diff --git a/examples/src/counter.ts b/examples/src/counter/counter.ts similarity index 100% rename from examples/src/counter.ts rename to examples/src/counter/counter.ts diff --git a/examples/src/log.ts b/examples/src/counter/log.ts similarity index 100% rename from examples/src/log.ts rename to examples/src/counter/log.ts diff --git a/examples/src/cross-contract-call-loop.js b/examples/src/cross-contract-calls/cross-contract-call-loop.js similarity index 100% rename from examples/src/cross-contract-call-loop.js rename to examples/src/cross-contract-calls/cross-contract-call-loop.js diff --git a/examples/src/cross-contract-call.js b/examples/src/cross-contract-calls/cross-contract-call.js similarity index 94% rename from examples/src/cross-contract-call.js rename to examples/src/cross-contract-calls/cross-contract-call.js index ca49f5078..2c761bf69 100644 --- a/examples/src/cross-contract-call.js +++ b/examples/src/cross-contract-calls/cross-contract-call.js @@ -1,4 +1,4 @@ -import { NearBindgen, call, view, initialize, near, bytes } from "near-sdk-js"; +import { NearBindgen, call, view, initialize, near } from "near-sdk-js"; @NearBindgen({ requireInit: true }) export class OnCall { diff --git a/examples/src/cross-contract-call.ts b/examples/src/cross-contract-calls/cross-contract-call.ts similarity index 94% rename from examples/src/cross-contract-call.ts rename to examples/src/cross-contract-calls/cross-contract-call.ts index 9d65938be..30fc30d53 100644 --- a/examples/src/cross-contract-call.ts +++ b/examples/src/cross-contract-calls/cross-contract-call.ts @@ -1,4 +1,4 @@ -import { NearBindgen, call, view, initialize, near, bytes } from "near-sdk-js"; +import { NearBindgen, call, view, initialize, near } from "near-sdk-js"; @NearBindgen({ requireInit: true }) export class OnCall { diff --git a/examples/src/fungible-token-helper.ts b/examples/src/fungible-token/fungible-token-helper.ts similarity index 100% rename from examples/src/fungible-token-helper.ts rename to examples/src/fungible-token/fungible-token-helper.ts diff --git a/examples/src/fungible-token-lockable.js b/examples/src/fungible-token/fungible-token-lockable.js similarity index 100% rename from examples/src/fungible-token-lockable.js rename to examples/src/fungible-token/fungible-token-lockable.js diff --git a/examples/src/fungible-token.ts b/examples/src/fungible-token/fungible-token.ts similarity index 100% rename from examples/src/fungible-token.ts rename to examples/src/fungible-token/fungible-token.ts diff --git a/examples/src/standard-ft/my-ft.ts b/examples/src/fungible-token/my-ft.ts similarity index 100% rename from examples/src/standard-ft/my-ft.ts rename to examples/src/fungible-token/my-ft.ts diff --git a/examples/src/standard-nft/my-nft.ts b/examples/src/non-fungible-token/my-nft.ts similarity index 100% rename from examples/src/standard-nft/my-nft.ts rename to examples/src/non-fungible-token/my-nft.ts diff --git a/examples/src/non-fungible-token-receiver.js b/examples/src/non-fungible-token/non-fungible-token-receiver.js similarity index 100% rename from examples/src/non-fungible-token-receiver.js rename to examples/src/non-fungible-token/non-fungible-token-receiver.js diff --git a/examples/src/non-fungible-token.js b/examples/src/non-fungible-token/non-fungible-token.js similarity index 99% rename from examples/src/non-fungible-token.js rename to examples/src/non-fungible-token/non-fungible-token.js index e18b2bd12..4028460fb 100644 --- a/examples/src/non-fungible-token.js +++ b/examples/src/non-fungible-token/non-fungible-token.js @@ -5,7 +5,6 @@ import { initialize, near, LookupMap, - bytes, assert, } from "near-sdk-js"; diff --git a/examples/src/standard-nft/test-approval-receiver.ts b/examples/src/non-fungible-token/test-approval-receiver.ts similarity index 100% rename from examples/src/standard-nft/test-approval-receiver.ts rename to examples/src/non-fungible-token/test-approval-receiver.ts diff --git a/examples/src/standard-nft/test-token-receiver.ts b/examples/src/non-fungible-token/test-token-receiver.ts similarity index 100% rename from examples/src/standard-nft/test-token-receiver.ts rename to examples/src/non-fungible-token/test-token-receiver.ts diff --git a/examples/src/programmatic-update-after.ts b/examples/src/programmatic-updates/programmatic-update-after.ts similarity index 100% rename from examples/src/programmatic-update-after.ts rename to examples/src/programmatic-updates/programmatic-update-after.ts diff --git a/examples/src/programmatic-update-before.ts b/examples/src/programmatic-updates/programmatic-update-before.ts similarity index 100% rename from examples/src/programmatic-update-before.ts rename to examples/src/programmatic-updates/programmatic-update-before.ts diff --git a/examples/src/state-migration-new.ts b/examples/src/state-migration/state-migration-new.ts similarity index 100% rename from examples/src/state-migration-new.ts rename to examples/src/state-migration/state-migration-new.ts diff --git a/examples/src/state-migration-original.ts b/examples/src/state-migration/state-migration-original.ts similarity index 88% rename from examples/src/state-migration-original.ts rename to examples/src/state-migration/state-migration-original.ts index 6ea99335a..2cc8a877e 100644 --- a/examples/src/state-migration-original.ts +++ b/examples/src/state-migration/state-migration-original.ts @@ -1,4 +1,4 @@ -import { NearBindgen, view, near, migrate, call, Vector, assert } from 'near-sdk-js' +import { NearBindgen, view, near, call, Vector } from 'near-sdk-js' import { AccountId } from 'near-sdk-js/lib/types' type Message = { diff --git a/examples/src/status-message-borsh.js b/examples/src/status-message/status-message-borsh.js similarity index 100% rename from examples/src/status-message-borsh.js rename to examples/src/status-message/status-message-borsh.js diff --git a/examples/src/status-message-collections.js b/examples/src/status-message/status-message-collections.js similarity index 100% rename from examples/src/status-message-collections.js rename to examples/src/status-message/status-message-collections.js diff --git a/examples/src/status-message-deserialize-err.js b/examples/src/status-message/status-message-deserialize-err.js similarity index 100% rename from examples/src/status-message-deserialize-err.js rename to examples/src/status-message/status-message-deserialize-err.js diff --git a/examples/src/status-message-migrate-add-field.js b/examples/src/status-message/status-message-migrate-add-field.js similarity index 93% rename from examples/src/status-message-migrate-add-field.js rename to examples/src/status-message/status-message-migrate-add-field.js index 2d3912205..7d9e225c9 100644 --- a/examples/src/status-message-migrate-add-field.js +++ b/examples/src/status-message/status-message-migrate-add-field.js @@ -1,4 +1,4 @@ -import {NearBindgen, call, view, near, migrate, Vector, assert} from "near-sdk-js"; +import {NearBindgen, call, view, near, migrate, assert} from "near-sdk-js"; class OldStatusMessage { constructor() { diff --git a/examples/src/status-message-serialize-err.js b/examples/src/status-message/status-message-serialize-err.js similarity index 100% rename from examples/src/status-message-serialize-err.js rename to examples/src/status-message/status-message-serialize-err.js diff --git a/examples/src/status-message.js b/examples/src/status-message/status-message.js similarity index 100% rename from examples/src/status-message.js rename to examples/src/status-message/status-message.js diff --git a/near-sdk-js@2.0.0-diff-1.0.0.md b/near-sdk-js@2.0.0-diff-1.0.0.md index 04767ff4a..0efe05852 100644 --- a/near-sdk-js@2.0.0-diff-1.0.0.md +++ b/near-sdk-js@2.0.0-diff-1.0.0.md @@ -1,7 +1,7 @@ # Breaking features diff from SDK 2.0.0 to 1.0.0 ## borsh data de/serializer for contract state * using for: new contracts or migrate from a borsh serialized contract -[example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message-borsh.js) +[example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message/status-message-borsh.js) ```js @NearBindgen({ serializer(statusMessage) { @@ -34,7 +34,7 @@ export class StatusMessage { ## js contract migration with data fields ### example1 * using for: contract state migrations -* [example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message-migrate-add-field.js) +* [example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message/status-message-migrate-add-field.js) ```js import {NearBindgen, call, view, near, migrate, Vector, assert} from "near-sdk-js"; @@ -65,7 +65,7 @@ export class StatusMessage { } ``` ### example2 -* another migration example can be found in [test-basic-updates.ava.js](./examples/__tests__/test-basic-updates.ava.js) with [old state contract](./examples/src/basic-updates-base.js) and new [new state contract](./examples/src/basic-updates-update.js). +* another migration example can be found in [test-basic-updates.ava.js](./examples/__tests__/test-basic-updates.ava.js) with [old state contract](./examples/src/basic-updates/basic-updates-base.js) and new [new state contract](./examples/src/basic-updates/basic-updates-update.js). with the test command in [examples directory](./examples): ```shell pnpm run test:basic-updates diff --git a/packages/near-contract-standards/lib/fungible_token/core_impl.d.ts b/packages/near-contract-standards/lib/fungible_token/core_impl.d.ts index 8c2d108d5..289770d9e 100644 --- a/packages/near-contract-standards/lib/fungible_token/core_impl.d.ts +++ b/packages/near-contract-standards/lib/fungible_token/core_impl.d.ts @@ -11,7 +11,7 @@ import { Option } from '../non_fungible_token/utils'; * - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it. * - AccountRegistrar -- interface for an account to register and unregister * - * For example usage, see examples/src/standard-ft/src/my-ft.ts + * For example usage, see examples/src/fungible-token/my-ft.ts */ export declare class FungibleToken implements FungibleTokenCore, StorageManagement, FungibleTokenResolver { accounts: LookupMap; diff --git a/packages/near-contract-standards/lib/fungible_token/core_impl.js b/packages/near-contract-standards/lib/fungible_token/core_impl.js index ff180195a..a401f1320 100644 --- a/packages/near-contract-standards/lib/fungible_token/core_impl.js +++ b/packages/near-contract-standards/lib/fungible_token/core_impl.js @@ -14,7 +14,7 @@ const ERR_TOTAL_SUPPLY_OVERFLOW = "Total supply overflow"; * - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it. * - AccountRegistrar -- interface for an account to register and unregister * - * For example usage, see examples/src/standard-ft/src/my-ft.ts + * For example usage, see examples/src/fungible-token/my-ft.ts */ export class FungibleToken { constructor() { diff --git a/packages/near-contract-standards/src/fungible_token/core_impl.ts b/packages/near-contract-standards/src/fungible_token/core_impl.ts index 5d281316a..e08206eae 100644 --- a/packages/near-contract-standards/src/fungible_token/core_impl.ts +++ b/packages/near-contract-standards/src/fungible_token/core_impl.ts @@ -32,7 +32,7 @@ const ERR_TOTAL_SUPPLY_OVERFLOW: string = "Total supply overflow"; * - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it. * - AccountRegistrar -- interface for an account to register and unregister * - * For example usage, see examples/src/standard-ft/src/my-ft.ts + * For example usage, see examples/src/fungible-token/my-ft.ts */ export class FungibleToken implements FungibleTokenCore, StorageManagement, FungibleTokenResolver { // AccountID -> Account balance. diff --git a/packages/near-sdk-js/README.md b/packages/near-sdk-js/README.md index ed12dcbf5..ed0c360d1 100644 --- a/packages/near-sdk-js/README.md +++ b/packages/near-sdk-js/README.md @@ -15,17 +15,17 @@ Learn more in our [Quick Start guide](https://docs.near.org/develop/quickstart-g There are a couple of contract examples in the project: - [Clean contract state](https://github.com/near/near-sdk-js/tree/develop/examples/src/clean-state.js) -- [Counter using low level API](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter-lowlevel.js) -- [Counter in JavaScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter.js) -- [Counter in TypeScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter.ts) -- [Doing cross contract call](https://github.com/near/near-sdk-js/tree/develop/examples/src/cross-contract-call.js) -- [Fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token.js) -- [Lockable fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token-lockable.js) -- [Non fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token.js) -- [Non fungible token receiver contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token-receiver.js) -- [Status message board](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message.js) -- [Status message board with unique messages](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message-collections.js) -- [Programmatic Update After Locking The Contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/programmatic-update.js) +- [Counter using low level API](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter-lowlevel.js) +- [Counter in JavaScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter.js) +- [Counter in TypeScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter.ts) +- [Doing cross contract call](https://github.com/near/near-sdk-js/tree/develop/examples/src//cross-contract-calls/cross-contract-call.js) +- [Fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token/fungible-token.js) +- [Lockable fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token/fungible-token-lockable.js) +- [Non fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token/non-fungible-token.js) +- [Non fungible token receiver contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token/non-fungible-token-receiver.js) +- [Status message board](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message/status-message.js) +- [Status message board with unique messages](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message/status-message-collections.js) +- [Programmatic Update After Locking The Contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/programmatic-updates/programmatic-update.js) To build all examples, run `pnpm build` in `examples/`. To test all examples, run `pnpm test`. You can also build and test one specific example with `pnpm build:` and `pnpm test:`, see `examples/package.json`. @@ -214,7 +214,7 @@ Asynchronous cross-contract calls allow parallel execution of multiple contracts ### 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). +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/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. @@ -222,7 +222,7 @@ In order to do that, your contract must be a class decorated with `@NearBindgen( 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) +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/status-message.js) `NearBindgen` decorator can accept `requireInit parameter`. From 1ec66349a7bc5c1c0f94892c6d0bdd741b455cdb Mon Sep 17 00:00:00 2001 From: Georgi Tsonev <31661340+gtsonevv@users.noreply.github.com> Date: Tue, 1 Oct 2024 15:35:48 +0300 Subject: [PATCH 2/3] docs: Enhance API Reference - Documentation improvements (#410) --- benchmark/__tests__/util.js | 2 + benchmark/src/deploy-contract.js | 5 ++ benchmark/src/expensive-calc.js | 5 ++ benchmark/src/highlevel-collection.js | 4 + benchmark/src/highlevel-minimal.js | 4 + benchmark/src/lowlevel-api.js | 8 ++ benchmark/src/lowlevel-minimal.js | 4 + .../lib/fungible_token/core.d.ts | 51 +++++++++++ .../lib/fungible_token/core_impl.js | 2 +- .../lib/fungible_token/metadata.d.ts | 3 + .../lib/fungible_token/metadata.js | 3 + .../lib/fungible_token/receiver.d.ts | 29 ++++++ .../lib/fungible_token/resolver.d.ts | 49 ++++++++++ .../lib/non_fungible_token/core/index.d.ts | 47 ++++++++++ .../lib/non_fungible_token/core/receiver.d.ts | 90 ++++++++++++++----- .../lib/non_fungible_token/core/resolver.d.ts | 40 ++++++++- .../lib/non_fungible_token/token.d.ts | 2 +- .../lib/non_fungible_token/utils.d.ts | 2 +- .../lib/non_fungible_token/utils.js | 2 +- .../src/fungible_token/core.ts | 52 +++++++++++ .../src/fungible_token/core_impl.ts | 2 +- .../src/fungible_token/metadata.ts | 3 + .../src/fungible_token/receiver.ts | 29 ++++++ .../src/fungible_token/resolver.ts | 49 ++++++++++ .../src/non_fungible_token/core/index.ts | 47 ++++++++++ .../src/non_fungible_token/core/resolver.ts | 40 ++++++++- .../src/non_fungible_token/token.ts | 2 +- .../src/non_fungible_token/utils.ts | 2 +- packages/near-sdk-js/README.md | 10 +-- packages/near-sdk-js/lib/api.d.ts | 6 +- packages/near-sdk-js/lib/api.js | 6 +- .../cli/build-tools/near-bindgen-exporter.js | 4 +- packages/near-sdk-js/lib/cli/post-install.js | 4 +- packages/near-sdk-js/lib/near-bindgen.d.ts | 2 +- packages/near-sdk-js/lib/promise.d.ts | 18 ++-- packages/near-sdk-js/lib/promise.js | 18 ++-- .../near-sdk-js/lib/types/collections.d.ts | 2 +- .../near-sdk-js/lib/types/public_key.d.ts | 2 + packages/near-sdk-js/lib/types/public_key.js | 2 + packages/near-sdk-js/src/api.ts | 6 +- .../cli/build-tools/near-bindgen-exporter.ts | 4 +- packages/near-sdk-js/src/cli/post-install.ts | 4 +- packages/near-sdk-js/src/near-bindgen.ts | 2 +- packages/near-sdk-js/src/promise.ts | 18 ++-- packages/near-sdk-js/src/types/collections.ts | 2 +- packages/near-sdk-js/src/types/public_key.ts | 2 + tests/src/alt_bn128_api.js | 2 + tests/src/bigint-serialization.ts | 8 ++ tests/src/bytes.js | 2 + tests/src/context_api.js | 2 + tests/src/date-serialization.ts | 8 ++ tests/src/decorators/payable.ts | 13 +++ tests/src/decorators/private.ts | 13 +++ tests/src/decorators/require_init_false.ts | 10 +++ tests/src/decorators/require_init_true.ts | 10 +++ tests/src/function-params.js | 8 +- tests/src/highlevel-promise.js | 3 + tests/src/log_panic_api.js | 2 + tests/src/lookup-map.js | 12 +++ tests/src/lookup-set.js | 11 +++ tests/src/math_api.js | 2 + tests/src/middlewares.ts | 5 ++ tests/src/migrate.ts | 9 ++ tests/src/model.js | 14 +++ tests/src/promise_api.js | 2 + tests/src/promise_batch_api.js | 2 + tests/src/public-key.js | 2 + tests/src/storage_api.js | 2 + tests/src/unordered-map.js | 16 ++++ tests/src/unordered-set.js | 16 ++++ tests/src/vector.js | 19 ++++ 71 files changed, 795 insertions(+), 88 deletions(-) diff --git a/benchmark/__tests__/util.js b/benchmark/__tests__/util.js index 0a3df2a06..bc2f6f6a0 100644 --- a/benchmark/__tests__/util.js +++ b/benchmark/__tests__/util.js @@ -1,3 +1,5 @@ +// Functions consumed by the benchmark contracts tests + export function formatGas(gas) { if (gas < 10 ** 12) { let tGas = gas / 10 ** 12; diff --git a/benchmark/src/deploy-contract.js b/benchmark/src/deploy-contract.js index b5a82fa39..a73f905b8 100644 --- a/benchmark/src/deploy-contract.js +++ b/benchmark/src/deploy-contract.js @@ -1,5 +1,10 @@ import { near } from "near-sdk-js"; +/** + * Used for contract deployment. More information for that + * can be found in the README.md + * - Deploy and cross contract call + */ export function deploy_contract() { let promiseId = near.promiseBatchCreate("a.caller.test.near"); near.promiseBatchActionCreateAccount(promiseId); diff --git a/benchmark/src/expensive-calc.js b/benchmark/src/expensive-calc.js index c5a18731b..75e813a48 100644 --- a/benchmark/src/expensive-calc.js +++ b/benchmark/src/expensive-calc.js @@ -1,5 +1,10 @@ import { NearBindgen, call, near } from "near-sdk-js"; +/** + * ExpensiveCalc is connected to the expensive contract. More information for that + * can be found in the README.md + * - Computational expensive contract + */ @NearBindgen({}) export class ExpensiveCalc { @call({}) diff --git a/benchmark/src/highlevel-collection.js b/benchmark/src/highlevel-collection.js index 435951e3e..a9a2e8ed1 100644 --- a/benchmark/src/highlevel-collection.js +++ b/benchmark/src/highlevel-collection.js @@ -1,5 +1,9 @@ import { NearBindgen, call, UnorderedMap } from "near-sdk-js"; +/** + * More information for that can be found in the README.md + * - Highlevel collection + */ @NearBindgen({}) export class HighlevelCollection { constructor() { diff --git a/benchmark/src/highlevel-minimal.js b/benchmark/src/highlevel-minimal.js index f540e7eef..410278793 100644 --- a/benchmark/src/highlevel-minimal.js +++ b/benchmark/src/highlevel-minimal.js @@ -1,5 +1,9 @@ import { NearBindgen, call } from "near-sdk-js"; +/** + * More information for that can be found in the README.md + * - A highlevel minimal contract (using nearbindgen) + */ @NearBindgen({}) export class HighlevelMinimal { @call({}) diff --git a/benchmark/src/lowlevel-api.js b/benchmark/src/lowlevel-api.js index b2e1ec558..db4b18bef 100644 --- a/benchmark/src/lowlevel-api.js +++ b/benchmark/src/lowlevel-api.js @@ -1,10 +1,18 @@ import { near } from "near-sdk-js"; +/** + * Helper method for the low level api. More information for that can be found in the README.md + * - Low level API + */ export function lowlevel_storage_write() { let data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); near.storageWriteRaw(data, data); } +/** + * Helper method for the low level api. More information for that can be found in the README.md + * - Low level API + */ export function lowlevel_storage_write_many() { let data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); near.storageWriteRaw(data, data); diff --git a/benchmark/src/lowlevel-minimal.js b/benchmark/src/lowlevel-minimal.js index 1611536f4..de03c685b 100644 --- a/benchmark/src/lowlevel-minimal.js +++ b/benchmark/src/lowlevel-minimal.js @@ -1,3 +1,7 @@ import { near } from "near-sdk-js"; +/** + * More information for that can be found in the README.md + * - A minimal contract + */ export function empty() {} diff --git a/packages/near-contract-standards/lib/fungible_token/core.d.ts b/packages/near-contract-standards/lib/fungible_token/core.d.ts index 84daf79e3..eb98b1929 100644 --- a/packages/near-contract-standards/lib/fungible_token/core.d.ts +++ b/packages/near-contract-standards/lib/fungible_token/core.d.ts @@ -1,5 +1,56 @@ import { AccountId, PromiseOrValue, Balance } from "near-sdk-js"; import { Option } from "../non_fungible_token/utils"; +/** + * The core methods for a basic fungible token. Extension standards may be + * added in addition to this interface. + * + * # Examples + * + * ```typescript + + * import { near, call, view, AccountId, PromiseOrValue, Balance } from "near-sdk-js"; + * import { Option } from "../non_fungible_token/utils"; + * import { FungibleTokenCore, FungibleToken } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({}) + * ft_transfer({ receiver_id, amount, memo }: { + * receiver_id: AccountId, + * amount: Balance, + * memo?: String + * }): void { + * this.token.ft_transfer({ receiver_id, amount, memo }); + * } + * + * @call({}) + * ft_transfer_call({ receiver_id, amount, memo, msg }: { + * receiver_id: AccountId, + * amount: Balance, + * memo?: Option, + * msg: String + * }): PromiseOrValue { + * return this.token.ft_transfer_call({ receiver_id, amount, memo, msg }); + * } + * + * @view({}) + * ft_total_supply(): Balance { + * return this.token.ft_total_supply(); + * } + * + * @view({}) + * ft_balance_of({ account_id }: { account_id: AccountId }): Balance { + * return this.token.ft_balance_of({ account_id }); + * } + * } + * ``` + */ export interface FungibleTokenCore { /** * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id`. diff --git a/packages/near-contract-standards/lib/fungible_token/core_impl.js b/packages/near-contract-standards/lib/fungible_token/core_impl.js index a401f1320..7a60f7c69 100644 --- a/packages/near-contract-standards/lib/fungible_token/core_impl.js +++ b/packages/near-contract-standards/lib/fungible_token/core_impl.js @@ -84,7 +84,7 @@ export class FungibleToken { // Get the unused amount from the `ft_on_transfer` call result. let unused_amount; try { - const promise_result = near.promiseResult(0).replace(/"*/g, ''); //TODO: why promiseResult returnes result with brackets? + const promise_result = near.promiseResult(0).replace(/"*/g, ''); //TODO: why promiseResult returns result with brackets? unused_amount = this.bigIntMin(amount, BigInt(promise_result)); } catch (e) { diff --git a/packages/near-contract-standards/lib/fungible_token/metadata.d.ts b/packages/near-contract-standards/lib/fungible_token/metadata.d.ts index 5db30b4cd..bb9c21af5 100644 --- a/packages/near-contract-standards/lib/fungible_token/metadata.d.ts +++ b/packages/near-contract-standards/lib/fungible_token/metadata.d.ts @@ -1,4 +1,7 @@ import { Option } from "../non_fungible_token/utils"; +/** + * Return metadata for the token, up to contract to implement. + */ export declare class FungibleTokenMetadata { spec: string; name: string; diff --git a/packages/near-contract-standards/lib/fungible_token/metadata.js b/packages/near-contract-standards/lib/fungible_token/metadata.js index 82be61985..ecd8c69f8 100644 --- a/packages/near-contract-standards/lib/fungible_token/metadata.js +++ b/packages/near-contract-standards/lib/fungible_token/metadata.js @@ -1,5 +1,8 @@ import { assert, } from "near-sdk-js"; const FT_METADATA_SPEC = "ft-1.0.0"; +/** + * Return metadata for the token, up to contract to implement. + */ export class FungibleTokenMetadata { constructor(spec, name, symbol, icon, referance, referance_hash, decimals) { this.spec = spec; diff --git a/packages/near-contract-standards/lib/fungible_token/receiver.d.ts b/packages/near-contract-standards/lib/fungible_token/receiver.d.ts index d63dfb404..a35770c4c 100644 --- a/packages/near-contract-standards/lib/fungible_token/receiver.d.ts +++ b/packages/near-contract-standards/lib/fungible_token/receiver.d.ts @@ -1,4 +1,33 @@ import { AccountId, PromiseOrValue } from "near-sdk-js"; +/** + * Provides token transfer resolve functionality. + * + * # Examples + * + * ```typescript + + * import { AccountId, PromiseOrValue } from "near-sdk-js"; + * import { FungibleTokenCore, FungibleToken, FungibleTokenReceiver } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore, FungibleTokenReceiver { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({}) + * ft_on_transfer({ sender_id, amount, msg }: { + * sender_id: AccountId; + * amount: number; + * msg: String; + * }): PromiseOrValue { + * return this.token.ft_on_transfer({ sender_id, amount, msg }); + * }; + * } + * ``` + */ export interface FungibleTokenReceiver { /** * Called by fungible token contract after `ft_transfer_call` was initiated by diff --git a/packages/near-contract-standards/lib/fungible_token/resolver.d.ts b/packages/near-contract-standards/lib/fungible_token/resolver.d.ts index f8d5255d9..9c2424f11 100644 --- a/packages/near-contract-standards/lib/fungible_token/resolver.d.ts +++ b/packages/near-contract-standards/lib/fungible_token/resolver.d.ts @@ -1,5 +1,54 @@ import { AccountId, Balance } from "near-sdk-js"; +/** + * Provides token transfer resolve functionality. + * + * # Examples + * + * ```typescript + * import { AccountId, Balance, call } from "near-sdk-js"; + * import { + * FungibleTokenCore, + * FungibleTokenResolver, + * FungibleToken, + * } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore, FungibleTokenResolver { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({ privateFunction: true }) + * ft_resolve_transfer({ + * sender_id, + * receiver_id, + * amount, + * }: { + * sender_id: AccountId, + * receiver_id: AccountId, + * amount: Balance + * }): Balance { + * const { used_amount, burned_amount } = this.token.internal_ft_resolve_transfer(sender_id, receiver_id, amount); + * if (burned_amount > 0) { + * console.log(`Account @${sender_id} burned ${burned_amount}`); + * } + * return used_amount; + * } + * } + * ``` + */ export interface FungibleTokenResolver { + /** + * Resolves the transfer of tokens between `sender_id` and `receiver_id`. + * + * @param sender_id - The account ID of the sender. + * @param receiver_id - The account ID of the receiver. + * @param amount - The amount of tokens to resolve in a decimal string representation. + * + * @returns The amount of tokens used during the transfer, returning the balance as a `Balance`. + */ ft_resolve_transfer({ sender_id, receiver_id, amount, }: { sender_id: AccountId; receiver_id: AccountId; diff --git a/packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts b/packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts index e3158367d..41fcb1447 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts +++ b/packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts @@ -8,6 +8,53 @@ import { Option } from "../utils"; * understand how the cross-contract call work. * * [core non-fungible token standard]: + * + * # Examples + * + * ```typescript + + * import { AccountId } from "near-sdk-js"; + * import { Option } from "../non_fungible_token/utils"; + * import { Token, TokenId } from "../token"; + * import { NonFungibleTokenCore, NonFungibleToken } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements NonFungibleTokenCore { + * private token: NonFungibleToken; + * + * constructor() { + * this.tokens = new NonFungibleToken(); + * } + * + * @call({}) + * nft_transfer({ receiver_id, token_id, approval_id, memo }: { + receiver_id: AccountId; + token_id: TokenId; + approval_id?: bigint; + memo?: string; + }): any { + * this.tokens.nft_transfer({ receiver_id, token_id, approval_id, memo }); + * } + * + * @call({}) + * nft_transfer_call({ receiver_id, token_id, approval_id, memo }: { + receiver_id: AccountId; + token_id: TokenId; + approval_id?: bigint; + memo?: string; + msg: string; + }): any { + * return this.tokens.nft_transfer_call({ receiver_id, token_id, approval_id, memo }); + * } + * + * @view({}) + * nft_token({ token_id }: { + token_id: TokenId; + }): Option { + return this.tokens.nft_token({ token_id }); + }; + * } + * ``` */ export interface NonFungibleTokenCore { /** Simple transfer. Transfer a given `token_id` from current owner to diff --git a/packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts b/packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts index 44048efc0..17f780aef 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts +++ b/packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts @@ -1,27 +1,71 @@ import { AccountId, PromiseOrValue } from "near-sdk-js"; import { TokenId } from "../token"; -/** Used when an NFT is transferred using `nft_transfer_call`. This interface is implemented on the receiving contract, not on the NFT contract. */ +/** Used when an NFT is transferred using `nft_transfer_call`. This interface is implemented on the receiving contract, not on the NFT contract. + * + * # Examples + * + * ```typescript + + * import { AccountId, PromiseOrValue } from "near-sdk-js"; + * import { TokenId } from "../token"; + * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenReceiver } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements NonFungibleTokenCore, NonFungibleTokenReceiver { + * private token: NonFungibleToken; + * + * constructor() { + * this.tokens = new NonFungibleToken(); + * } + * + * @call({}) + * nft_on_transfer({ + sender_id, + previous_owner_id, + token_id, + msg, + }: { + sender_id: AccountId; + previous_owner_id: AccountId; + token_id: TokenId; + msg: string; + }): PromiseOrValue { + return this.tokens.nft_on_transfer({ + sender_id, + previous_owner_id, + token_id, + msg + }) + } + * } + * ``` +*/ export interface NonFungibleTokenReceiver { - /** Take some action after receiving a non-fungible token - * - * Requirements: - * - Contract MUST restrict calls to this function to a set of whitelisted NFT - * contracts - * - * @param sender_id - The sender of `nft_transfer_call` - * @param previous_owner_id - The account that owned the NFT prior to it being - * transferred to this contract, which can differ from `sender_id` if using - * Approval Management extension - * @param token_id - The `token_id` argument given to `nft_transfer_call` - * @param msg - Information necessary for this contract to know how to process the - * request. This may include method names and/or arguments. - * - * @returns true if token should be returned to `sender_id` - */ - nft_on_transfer({ sender_id, previous_owner_id, token_id, msg, }: { - sender_id: AccountId; - previous_owner_id: AccountId; - token_id: TokenId; - msg: string; - }): PromiseOrValue; + /** Take some action after receiving a non-fungible token + * + * Requirements: + * - Contract MUST restrict calls to this function to a set of whitelisted NFT + * contracts + * + * @param sender_id - The sender of `nft_transfer_call` + * @param previous_owner_id - The account that owned the NFT prior to it being + * transferred to this contract, which can differ from `sender_id` if using + * Approval Management extension + * @param token_id - The `token_id` argument given to `nft_transfer_call` + * @param msg - Information necessary for this contract to know how to process the + * request. This may include method names and/or arguments. + * + * @returns true if token should be returned to `sender_id` + */ + nft_on_transfer({ + sender_id, + previous_owner_id, + token_id, + msg, + }: { + sender_id: AccountId; + previous_owner_id: AccountId; + token_id: TokenId; + msg: string; + }): PromiseOrValue; } diff --git a/packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts b/packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts index 7dd48c2bc..c34f4d68e 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts +++ b/packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts @@ -1,6 +1,42 @@ import { AccountId } from "near-sdk-js"; import { TokenId } from "../token"; -/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract. */ +/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract. + * + * # Examples + * + * ```typescript + + * import { AccountId } from "near-sdk-js"; + * import { TokenId } from "../token"; + * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenResolver } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements NonFungibleTokenCore, NonFungibleTokenResolver { + * private token: NonFungibleToken; + * + * constructor() { + * this.tokens = new NonFungibleToken(); + * } + * + * @call({}) + * nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: { + previous_owner_id: AccountId; + receiver_id: AccountId; + token_id: TokenId; + approved_account_ids?: { + [approval: AccountId]: bigint; + }; + }): boolean; { + return this.tokens.nft_resolve_transfer({ + previous_owner_id, + receiver_id, + token_id, + approved_account_ids, + }); + } + * } + * ``` +*/ export interface NonFungibleTokenResolver { /** Finalize an `nft_transfer_call` chain of cross-contract calls. * @@ -22,7 +58,7 @@ export interface NonFungibleTokenResolver { * @param previous_owner_id - The owner prior to the call to `nft_transfer_call` * @param receiver_id - The `receiver_id` argument given to `nft_transfer_call` * @param token_id - The `token_id` argument given to `ft_transfer_call` - * @param approvals - If using Approval Management, contract MUST provide + * @param approved_account_ids - If using Approval Management, contract MUST provide * set of original approved accounts in this argument, and restore these * approved accounts in case of revert. * diff --git a/packages/near-contract-standards/lib/non_fungible_token/token.d.ts b/packages/near-contract-standards/lib/non_fungible_token/token.d.ts index cbe49f357..29f097cf9 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/token.d.ts +++ b/packages/near-contract-standards/lib/non_fungible_token/token.d.ts @@ -1,6 +1,6 @@ import { TokenMetadata } from "./metadata"; import { AccountId } from "near-sdk-js"; -/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use autoincrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */ +/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use auto incrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */ export declare type TokenId = string; /** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, as they are frequently used in modern NFTs. */ export declare class Token { diff --git a/packages/near-contract-standards/lib/non_fungible_token/utils.d.ts b/packages/near-contract-standards/lib/non_fungible_token/utils.d.ts index 61d03908e..506baf870 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/utils.d.ts +++ b/packages/near-contract-standards/lib/non_fungible_token/utils.d.ts @@ -1,7 +1,7 @@ import { AccountId } from "near-sdk-js"; export declare function refund_storage_deposit(account_id: AccountId, storage_released: number): void; export declare function refund_deposit_to_account(storage_used: bigint, account_id: AccountId): void; -/** Assumes that the precedecessor will be refunded */ +/** Assumes that the predecessor will be refunded */ export declare function refund_deposit(storage_used: bigint): void; export declare function hash_account_id(account_id: AccountId): Uint8Array; /** Assert that at least 1 yoctoNEAR was attached. */ diff --git a/packages/near-contract-standards/lib/non_fungible_token/utils.js b/packages/near-contract-standards/lib/non_fungible_token/utils.js index a4a2ef0f7..22779d885 100644 --- a/packages/near-contract-standards/lib/non_fungible_token/utils.js +++ b/packages/near-contract-standards/lib/non_fungible_token/utils.js @@ -15,7 +15,7 @@ export function refund_deposit_to_account(storage_used, account_id) { near.promiseReturn(promise_id); } } -/** Assumes that the precedecessor will be refunded */ +/** Assumes that the predecessor will be refunded */ export function refund_deposit(storage_used) { refund_deposit_to_account(storage_used, near.predecessorAccountId()); } diff --git a/packages/near-contract-standards/src/fungible_token/core.ts b/packages/near-contract-standards/src/fungible_token/core.ts index f18152ab0..a179a8473 100644 --- a/packages/near-contract-standards/src/fungible_token/core.ts +++ b/packages/near-contract-standards/src/fungible_token/core.ts @@ -1,5 +1,57 @@ import { AccountId, PromiseOrValue, Balance } from "near-sdk-js" import { Option } from "../non_fungible_token/utils" + +/** + * The core methods for a basic fungible token. Extension standards may be + * added in addition to this interface. + * + * # Examples + * + * ```typescript + + * import { near, call, view, AccountId, PromiseOrValue, Balance } from "near-sdk-js"; + * import { Option } from "../non_fungible_token/utils"; + * import { FungibleTokenCore, FungibleToken } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({}) + * ft_transfer({ receiver_id, amount, memo }: { + * receiver_id: AccountId, + * amount: Balance, + * memo?: String + * }): void { + * this.token.ft_transfer({ receiver_id, amount, memo }); + * } + * + * @call({}) + * ft_transfer_call({ receiver_id, amount, memo, msg }: { + * receiver_id: AccountId, + * amount: Balance, + * memo?: Option, + * msg: String + * }): PromiseOrValue { + * return this.token.ft_transfer_call({ receiver_id, amount, memo, msg }); + * } + * + * @view({}) + * ft_total_supply(): Balance { + * return this.token.ft_total_supply(); + * } + * + * @view({}) + * ft_balance_of({ account_id }: { account_id: AccountId }): Balance { + * return this.token.ft_balance_of({ account_id }); + * } + * } + * ``` + */ export interface FungibleTokenCore { /** * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id`. diff --git a/packages/near-contract-standards/src/fungible_token/core_impl.ts b/packages/near-contract-standards/src/fungible_token/core_impl.ts index e08206eae..1be080e00 100644 --- a/packages/near-contract-standards/src/fungible_token/core_impl.ts +++ b/packages/near-contract-standards/src/fungible_token/core_impl.ts @@ -123,7 +123,7 @@ export class FungibleToken implements FungibleTokenCore, StorageManagement, Fung // Get the unused amount from the `ft_on_transfer` call result. let unused_amount: Balance; try { - const promise_result = near.promiseResult(0).replace(/"*/g, ''); //TODO: why promiseResult returnes result with brackets? + const promise_result = near.promiseResult(0).replace(/"*/g, ''); //TODO: why promiseResult returns result with brackets? unused_amount = this.bigIntMin(amount, BigInt(promise_result)); } catch (e) { if (e.message.includes('Failed')) { diff --git a/packages/near-contract-standards/src/fungible_token/metadata.ts b/packages/near-contract-standards/src/fungible_token/metadata.ts index 81380dc86..da89c7cba 100644 --- a/packages/near-contract-standards/src/fungible_token/metadata.ts +++ b/packages/near-contract-standards/src/fungible_token/metadata.ts @@ -6,6 +6,9 @@ import { Option } from "../non_fungible_token/utils"; const FT_METADATA_SPEC: string = "ft-1.0.0"; +/** + * Return metadata for the token, up to contract to implement. + */ export class FungibleTokenMetadata { spec: string; name: string; diff --git a/packages/near-contract-standards/src/fungible_token/receiver.ts b/packages/near-contract-standards/src/fungible_token/receiver.ts index 61f022e20..963b97d7b 100644 --- a/packages/near-contract-standards/src/fungible_token/receiver.ts +++ b/packages/near-contract-standards/src/fungible_token/receiver.ts @@ -1,5 +1,34 @@ import { AccountId, PromiseOrValue } from "near-sdk-js"; +/** + * Provides token transfer resolve functionality. + * + * # Examples + * + * ```typescript + + * import { AccountId, PromiseOrValue } from "near-sdk-js"; + * import { FungibleTokenCore, FungibleToken, FungibleTokenReceiver } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore, FungibleTokenReceiver { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({}) + * ft_on_transfer({ sender_id, amount, msg }: { + * sender_id: AccountId; + * amount: number; + * msg: String; + * }): PromiseOrValue { + * return this.token.ft_on_transfer({ sender_id, amount, msg }); + * }; + * } + * ``` + */ export interface FungibleTokenReceiver { /** * Called by fungible token contract after `ft_transfer_call` was initiated by diff --git a/packages/near-contract-standards/src/fungible_token/resolver.ts b/packages/near-contract-standards/src/fungible_token/resolver.ts index 6f2d0a12e..4a41a3d1f 100644 --- a/packages/near-contract-standards/src/fungible_token/resolver.ts +++ b/packages/near-contract-standards/src/fungible_token/resolver.ts @@ -1,6 +1,55 @@ import { AccountId, Balance } from "near-sdk-js"; +/** + * Provides token transfer resolve functionality. + * + * # Examples + * + * ```typescript + * import { AccountId, Balance, call } from "near-sdk-js"; + * import { + * FungibleTokenCore, + * FungibleTokenResolver, + * FungibleToken, + * } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements FungibleTokenCore, FungibleTokenResolver { + * private token: FungibleToken; + * + * constructor() { + * this.token = new FungibleToken(); + * } + * + * @call({ privateFunction: true }) + * ft_resolve_transfer({ + * sender_id, + * receiver_id, + * amount, + * }: { + * sender_id: AccountId, + * receiver_id: AccountId, + * amount: Balance + * }): Balance { + * const { used_amount, burned_amount } = this.token.internal_ft_resolve_transfer(sender_id, receiver_id, amount); + * if (burned_amount > 0) { + * console.log(`Account @${sender_id} burned ${burned_amount}`); + * } + * return used_amount; + * } + * } + * ``` + */ export interface FungibleTokenResolver { + /** + * Resolves the transfer of tokens between `sender_id` and `receiver_id`. + * + * @param sender_id - The account ID of the sender. + * @param receiver_id - The account ID of the receiver. + * @param amount - The amount of tokens to resolve in a decimal string representation. + * + * @returns The amount of tokens used during the transfer, returning the balance as a `Balance`. + */ ft_resolve_transfer({ sender_id, receiver_id, diff --git a/packages/near-contract-standards/src/non_fungible_token/core/index.ts b/packages/near-contract-standards/src/non_fungible_token/core/index.ts index 624be9f97..f4ad83fb3 100644 --- a/packages/near-contract-standards/src/non_fungible_token/core/index.ts +++ b/packages/near-contract-standards/src/non_fungible_token/core/index.ts @@ -9,6 +9,53 @@ import { Option } from "../utils"; * understand how the cross-contract call work. * * [core non-fungible token standard]: + * + * # Examples + * + * ```typescript + + * import { AccountId } from "near-sdk-js"; + * import { Option } from "../non_fungible_token/utils"; + * import { Token, TokenId } from "../token"; + * import { NonFungibleTokenCore, NonFungibleToken } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements NonFungibleTokenCore { + * private token: NonFungibleToken; + * + * constructor() { + * this.tokens = new NonFungibleToken(); + * } + * + * @call({}) + * nft_transfer({ receiver_id, token_id, approval_id, memo }: { + receiver_id: AccountId; + token_id: TokenId; + approval_id?: bigint; + memo?: string; + }): any { + * this.tokens.nft_transfer({ receiver_id, token_id, approval_id, memo }); + * } + * + * @call({}) + * nft_transfer_call({ receiver_id, token_id, approval_id, memo }: { + receiver_id: AccountId; + token_id: TokenId; + approval_id?: bigint; + memo?: string; + msg: string; + }): any { + * return this.tokens.nft_transfer_call({ receiver_id, token_id, approval_id, memo }); + * } + * + * @view({}) + * nft_token({ token_id }: { + token_id: TokenId; + }): Option { + return this.tokens.nft_token({ token_id }); + }; + * } + * ``` */ export interface NonFungibleTokenCore { /** Simple transfer. Transfer a given `token_id` from current owner to diff --git a/packages/near-contract-standards/src/non_fungible_token/core/resolver.ts b/packages/near-contract-standards/src/non_fungible_token/core/resolver.ts index f073653c3..38a425cd1 100644 --- a/packages/near-contract-standards/src/non_fungible_token/core/resolver.ts +++ b/packages/near-contract-standards/src/non_fungible_token/core/resolver.ts @@ -1,7 +1,43 @@ import { AccountId } from "near-sdk-js"; import { TokenId } from "../token"; -/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract. */ +/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract. + * + * # Examples + * + * ```typescript + + * import { AccountId } from "near-sdk-js"; + * import { TokenId } from "../token"; + * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenResolver } from "near-contract-standards/lib" + * + * @NearBindgen({ requireInit: false }) + * export class Contract implements NonFungibleTokenCore, NonFungibleTokenResolver { + * private token: NonFungibleToken; + * + * constructor() { + * this.tokens = new NonFungibleToken(); + * } + * + * @call({}) + * nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: { + previous_owner_id: AccountId; + receiver_id: AccountId; + token_id: TokenId; + approved_account_ids?: { + [approval: AccountId]: bigint; + }; + }): boolean; { + return this.tokens.nft_resolve_transfer({ + previous_owner_id, + receiver_id, + token_id, + approved_account_ids, + }); + } + * } + * ``` +*/ export interface NonFungibleTokenResolver { /** Finalize an `nft_transfer_call` chain of cross-contract calls. * @@ -23,7 +59,7 @@ export interface NonFungibleTokenResolver { * @param previous_owner_id - The owner prior to the call to `nft_transfer_call` * @param receiver_id - The `receiver_id` argument given to `nft_transfer_call` * @param token_id - The `token_id` argument given to `ft_transfer_call` - * @param approvals - If using Approval Management, contract MUST provide + * @param approved_account_ids - If using Approval Management, contract MUST provide * set of original approved accounts in this argument, and restore these * approved accounts in case of revert. * diff --git a/packages/near-contract-standards/src/non_fungible_token/token.ts b/packages/near-contract-standards/src/non_fungible_token/token.ts index 09f5d002f..567aa4858 100644 --- a/packages/near-contract-standards/src/non_fungible_token/token.ts +++ b/packages/near-contract-standards/src/non_fungible_token/token.ts @@ -1,7 +1,7 @@ import { TokenMetadata } from "./metadata"; import { AccountId } from "near-sdk-js"; -/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use autoincrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */ +/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use auto incrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */ export type TokenId = string; /** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, as they are frequently used in modern NFTs. */ diff --git a/packages/near-contract-standards/src/non_fungible_token/utils.ts b/packages/near-contract-standards/src/non_fungible_token/utils.ts index 97a4889ff..4fa1c7046 100644 --- a/packages/near-contract-standards/src/non_fungible_token/utils.ts +++ b/packages/near-contract-standards/src/non_fungible_token/utils.ts @@ -32,7 +32,7 @@ export function refund_deposit_to_account( } } -/** Assumes that the precedecessor will be refunded */ +/** Assumes that the predecessor will be refunded */ export function refund_deposit(storage_used: bigint): void { refund_deposit_to_account(storage_used, near.predecessorAccountId()); } diff --git a/packages/near-sdk-js/README.md b/packages/near-sdk-js/README.md index ed0c360d1..fe04545b4 100644 --- a/packages/near-sdk-js/README.md +++ b/packages/near-sdk-js/README.md @@ -61,7 +61,7 @@ All NEAR blockchain provided functionality (host functions) are defined in `src/ ```js import { near } from "near-sdk-js"; -// near.. e.g.: +// near.. e.g.: let signer = near.signerAccountId(); ``` @@ -70,7 +70,7 @@ let signer = near.signerAccountId(); 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. -- For those API that takes or returns raw bytes, it is a JavaScript `Uint8Array`. You can use standard `Uint8Array` methods on it or decode it to string with `decode` or `str`. The differece between `decode` and `str` is: `decode` decode the array as UTF-8 sequence. `str` simply converts each Uint8 to one char with that char code. +- For those API that takes or returns raw bytes, it is a JavaScript `Uint8Array`. You can use standard `Uint8Array` methods on it or decode it to string with `decode` or `str`. The difference between `decode` and `str` is: `decode` decode the array as UTF-8 sequence. `str` simply converts each Uint8 to one char with that char code. ### Context API @@ -490,7 +490,7 @@ someMethod() { } ``` -### Highlevel Promise APIs +### High level 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. @@ -552,7 +552,7 @@ 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 string and bigint. +NEAR-SDK-JS also includes type definitions 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 string and bigint. #### Public Key @@ -607,5 +607,5 @@ In order to use WSL2, follow the next steps: In case of any issues of setting up WSL2 make sure that: - Your Windows OS is up to date -- Virtualisation is turned on in BIOS +- Virtualization is turned on in BIOS - `Windows Subsystem for Linux` and `Virtual Machine Platform` are turned on in `Windows Features` (Start -> Search -> Turn Windows Feature On or Off) diff --git a/packages/near-sdk-js/lib/api.d.ts b/packages/near-sdk-js/lib/api.d.ts index 595388fbc..5a5f9274a 100644 --- a/packages/near-sdk-js/lib/api.d.ts +++ b/packages/near-sdk-js/lib/api.d.ts @@ -75,13 +75,13 @@ export declare function storageReadRaw(key: Uint8Array): Uint8Array | null; */ export declare function storageRead(key: string): string | null; /** - * Checks for the existance of a value under the provided key in NEAR storage. + * Checks for the existence of a value under the provided key in NEAR storage. * * @param key - The key to check for in storage. */ export declare function storageHasKeyRaw(key: Uint8Array): boolean; /** - * Checks for the existance of a value under the provided utf-8 string key in NEAR storage. + * Checks for the existence of a value under the provided utf-8 string key in NEAR storage. * * @param key - The utf-8 string key to check for in storage. */ @@ -404,7 +404,7 @@ export declare function validatorTotalStake(): bigint; * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \sum_i * mul_i g_{1 i} should be equal result. * - * @param value - equence of (g1:G1, fr:Fr), where + * @param value - sequence of (g1:G1, fr:Fr), where * G1 is point (x:Fq, y:Fq) on alt_bn128, * alt_bn128 is Y^2 = X^3 + 3 curve over Fq. * `value` is encoded as packed, little-endian diff --git a/packages/near-sdk-js/lib/api.js b/packages/near-sdk-js/lib/api.js index db5127114..49f915dcf 100644 --- a/packages/near-sdk-js/lib/api.js +++ b/packages/near-sdk-js/lib/api.js @@ -130,7 +130,7 @@ export function storageRead(key) { return null; } /** - * Checks for the existance of a value under the provided key in NEAR storage. + * Checks for the existence of a value under the provided key in NEAR storage. * * @param key - The key to check for in storage. */ @@ -138,7 +138,7 @@ export function storageHasKeyRaw(key) { return env.storage_has_key(key) === 1n; } /** - * Checks for the existance of a value under the provided utf-8 string key in NEAR storage. + * Checks for the existence of a value under the provided utf-8 string key in NEAR storage. * * @param key - The utf-8 string key to check for in storage. */ @@ -572,7 +572,7 @@ export function validatorTotalStake() { * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \sum_i * mul_i g_{1 i} should be equal result. * - * @param value - equence of (g1:G1, fr:Fr), where + * @param value - sequence of (g1:G1, fr:Fr), where * G1 is point (x:Fq, y:Fq) on alt_bn128, * alt_bn128 is Y^2 = X^3 + 3 curve over Fq. * `value` is encoded as packed, little-endian diff --git a/packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js b/packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js index 6cd1d9975..0cbf9308e 100644 --- a/packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js +++ b/packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js @@ -124,7 +124,7 @@ function collectArguments(classId) { ]); } /** - * A helper function that inserts a contract method call expresion. + * A helper function that inserts a contract method call expression. * It calls the appropriate contract method and passes the collected _\_args_. * * ```typescript @@ -178,7 +178,7 @@ function executePromise(classId) { ])))); } /** - * A helper function that inserts the overriden function declaration into the class. + * A helper function that inserts the overridden function declaration into the class. * * @param classId - The class ID of the class being extended. * @param methodName - The name of the method being called. diff --git a/packages/near-sdk-js/lib/cli/post-install.js b/packages/near-sdk-js/lib/cli/post-install.js index 700fee80a..1094f9418 100644 --- a/packages/near-sdk-js/lib/cli/post-install.js +++ b/packages/near-sdk-js/lib/cli/post-install.js @@ -13,8 +13,8 @@ process.chdir(DEPS); const PLATFORM = os.platform(); const ARCH = os.arch(); console.log(`Current platform: ${PLATFORM}, current architecture: ${ARCH}`); -const SUPPORTED_PLATFORMS = ["linux", "darwin"]; // Unsaported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android' -const SUPPORTED_ARCH = ["x64", "arm64"]; // Unsaported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' +const SUPPORTED_PLATFORMS = ["linux", "darwin"]; // Unsupported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android' +const SUPPORTED_ARCH = ["x64", "arm64"]; // Unsupported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' if (!SUPPORTED_PLATFORMS.includes(PLATFORM)) { console.error(`Platform ${PLATFORM} is not supported at the moment`); process.exit(1); diff --git a/packages/near-sdk-js/lib/near-bindgen.d.ts b/packages/near-sdk-js/lib/near-bindgen.d.ts index c17aaca60..af350c64b 100644 --- a/packages/near-sdk-js/lib/near-bindgen.d.ts +++ b/packages/near-sdk-js/lib/near-bindgen.d.ts @@ -20,7 +20,7 @@ export declare function initialize(_empty: EmptyParameterObject): DecoratorFunct export declare function view(_empty: EmptyParameterObject): DecoratorFunction; /** * Tells the SDK to expose this function as a call function. - * Adds the neccessary checks if the function is private or payable. + * Adds the necessary checks if the function is private or payable. * * @param options - Options to configure the function behaviour. * @param options.privateFunction - Whether the function can be called by other contracts. diff --git a/packages/near-sdk-js/lib/promise.d.ts b/packages/near-sdk-js/lib/promise.d.ts index d5f4186ff..b9b735ccb 100644 --- a/packages/near-sdk-js/lib/promise.d.ts +++ b/packages/near-sdk-js/lib/promise.d.ts @@ -121,7 +121,7 @@ export declare class FunctionCallWeightRaw extends PromiseAction { export declare class Transfer extends PromiseAction { amount: Balance; /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ constructor(amount: Balance); add(promiseIndex: PromiseIndex): void; @@ -135,7 +135,7 @@ export declare class Stake extends PromiseAction { amount: Balance; publicKey: PublicKey; /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ constructor(amount: Balance, publicKey: PublicKey); @@ -171,7 +171,7 @@ export declare class AddAccessKey extends PromiseAction { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ constructor(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string, nonce: Nonce); @@ -198,7 +198,7 @@ export declare class DeleteKey extends PromiseAction { export declare class DeleteAccount extends PromiseAction { beneficiaryId: AccountId; /** - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ constructor(beneficiaryId: AccountId); add(promiseIndex: PromiseIndex): void; @@ -288,13 +288,13 @@ export declare class NearPromise { /** * Creates a transfer promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ transfer(amount: Balance): NearPromise; /** * Creates a stake promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ stake(amount: Balance, publicKey: PublicKey): NearPromise; @@ -320,7 +320,7 @@ export declare class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. */ addAccessKey(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string): NearPromise; /** @@ -330,7 +330,7 @@ export declare class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ addAccessKeyWithNonce(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string, nonce: Nonce): NearPromise; @@ -343,7 +343,7 @@ export declare class NearPromise { /** * Creates a delete account promise action and adds it to the current promise. * - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ deleteAccount(beneficiaryId: AccountId): NearPromise; /** diff --git a/packages/near-sdk-js/lib/promise.js b/packages/near-sdk-js/lib/promise.js index b29c840df..e0528352d 100644 --- a/packages/near-sdk-js/lib/promise.js +++ b/packages/near-sdk-js/lib/promise.js @@ -135,7 +135,7 @@ export class FunctionCallWeightRaw extends PromiseAction { */ export class Transfer extends PromiseAction { /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ constructor(amount) { super(); @@ -152,7 +152,7 @@ export class Transfer extends PromiseAction { */ export class Stake extends PromiseAction { /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ constructor(amount, publicKey) { @@ -193,7 +193,7 @@ export class AddAccessKey extends PromiseAction { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ constructor(publicKey, allowance, receiverId, functionNames, nonce) { @@ -232,7 +232,7 @@ export class DeleteKey extends PromiseAction { */ export class DeleteAccount extends PromiseAction { /** - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ constructor(beneficiaryId) { super(); @@ -367,7 +367,7 @@ export class NearPromise { /** * Creates a transfer promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ transfer(amount) { return this.addAction(new Transfer(amount)); @@ -375,7 +375,7 @@ export class NearPromise { /** * Creates a stake promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ stake(amount, publicKey) { @@ -407,7 +407,7 @@ export class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. */ addAccessKey(publicKey, allowance, receiverId, functionNames) { return this.addAccessKeyWithNonce(publicKey, allowance, receiverId, functionNames, 0n); @@ -419,7 +419,7 @@ export class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ addAccessKeyWithNonce(publicKey, allowance, receiverId, functionNames, nonce) { @@ -436,7 +436,7 @@ export class NearPromise { /** * Creates a delete account promise action and adds it to the current promise. * - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ deleteAccount(beneficiaryId) { return this.addAction(new DeleteAccount(beneficiaryId)); diff --git a/packages/near-sdk-js/lib/types/collections.d.ts b/packages/near-sdk-js/lib/types/collections.d.ts index c67d1724a..773fc3197 100644 --- a/packages/near-sdk-js/lib/types/collections.d.ts +++ b/packages/near-sdk-js/lib/types/collections.d.ts @@ -3,7 +3,7 @@ */ export interface GetOptions { /** - * A constructor function to call after deserializing a value. Tipically this is a constructor of the class you are storing. + * A constructor function to call after deserializing a value. Typically this is a constructor of the class you are storing. * * @param value - The value returned from deserialization - either the provided `deserializer` or default deserialization function. */ diff --git a/packages/near-sdk-js/lib/types/public_key.d.ts b/packages/near-sdk-js/lib/types/public_key.d.ts index 6b31d021b..cfa7bef2e 100644 --- a/packages/near-sdk-js/lib/types/public_key.d.ts +++ b/packages/near-sdk-js/lib/types/public_key.d.ts @@ -19,6 +19,8 @@ export declare class UnknownCurve extends ParsePublicKeyError { } /** * A abstraction on top of the NEAR public key string. + * Public key in a binary format with base58 string serialization with human-readable curve. + * The key types currently supported are `secp256k1` and `ed25519`. */ export declare class PublicKey { /** diff --git a/packages/near-sdk-js/lib/types/public_key.js b/packages/near-sdk-js/lib/types/public_key.js index f778e20ce..2c0a7bca6 100644 --- a/packages/near-sdk-js/lib/types/public_key.js +++ b/packages/near-sdk-js/lib/types/public_key.js @@ -75,6 +75,8 @@ export class UnknownCurve extends ParsePublicKeyError { } /** * A abstraction on top of the NEAR public key string. + * Public key in a binary format with base58 string serialization with human-readable curve. + * The key types currently supported are `secp256k1` and `ed25519`. */ export class PublicKey { /** diff --git a/packages/near-sdk-js/src/api.ts b/packages/near-sdk-js/src/api.ts index a02108315..172b05914 100644 --- a/packages/near-sdk-js/src/api.ts +++ b/packages/near-sdk-js/src/api.ts @@ -303,7 +303,7 @@ export function storageRead(key: string): string | null { } /** - * Checks for the existance of a value under the provided key in NEAR storage. + * Checks for the existence of a value under the provided key in NEAR storage. * * @param key - The key to check for in storage. */ @@ -312,7 +312,7 @@ export function storageHasKeyRaw(key: Uint8Array): boolean { } /** - * Checks for the existance of a value under the provided utf-8 string key in NEAR storage. + * Checks for the existence of a value under the provided utf-8 string key in NEAR storage. * * @param key - The utf-8 string key to check for in storage. */ @@ -967,7 +967,7 @@ export function validatorTotalStake(): bigint { * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \sum_i * mul_i g_{1 i} should be equal result. * - * @param value - equence of (g1:G1, fr:Fr), where + * @param value - sequence of (g1:G1, fr:Fr), where * G1 is point (x:Fq, y:Fq) on alt_bn128, * alt_bn128 is Y^2 = X^3 + 3 curve over Fq. * `value` is encoded as packed, little-endian diff --git a/packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts b/packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts index 922266d40..9c9f5ce37 100644 --- a/packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts +++ b/packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts @@ -189,7 +189,7 @@ function collectArguments(classId: t.Identifier): t.VariableDeclaration { } /** - * A helper function that inserts a contract method call expresion. + * A helper function that inserts a contract method call expression. * It calls the appropriate contract method and passes the collected _\_args_. * * ```typescript @@ -306,7 +306,7 @@ function executePromise(classId: t.Identifier): t.IfStatement { } /** - * A helper function that inserts the overriden function declaration into the class. + * A helper function that inserts the overridden function declaration into the class. * * @param classId - The class ID of the class being extended. * @param methodName - The name of the method being called. diff --git a/packages/near-sdk-js/src/cli/post-install.ts b/packages/near-sdk-js/src/cli/post-install.ts index e2095bc8e..3ea007ed0 100644 --- a/packages/near-sdk-js/src/cli/post-install.ts +++ b/packages/near-sdk-js/src/cli/post-install.ts @@ -18,8 +18,8 @@ const PLATFORM = os.platform(); const ARCH = os.arch(); console.log(`Current platform: ${PLATFORM}, current architecture: ${ARCH}`); -const SUPPORTED_PLATFORMS = ["linux", "darwin"]; // Unsaported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android' -const SUPPORTED_ARCH = ["x64", "arm64"]; // Unsaported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' +const SUPPORTED_PLATFORMS = ["linux", "darwin"]; // Unsupported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android' +const SUPPORTED_ARCH = ["x64", "arm64"]; // Unsupported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' if (!SUPPORTED_PLATFORMS.includes(PLATFORM)) { console.error(`Platform ${PLATFORM} is not supported at the moment`); diff --git a/packages/near-sdk-js/src/near-bindgen.ts b/packages/near-sdk-js/src/near-bindgen.ts index df1e04a2f..ec1f2653f 100644 --- a/packages/near-sdk-js/src/near-bindgen.ts +++ b/packages/near-sdk-js/src/near-bindgen.ts @@ -63,7 +63,7 @@ export function view(_empty: EmptyParameterObject): DecoratorFunction { /** * Tells the SDK to expose this function as a call function. - * Adds the neccessary checks if the function is private or payable. + * Adds the necessary checks if the function is private or payable. * * @param options - Options to configure the function behaviour. * @param options.privateFunction - Whether the function can be called by other contracts. diff --git a/packages/near-sdk-js/src/promise.ts b/packages/near-sdk-js/src/promise.ts index 5e63cb3b3..493cbac75 100644 --- a/packages/near-sdk-js/src/promise.ts +++ b/packages/near-sdk-js/src/promise.ts @@ -185,7 +185,7 @@ export class FunctionCallWeightRaw extends PromiseAction { */ export class Transfer extends PromiseAction { /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ constructor(public amount: Balance) { super(); @@ -203,7 +203,7 @@ export class Transfer extends PromiseAction { */ export class Stake extends PromiseAction { /** - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ constructor(public amount: Balance, public publicKey: PublicKey) { @@ -252,7 +252,7 @@ export class AddAccessKey extends PromiseAction { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ constructor( @@ -301,7 +301,7 @@ export class DeleteKey extends PromiseAction { */ export class DeleteAccount extends PromiseAction { /** - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ constructor(public beneficiaryId: AccountId) { super(); @@ -486,7 +486,7 @@ export class NearPromise { /** * Creates a transfer promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. */ transfer(amount: Balance): NearPromise { return this.addAction(new Transfer(amount)); @@ -495,7 +495,7 @@ export class NearPromise { /** * Creates a stake promise action and adds it to the current promise. * - * @param amount - The amount of NEAR to tranfer. + * @param amount - The amount of NEAR to transfer. * @param publicKey - The public key to use for staking. */ stake(amount: Balance, publicKey: PublicKey): NearPromise { @@ -530,7 +530,7 @@ export class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. */ addAccessKey( publicKey: PublicKey, @@ -554,7 +554,7 @@ export class NearPromise { * @param publicKey - The public key to add as a access key. * @param allowance - The allowance for the key in yoctoNEAR. * @param receiverId - The account ID of the receiver. - * @param functionNames - The names of funcitons to authorize. + * @param functionNames - The names of functions to authorize. * @param nonce - The nonce to use. */ addAccessKeyWithNonce( @@ -581,7 +581,7 @@ export class NearPromise { /** * Creates a delete account promise action and adds it to the current promise. * - * @param beneficiaryId - The beneficiary of the account deletion - the account to recieve all of the remaining funds of the deleted account. + * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account. */ deleteAccount(beneficiaryId: AccountId): NearPromise { return this.addAction(new DeleteAccount(beneficiaryId)); diff --git a/packages/near-sdk-js/src/types/collections.ts b/packages/near-sdk-js/src/types/collections.ts index b48aab1e9..33c28c2eb 100644 --- a/packages/near-sdk-js/src/types/collections.ts +++ b/packages/near-sdk-js/src/types/collections.ts @@ -3,7 +3,7 @@ */ export interface GetOptions { /** - * A constructor function to call after deserializing a value. Tipically this is a constructor of the class you are storing. + * A constructor function to call after deserializing a value. Typically this is a constructor of the class you are storing. * * @param value - The value returned from deserialization - either the provided `deserializer` or default deserialization function. */ diff --git a/packages/near-sdk-js/src/types/public_key.ts b/packages/near-sdk-js/src/types/public_key.ts index 5360b7a6f..e345db4b8 100644 --- a/packages/near-sdk-js/src/types/public_key.ts +++ b/packages/near-sdk-js/src/types/public_key.ts @@ -77,6 +77,8 @@ export class UnknownCurve extends ParsePublicKeyError { /** * A abstraction on top of the NEAR public key string. + * Public key in a binary format with base58 string serialization with human-readable curve. + * The key types currently supported are `secp256k1` and `ed25519`. */ export class PublicKey { /** diff --git a/tests/src/alt_bn128_api.js b/tests/src/alt_bn128_api.js index 0789d3dfa..5699fa50d 100644 --- a/tests/src/alt_bn128_api.js +++ b/tests/src/alt_bn128_api.js @@ -1,5 +1,7 @@ import { near, bytes } from "near-sdk-js"; +// Functions consumed by the altBn128PairingCheck tests + export function test_alt_bn128_g1_sum() { // Originated from https://github.com/near/nearcore/blob/8cd095ffc98a6507ed2d2a8982a6a3e42ebc1b62/runtime/near-test-contracts/estimator-contract/src/lib.rs#L557-L720 let buffer = new Uint8Array([ diff --git a/tests/src/bigint-serialization.ts b/tests/src/bigint-serialization.ts index c7f9c6038..69121b315 100644 --- a/tests/src/bigint-serialization.ts +++ b/tests/src/bigint-serialization.ts @@ -1,5 +1,13 @@ import { near, NearBindgen, call, view } from "near-sdk-js"; +/** + * Simple class used for testing of the `bigintField`. + * - Includes methods: + * - `getBigintField()` - returns the current `bigintField` value. + * - `setBigintField(args: { bigintField })` - used to change the current `bigintField` value. + * - `increment()` - increases the `bigintField` value by `1n`. + * @param bigintField - Simple bigint used for testing. + */ @NearBindgen({}) export class BigIntSerializationTest { bigintField: bigint; diff --git a/tests/src/bytes.js b/tests/src/bytes.js index a8829bf72..af868173d 100644 --- a/tests/src/bytes.js +++ b/tests/src/bytes.js @@ -1,5 +1,7 @@ import { near, bytes, str, encode, decode, assert } from "near-sdk-js"; +// Functions consumed by the bytes tests + export function log_expected_input_tests() { // log ascii string near.log("abc"); diff --git a/tests/src/context_api.js b/tests/src/context_api.js index 05a6fadb0..895ed439e 100644 --- a/tests/src/context_api.js +++ b/tests/src/context_api.js @@ -1,5 +1,7 @@ import { near, bytes } from "near-sdk-js"; +// Functions consumed by the context api tests + export function get_current_account_id() { near.valueReturn(near.currentAccountId()); } diff --git a/tests/src/date-serialization.ts b/tests/src/date-serialization.ts index aeb0e817c..9a29a7aff 100644 --- a/tests/src/date-serialization.ts +++ b/tests/src/date-serialization.ts @@ -1,5 +1,13 @@ import { near, NearBindgen, call, view } from "near-sdk-js"; +/** + * Simple class used for testing of the `dateField`. + * - Includes methods: + * - `getDateField()` - returns the current `dateField` value. + * - `setDateField(args: { dateField })` - used to change the current `dateField` value. + * - `getDateFieldAsMilliseconds()` - returns the `dateField` value in milliseconds. + * @param dateField - Simple `Date` used for testing. + */ @NearBindgen({}) export class DateSerializationTest { dateField: Date; diff --git a/tests/src/decorators/payable.ts b/tests/src/decorators/payable.ts index 5400aaf4a..7f8401e63 100644 --- a/tests/src/decorators/payable.ts +++ b/tests/src/decorators/payable.ts @@ -1,5 +1,18 @@ import { near, NearBindgen, call, view } from "near-sdk-js"; +/** + * Simple class used for testing of the `@call` decorator method with `option.payableFunction`, + * which identifies whether the function can accept an attached deposit. + * - `option.payableFunction` set to `true` + * - `option.payableFunction` set to `false` + * - Includes methods: + * - `setValueWithPayableFunction({ value })` - used to change the current value and can accept an attached deposit. + * - `setValueWithNotPayableFunction({ value })` - used to change the current value and cannot accept an attached deposit. + * - `setValueWithNotPayableFunctionByDefault({ value })` - used to change the current value and cannot accept an attached deposit, + * default behavior. + * - `getValue()` - returns the current value + * @param value - Simple string used for testing. + */ @NearBindgen({}) export class PayableTest { value: string; diff --git a/tests/src/decorators/private.ts b/tests/src/decorators/private.ts index cad023dbe..5117aeed9 100644 --- a/tests/src/decorators/private.ts +++ b/tests/src/decorators/private.ts @@ -1,5 +1,18 @@ import { near, NearBindgen, call, view } from "near-sdk-js"; +/** + * Simple class used for testing of the `@call` decorator method with `option.privateFunction`, + * which identifies whether the function can be called by other contracts. + * - `option.privateFunction` set to `true` + * - `option.privateFunction` set to `false` + * - Includes methods: + * - `setValueWithPrivateFunction({ value })` - used to change the current value and cannot be called by other contracts. + * - `setValueWithNotPrivateFunction({ value })` - used to change the current value and can be called by other contracts. + * - `setValueWithNotPrivateFunctionByDefault({ value })` - used to change the current value and can be called by other contracts, + * default behavior. + * - `getValue()` - returns the current value + * @param value - Simple string used for testing. + */ @NearBindgen({}) export class PrivateTest { value: string; diff --git a/tests/src/decorators/require_init_false.ts b/tests/src/decorators/require_init_false.ts index 5c24c597e..afb2ef6a7 100644 --- a/tests/src/decorators/require_init_false.ts +++ b/tests/src/decorators/require_init_false.ts @@ -1,5 +1,15 @@ import { near, NearBindgen, call, view, initialize } from "near-sdk-js"; +/** + * Simple class used for testing of the `NearBindgen` decorator with `option.requireInit`, + * which identifies whether the contract requires initialization or not. + * - `option.requireInit` set to `false` - Contract does not require initialization. + * - Includes methods: + * - `init()` - used for initializing the class + * - `getStatus()` - used to get the current status param + * - `setStatus()` - used to change the current status + * @param status - Simple string used for testing. + */ @NearBindgen({ requireInit: false }) export class NBTest { status: string; diff --git a/tests/src/decorators/require_init_true.ts b/tests/src/decorators/require_init_true.ts index 6d813619b..a13547bc7 100644 --- a/tests/src/decorators/require_init_true.ts +++ b/tests/src/decorators/require_init_true.ts @@ -1,5 +1,15 @@ import { near, NearBindgen, call, view, initialize } from "near-sdk-js"; +/** + * Simple class used for testing of the `NearBindgen` decorator with `option.requireInit`, + * which identifies whether the contract requires initialization or not. + * - `option.requireInit` set to `true` - Contract requires initialization. + * - Includes methods: + * - `init()` - used for initializing the class + * - `getStatus()` - used to get the current status param + * - `setStatus()` - used to change the current status + * @param status - Simple string used for testing. + */ @NearBindgen({ requireInit: true }) export class NBTest { status: string; diff --git a/tests/src/function-params.js b/tests/src/function-params.js index 18253ea1c..599ef2b18 100644 --- a/tests/src/function-params.js +++ b/tests/src/function-params.js @@ -1,7 +1,13 @@ import { NearBindgen, call, view, near } from "near-sdk-js"; /** - * Simple contract to test function parameters + * Simple contract used to test function params. + * - Includes methods: + * - `set_values({ param1, param2, param3 })` - change all the values. + * - `get_values()` - returns an object containing all the values. + * @param val1 - Simple string used for testing. + * @param val2 - Simple string used for testing. + * @param val3 - Simple string used for testing. */ @NearBindgen({}) export class FunctionParamsTestContract { diff --git a/tests/src/highlevel-promise.js b/tests/src/highlevel-promise.js index adb49883a..cf8519b27 100644 --- a/tests/src/highlevel-promise.js +++ b/tests/src/highlevel-promise.js @@ -14,6 +14,9 @@ function arrayN(n) { return [...Array(Number(n)).keys()]; } +/** + * More information about this class, can be found in - benchmark/README.md/Highlevel collection + */ @NearBindgen({}) export class HighlevelPromiseContract { @call({}) diff --git a/tests/src/log_panic_api.js b/tests/src/log_panic_api.js index 1d386ca45..f75018f0a 100644 --- a/tests/src/log_panic_api.js +++ b/tests/src/log_panic_api.js @@ -1,5 +1,7 @@ import { near, bytes } from "near-sdk-js"; +// Functions consumed by the log panic tests + export function log_expected_input_tests() { // log ascii string near.log("abc"); diff --git a/tests/src/lookup-map.js b/tests/src/lookup-map.js index 2f7cc382b..f3c08b3c9 100644 --- a/tests/src/lookup-map.js +++ b/tests/src/lookup-map.js @@ -1,6 +1,18 @@ import { NearBindgen, call, view, LookupMap } from "near-sdk-js"; import { House, Room } from "./model.js"; +/** + * Simple contract used to test `lookupMap` functionality. + * - Includes methods: + * - `get({ key })` - Get the data stored at the provided key. + * - `containsKey({ key })` - Checks whether the collection contains the value. + * - `set({ key, value })` - Store a new value at the provided key. + * - `remove_key({ key })` - Removes and retrieves the element with the provided key. + * - `extend({ kvs })` - Extends the current collection with the passed in array of key-value pairs. + * - `add_house()` - Adds a test `House` object in the `lookupMap`. + * - `get_house()` - Returns a `string` containing the `house.describe()` + `room.describe()` results. + * @param lookupMap - Simple `LookupMap` used for testing. + */ @NearBindgen({}) export class LookupMapTestContract { constructor() { diff --git a/tests/src/lookup-set.js b/tests/src/lookup-set.js index f5dc9d2a9..ce5bc3582 100644 --- a/tests/src/lookup-set.js +++ b/tests/src/lookup-set.js @@ -1,6 +1,17 @@ import { NearBindgen, call, view, LookupSet } from "near-sdk-js"; import { House, Room } from "./model.js"; +/** + * Simple contract used to test `lookupSet` functionality. + * - Includes methods: + * - `contains({ key })` - Checks whether the value is present in the set. + * - `set({ key })` - f the set did not have this value present, `true` is returned. If the set did have this value present, `false` is returned. + * - `remove_key({ key })` - Removes and retrieves the element with the provided key. + * - `extend({ keys })` - Extends the current collection with the passed array of elements. + * - `add_house({ name, rooms })` - Adds a test `House` object in the `lookupSet`. + * - `house_exist({ name, rooms })` - Checks whether the value is present in the set, `true` if present, `false` if not. + * @param lookupSet - Simple `LookupSet` used for testing. + */ @NearBindgen({}) export class LookupSetTestContract { constructor() { diff --git a/tests/src/math_api.js b/tests/src/math_api.js index b7827ab4a..1befd6ce2 100644 --- a/tests/src/math_api.js +++ b/tests/src/math_api.js @@ -1,5 +1,7 @@ import { near, bytes } from "near-sdk-js"; +// Functions consumed by the math api tests + export function test_sha256() { near.valueReturnRaw(near.sha256(bytes("tesdsst"))); } diff --git a/tests/src/middlewares.ts b/tests/src/middlewares.ts index 7ea73a164..59779472c 100644 --- a/tests/src/middlewares.ts +++ b/tests/src/middlewares.ts @@ -7,6 +7,11 @@ import { middleware, } from "near-sdk-js"; +/** + * Simple contract used for testing the `@middleware` decorator. + * The method that gets called with the same arguments that are passed to the function it is wrapping. + * @param args - Arguments that will be passed to the function - immutable. + */ @NearBindgen({ requireInit: true }) export class Contract { @initialize({}) diff --git a/tests/src/migrate.ts b/tests/src/migrate.ts index eb5cd7f8c..91d47f60a 100644 --- a/tests/src/migrate.ts +++ b/tests/src/migrate.ts @@ -1,5 +1,14 @@ import { NearBindgen, near, call, view, migrate } from "near-sdk-js"; +/** + * Simple class used for testing. + * - `option.requireInit` set to `true` - Contract requires initialization. + * - Includes methods: + * - `increase({ n })` - increases the count with the given `n` + * - `getCount()` - get the current count + * - `migrFuncValueTo18()` - set the current count to `18` + * @param count - Simple number used for testing. + */ @NearBindgen({}) export class Counter { count = 0; diff --git a/tests/src/model.js b/tests/src/model.js index 28e4e72d8..af26fe9ef 100644 --- a/tests/src/model.js +++ b/tests/src/model.js @@ -1,3 +1,10 @@ +/** + * Simple model used for testing. + * - Includes methods: + * - `describe()` - returns a string `house ${this.name} has ${this.rooms.length} rooms.` + * @param name - Simple `string` used for testing. + * @param rooms - Simple `Room[]` used for testing. + */ export class House { constructor(name, rooms) { this.name = name; @@ -9,6 +16,13 @@ export class House { } } +/** + * Simple model used for testing. + * - Includes methods: + * - `describe()` - returns a string `room ${this.name} is ${this.size}.` + * @param name - Simple `string` used for testing. + * @param size - Simple `number` used for testing. + */ export class Room { constructor(name, size) { this.name = name; diff --git a/tests/src/promise_api.js b/tests/src/promise_api.js index 0775a2624..c40f430d8 100644 --- a/tests/src/promise_api.js +++ b/tests/src/promise_api.js @@ -1,5 +1,7 @@ import { near } from "near-sdk-js"; +// Functions consumed by the promise api tests + function arrayN(n) { return [...Array(Number(n)).keys()]; } diff --git a/tests/src/promise_batch_api.js b/tests/src/promise_batch_api.js index 2e78d7dee..e63ffe69b 100644 --- a/tests/src/promise_batch_api.js +++ b/tests/src/promise_batch_api.js @@ -1,5 +1,7 @@ import { near, includeBytes } from "near-sdk-js"; +// Functions consumed by the promise batch api tests + export function test_promise_batch_stake() { let promiseId = near.promiseBatchCreate("caller2.test.near"); near.promiseBatchActionStake( diff --git a/tests/src/public-key.js b/tests/src/public-key.js index 2aff98605..818f685de 100644 --- a/tests/src/public-key.js +++ b/tests/src/public-key.js @@ -2,6 +2,8 @@ import { near } from "near-sdk-js"; import { CurveType, PublicKey } from "near-sdk-js"; import { assert } from "near-sdk-js"; +// Functions consumed by the public key tests + function runtime_validate_public_key(prefix, public_key) { let promiseId = near.promiseBatchCreate(prefix + ".pk.test.near"); near.promiseBatchActionCreateAccount(promiseId); diff --git a/tests/src/storage_api.js b/tests/src/storage_api.js index c7c7e56fe..f562cc0dd 100644 --- a/tests/src/storage_api.js +++ b/tests/src/storage_api.js @@ -1,5 +1,7 @@ import { near, bytes } from "near-sdk-js"; +// Functions consumed by the storage api tests + export function test_storage_write() { near.valueReturnRaw( bytes( diff --git a/tests/src/unordered-map.js b/tests/src/unordered-map.js index 83451c35e..889065eb8 100644 --- a/tests/src/unordered-map.js +++ b/tests/src/unordered-map.js @@ -1,6 +1,22 @@ import { NearBindgen, call, view, UnorderedMap } from "near-sdk-js"; import { House, Room } from "./model.js"; +/** + * Simple contract used for testing the `unorderedMap`. + * - Includes methods: + * - `len()` - Returns the current number of elements present in the map. + * - `isEmpty()` - Checks whether the collection is empty. + * - `get({ key })` - Get the data stored at the provided key. + * - `set({ key, value })` - Store a new value at the provided key. + * - `remove_key({ key })` - Removes and retrieves the element with the provided key. + * - `clear()` - Remove all of the elements stored within the collection. + * - `toArray()` - Return a JavaScript array of the data stored within the collection. + * - `extend({ kvs })` - Extends the current collection with the passed in array of key-value pairs. + * - `add_house()` - Store a new `House` object in the `unorderedMap` instance. + * - `get_house()` - Retrieves the current `House` object from the `unorderedMap` and returns a string `house.describe() + room.describe()` + * - `keys({ start, limit })` - Converts the deserialized data from storage to a JavaScript instance of the collection. + * @param unorderedMap - Simple `UnorderedMap` used for testing. + */ @NearBindgen({}) export class UnorderedMapTestContract { constructor() { diff --git a/tests/src/unordered-set.js b/tests/src/unordered-set.js index a40e1d197..ec9b6c90f 100644 --- a/tests/src/unordered-set.js +++ b/tests/src/unordered-set.js @@ -1,6 +1,22 @@ import { NearBindgen, call, view, UnorderedSet } from "near-sdk-js"; import { House, Room } from "./model.js"; +/** + * Simple contract used for testing the `unorderedSet`. + * - Includes methods: + * - `len()` - Returns the current number of elements present in the set. + * - `isEmpty()` - Checks whether the collection is empty. + * - `contains({ element })` - Checks whether the collection contains the value. + * - `set({ element }) ` - Store a new value at the provided key. + * - `remove_key({ element })` - Removes and retrieves the element. + * - `clear()` - Remove all of the elements stored within the collection. + * - `toArray()` - Return a JavaScript array of the data stored within the collection. + * - `elements({ start, limit })` - Converts the deserialized data from storage to a JavaScript instance of the collection. + * - `extend({ elements })` - Extends the current collection with the passed in array of elements. + * - `add_house({ name, rooms })` - Store a new `House` object in the `unorderedMap` instance. + * - `house_exist({ name, rooms })` - Checks whether the collection contains the passed `House` object. + * @param unorderedSet - Simple `UnorderedSet` used for testing. + */ @NearBindgen({}) export class UnorderedSetTestContract { constructor() { diff --git a/tests/src/vector.js b/tests/src/vector.js index d1f873784..1f304ea8e 100644 --- a/tests/src/vector.js +++ b/tests/src/vector.js @@ -1,6 +1,25 @@ import { NearBindgen, call, view, Vector } from "near-sdk-js"; import { House, Room } from "./model.js"; +/** + * Simple contract used for testing the `vector`. + * - Includes methods: + * - `len()` - Returns the current number of elements. + * - `isEmpty()` - Checks whether the collection is empty. + * - `get({ index })` - Get the value at the current index. + * - `push({ value })` - Adds data to the collection. + * - `pop()` - Removes and retrieves the element with the highest index.. + * - `clear()` - Remove all of the elements stored within the collection. + * - `toArray()` - Return a JavaScript array of the data stored within the collection. + * - `extend({ kvs })` - Extends the current collection with the passed in array of elements. + * - `replace({ index, value })` - Replaces the data stored at the provided index with the provided data and returns the previously stored data. + * - `swapRemove({ index })` - Removes an element from the vector and returns it in serialized form. + * The removed element is replaced by the last element of the vector. + * Does not preserve ordering, but is `O(1)`. + * - `add_house()` - Store a new `House` object in the `unorderedMap` instance. + * - `get_house()` - Returns the `House` object at index `0`. + * @param vector - Simple `Vector` used for testing. + */ @NearBindgen({}) export class VectorTestContract { constructor() { From 9623545c4ccbcc34536f20c048d58112364cb6d8 Mon Sep 17 00:00:00 2001 From: Georgi Tsonev <31661340+gtsonevv@users.noreply.github.com> Date: Tue, 1 Oct 2024 15:38:21 +0300 Subject: [PATCH 3/3] chore: Add collections gas usage tests (#411) --- .../test-collections-performance.ava.js | 151 ++++++++++++++++++ benchmark/__tests__/util.js | 15 ++ benchmark/package.json | 8 +- benchmark/src/lookup-map.js | 23 +++ benchmark/src/lookup-set.js | 23 +++ benchmark/src/unordered-map.js | 31 ++++ benchmark/src/unordered-set.js | 31 ++++ benchmark/src/vector.js | 31 ++++ 8 files changed, 312 insertions(+), 1 deletion(-) create mode 100644 benchmark/__tests__/test-collections-performance.ava.js create mode 100644 benchmark/src/lookup-map.js create mode 100644 benchmark/src/lookup-set.js create mode 100644 benchmark/src/unordered-map.js create mode 100644 benchmark/src/unordered-set.js create mode 100644 benchmark/src/vector.js diff --git a/benchmark/__tests__/test-collections-performance.ava.js b/benchmark/__tests__/test-collections-performance.ava.js new file mode 100644 index 000000000..858599c0d --- /dev/null +++ b/benchmark/__tests__/test-collections-performance.ava.js @@ -0,0 +1,151 @@ +import { Worker } from "near-workspaces"; +import test from "ava"; +import { logTotalGas, randomInt } from "./util.js"; + +const COLLECTION_SIZE = 20; + +test.before(async (t) => { + // Init the worker and start a Sandbox server + const worker = await Worker.init(); + + // Prepare sandbox for tests, create accounts, deploy contracts, etx. + const root = worker.rootAccount; + + // Deploy the test contracts. + const lookupMapContract = await root.devDeploy("build/lookup-map.wasm"); + const lookupSetContract = await root.devDeploy("build/lookup-set.wasm"); + const unorderedMapContract = await root.devDeploy("build/unordered-map.wasm"); + const unorderedSetContract = await root.devDeploy("build/unordered-set.wasm"); + const vectorContract = await root.devDeploy("build/vector.wasm"); + + // Test users + const ali = await root.createSubAccount("ali"); + + // Save state for test runs + t.context.worker = worker; + t.context.accounts = { + root, + lookupMapContract, + lookupSetContract, + unorderedMapContract, + unorderedSetContract, + vectorContract, + ali, + }; +}); + +test.after.always(async (t) => { + await t.context.worker.tearDown().catch((error) => { + console.log("Failed to tear down the worker:", error); + }); +}); + +test("JS lookup map contract operations", async (t) => { + const { ali, lookupMapContract } = t.context.accounts; + + let rAdd; + for (let i = 0; i < COLLECTION_SIZE; i++) { + rAdd = await ali.callRaw(lookupMapContract, "addElement", { key: i, value: i }); + } + t.is(rAdd.result.status.SuccessValue, ""); + logTotalGas("Add element", rAdd, t); + + const val = randomInt(COLLECTION_SIZE); + const rGet = await ali.callRaw(lookupMapContract, "getElement", { key: val }); + t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, "base64")), val); + logTotalGas("Get element", rGet, t); + + const rRem = await ali.callRaw(lookupMapContract, "removeElement", { key: randomInt(COLLECTION_SIZE) }); + t.is(rRem.result.status.SuccessValue, ""); + logTotalGas("Remove element", rRem, t); +}); + +test("JS lookup set contract operations", async (t) => { + const { ali, lookupSetContract } = t.context.accounts; + + let rAdd; + for (let i = 0; i < COLLECTION_SIZE; i++) { + rAdd = await ali.callRaw(lookupSetContract, "addElement", { value: i }); + } + t.is(rAdd.result.status.SuccessValue, ""); + logTotalGas("Add element", rAdd, t); + + const rGet = await ali.callRaw(lookupSetContract, "containsElement", { value: randomInt(COLLECTION_SIZE) }); + t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, "base64")), true); + logTotalGas("Get element", rGet, t); + + const rRem = await ali.callRaw(lookupSetContract, "removeElement", { value: randomInt(COLLECTION_SIZE) }); + t.is(rRem.result.status.SuccessValue, ""); + logTotalGas("Remove element", rRem, t); +}); + +test("JS unordered map contract operations", async (t) => { + const { ali, unorderedMapContract } = t.context.accounts; + + let rAdd; + for (let i = 0; i < COLLECTION_SIZE; i++) { + rAdd = await ali.callRaw(unorderedMapContract, "addElement", { key: i, value: i }); + } + t.is(rAdd.result.status.SuccessValue, ""); + logTotalGas("Add element", rAdd, t); + + const val = randomInt(COLLECTION_SIZE); + const rGet = await ali.callRaw(unorderedMapContract, "getElement", { key: val }); + t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, "base64")), val); + logTotalGas("Get element", rGet, t); + + const rIt = await ali.callRaw(unorderedMapContract, "iterate", {}); + t.is(rIt.result.status.SuccessValue, ""); + logTotalGas("Iterate collection", rIt, t); + + const rRem = await ali.callRaw(unorderedMapContract, "removeElement", { key: randomInt(COLLECTION_SIZE) }); + t.is(rRem.result.status.SuccessValue, ""); + logTotalGas("Remove element", rRem, t); +}); + +test("JS unordered set contract operations", async (t) => { + const { ali, unorderedSetContract } = t.context.accounts; + + let rAdd; + for (let i = 0; i < COLLECTION_SIZE; i++) { + rAdd = await ali.callRaw(unorderedSetContract, "addElement", { value: i }); + } + t.is(rAdd.result.status.SuccessValue, ""); + logTotalGas("Add element", rAdd, t); + + const rGet = await ali.callRaw(unorderedSetContract, "containsElement", { value: randomInt(COLLECTION_SIZE) }); + t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, "base64")), true); + logTotalGas ("Get element", rGet, t); + + const rIt = await ali.callRaw(unorderedSetContract, "iterate", {}); + t.is(rIt.result.status.SuccessValue, ""); + logTotalGas("Iterate collection", rIt, t); + + const rRem = await ali.callRaw(unorderedSetContract, "removeElement", { value: randomInt(COLLECTION_SIZE) }); + t.is(rRem.result.status.SuccessValue, ""); + logTotalGas("Remove element", rRem, t); +}); + +test("JS vector contract operations", async (t) => { + const { ali, vectorContract } = t.context.accounts; + + let rAdd; + for (let i = 0; i < COLLECTION_SIZE; i++) { + rAdd = await ali.callRaw(vectorContract, "addElement", { value: i }); + } + t.is(rAdd.result.status.SuccessValue, ""); + logTotalGas("Add element", rAdd, t); + + const val = randomInt(COLLECTION_SIZE); + const rGet = await ali.callRaw(vectorContract, "getElement", { index: val }); + t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, "base64")), val); + logTotalGas("Get element", rGet, t); + + const rIt = await ali.callRaw(vectorContract, "iterate", {}); + t.is(rIt.result.status.SuccessValue, ""); + logTotalGas("Iterate collection", rIt, t); + + const rRem = await ali.callRaw(vectorContract, "removeElement", { index: randomInt(COLLECTION_SIZE) }); + t.is(rRem.result.status.SuccessValue, ""); + logTotalGas("Remove element", rRem, t); +}); \ No newline at end of file diff --git a/benchmark/__tests__/util.js b/benchmark/__tests__/util.js index bc2f6f6a0..e91d8ea6a 100644 --- a/benchmark/__tests__/util.js +++ b/benchmark/__tests__/util.js @@ -51,3 +51,18 @@ export function logGasDetail(r, t) { ) ); } + +export function logTotalGas(prefix = '', r, t) { + t.log( + prefix + ' - Total gas used: ', + formatGas( + r.result.transaction_outcome.outcome.gas_burnt + + r.result.receipts_outcome[0].outcome.gas_burnt + + (r.result.receipts_outcome[1]?.outcome.gas_burnt || 0) + ) + ); +} + +export function randomInt(max) { + return Math.floor(Math.random() * max); +} \ No newline at end of file diff --git a/benchmark/package.json b/benchmark/package.json index 897f9a8d1..1ed0f72d6 100644 --- a/benchmark/package.json +++ b/benchmark/package.json @@ -12,13 +12,19 @@ "build:highlevel-collection": "near-sdk-js build src/highlevel-collection.js build/highlevel-collection.wasm", "build:expensive-calc": "near-sdk-js build src/expensive-calc.js build/expensive-calc.wasm", "build:deploy-contract": "near-sdk-js build src/deploy-contract.js build/deploy-contract.wasm", + "build:lookup-map": "near-sdk-js build src/lookup-map.js build/lookup-map.wasm", + "build:lookup-set": "near-sdk-js build src/lookup-set.js build/lookup-set.wasm", + "build:unordered-map": "near-sdk-js build src/unordered-map.js build/unordered-map.wasm", + "build:unordered-set": "near-sdk-js build src/unordered-set.js build/unordered-set.wasm", + "build:vector": "near-sdk-js build src/vector.js build/vector.wasm", "test": "ava", "test:lowlevel-minimal": "ava __tests__/test-lowlevel-minimal.ava.js", "test:highlevel-minimal": "ava __tests__/test-highlevel-minimal.ava.js", "test:lowlevel-api": "ava __tests__/test-lowlevel-api.ava.js", "test:highlevel-collection": "ava __tests__/test-highlevel-collection.ava.js", "test:expensive-calc": "ava __tests__/test-expensive-calc.ava.js", - "test:deploy-contract": "ava __tests__/test-deploy-contract.ava.js" + "test:deploy-contract": "ava __tests__/test-deploy-contract.ava.js", + "test:collections": "ava __tests__/test-collections-performance.ava.js" }, "author": "Near Inc ", "license": "Apache-2.0", diff --git a/benchmark/src/lookup-map.js b/benchmark/src/lookup-map.js new file mode 100644 index 000000000..ccca0126d --- /dev/null +++ b/benchmark/src/lookup-map.js @@ -0,0 +1,23 @@ +import { NearBindgen, call, LookupMap, view } from "near-sdk-js"; + +@NearBindgen({}) +export class LookupMapContract { + constructor() { + this.lookupMap = new LookupMap("LM"); + } + + @call({}) + addElement({ key, value }) { + this.lookupMap.set(key, value); + } + + @call({}) + removeElement({ key }) { + this.lookupMap.remove(key); + } + + @view({}) + getElement({ key }) { + return this.lookupMap.get(key); + } +} diff --git a/benchmark/src/lookup-set.js b/benchmark/src/lookup-set.js new file mode 100644 index 000000000..7d23c2f0b --- /dev/null +++ b/benchmark/src/lookup-set.js @@ -0,0 +1,23 @@ +import { NearBindgen, call, LookupSet, view } from "near-sdk-js"; + +@NearBindgen({}) +export class LookupSetContract { + constructor() { + this.lookupSet = new LookupSet("LS"); + } + + @call({}) + addElement({ value }) { + this.lookupSet.set(value); + } + + @call({}) + removeElement({ value }) { + this.lookupSet.remove(value); + } + + @view({}) + containsElement({ value }) { + return this.lookupSet.contains(value); + } +} diff --git a/benchmark/src/unordered-map.js b/benchmark/src/unordered-map.js new file mode 100644 index 000000000..c35b05287 --- /dev/null +++ b/benchmark/src/unordered-map.js @@ -0,0 +1,31 @@ +import { NearBindgen, call, UnorderedMap, view } from "near-sdk-js"; + +@NearBindgen({}) +export class UnorderedMapContract { + constructor() { + this.unorderedMap = new UnorderedMap("UM"); + } + + @call({}) + addElement({ key, value }) { + this.unorderedMap.set(key, value); + } + + @call({}) + removeElement({ key }) { + this.unorderedMap.remove(key); + } + + @view({}) + getElement({ key }) { + return this.unorderedMap.get(key); + } + + @view({}) + iterate() { + const size = this.unorderedMap.length; + for (let i = 0; i < size; i++) { + this.unorderedMap.get(i); + } + } +} diff --git a/benchmark/src/unordered-set.js b/benchmark/src/unordered-set.js new file mode 100644 index 000000000..644f5adc3 --- /dev/null +++ b/benchmark/src/unordered-set.js @@ -0,0 +1,31 @@ +import { NearBindgen, call, UnorderedSet, view } from "near-sdk-js"; + +@NearBindgen({}) +export class UnorderedSetContract { + constructor() { + this.unorderedSet = new UnorderedSet("US"); + } + + @call({}) + addElement({ value }) { + this.unorderedSet.set(value); + } + + @call({}) + removeElement({ value }) { + this.unorderedSet.remove(value); + } + + @view({}) + containsElement({ value }) { + return this.unorderedSet.contains(value); + } + + @view({}) + iterate() { + const size = this.unorderedSet.length; + for (let i = 0; i < size; i++) { + this.unorderedSet.contains(i); + } + } +} diff --git a/benchmark/src/vector.js b/benchmark/src/vector.js new file mode 100644 index 000000000..88e87036a --- /dev/null +++ b/benchmark/src/vector.js @@ -0,0 +1,31 @@ +import { NearBindgen, call, Vector, view } from "near-sdk-js"; + +@NearBindgen({}) +export class VectorContract { + constructor() { + this.vector = new Vector("V"); + } + + @call({}) + addElement({ value }) { + this.vector.push(value); + } + + @call({}) + removeElement({ index }) { + this.vector.swapRemove(index); + } + + @view({}) + getElement({ index }) { + return this.vector.get(index); + } + + @view({}) + iterate() { + const size = this.vector.length; + for (let i = 0; i < size; i++) { + this.vector.get(i); + } + } +}