Showing preview only (1,090K chars total). Download the full file or copy to clipboard to get everything.
Repository: near/near-sdk-js
Branch: develop
Commit: 8431739ff5e4
Files: 348
Total size: 997.0 KB
Directory structure:
gitextract_uwvzvvaa/
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug.yml
│ │ ├── config.yml
│ │ └── feature.yml
│ ├── pull_request_template.md
│ └── workflows/
│ ├── add-to-devtools.yml
│ ├── tests.yml
│ ├── typedoc-generate-gitbook-docs.yml
│ └── typedoc-generator.yml
├── .gitignore
├── .npmrc
├── AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md
├── CODEOWNERS
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── LICENSE-APACHE
├── README.md
├── RELEASE.md
├── RUNTIME_INVESTIGATE.md
├── SECURITY.md
├── TOOLING.md
├── benchmark/
│ ├── .gitignore
│ ├── README.md
│ ├── __tests__/
│ │ ├── test-collections-performance.ava.js
│ │ ├── test-deploy-contract.ava.js
│ │ ├── test-expensive-calc.ava.js
│ │ ├── test-highlevel-collection.ava.js
│ │ ├── test-highlevel-minimal.ava.js
│ │ ├── test-lowlevel-api.ava.js
│ │ ├── test-lowlevel-minimal.ava.js
│ │ └── util.js
│ ├── ava.config.cjs
│ ├── example-outcome.json
│ ├── jsconfig.json
│ ├── package.json
│ ├── res/
│ │ ├── deploy_contract.wasm
│ │ ├── expensive_calc.wasm
│ │ ├── highlevel_collection.wasm
│ │ ├── highlevel_minimal.wasm
│ │ ├── lowlevel_api.wasm
│ │ └── lowlevel_minimal.wasm
│ ├── src/
│ │ ├── deploy-contract.js
│ │ ├── expensive-calc.js
│ │ ├── highlevel-collection.js
│ │ ├── highlevel-minimal.js
│ │ ├── lookup-map.js
│ │ ├── lookup-set.js
│ │ ├── lowlevel-api.js
│ │ ├── lowlevel-minimal.js
│ │ ├── unordered-map.js
│ │ ├── unordered-set.js
│ │ └── vector.js
│ └── tsconfig.json
├── examples/
│ ├── .gitignore
│ ├── README.md
│ ├── __tests__/
│ │ ├── standard-ft/
│ │ │ └── ft-tests.ava.js
│ │ ├── standard-nft/
│ │ │ ├── test_approval.ava.js
│ │ │ ├── test_core.ava.js
│ │ │ └── test_enumeration.ava.js
│ │ ├── test-basic-updates.ava.js
│ │ ├── test-clean-state.ava.js
│ │ ├── test-counter.ava.js
│ │ ├── test-cross-contract-call-loop.ava.js
│ │ ├── test-cross-contract-call-ts.ava.js
│ │ ├── test-cross-contract-call.ava.js
│ │ ├── test-fungible-token-lockable.ava.js
│ │ ├── test-fungible-token.ava.js
│ │ ├── test-nested-collections.ava.js
│ │ ├── test-non-fungible-token.ava.js
│ │ ├── test-parking-lot.ava.js
│ │ ├── test-programmatic-update.ava.js
│ │ ├── test-state-message-migration-add-filed.ava.js
│ │ ├── test-state-migration.ava.js
│ │ ├── test-status-deserialize-class.ava.js
│ │ ├── test-status-message-borsh.ava.js
│ │ ├── test-status-message-collections.ava.js
│ │ ├── test-status-message-deserialize-err.ava.js
│ │ ├── test-status-message-serialize-err.ava.js
│ │ └── test-status-message.ava.js
│ ├── ava.config.cjs
│ ├── jsconfig.json
│ ├── package.json
│ ├── res/
│ │ └── defi.wasm
│ ├── src/
│ │ ├── basic-updates/
│ │ │ ├── basic-updates-base.js
│ │ │ └── basic-updates-update.js
│ │ ├── clean-state.js
│ │ ├── counter/
│ │ │ ├── counter-lowlevel.js
│ │ │ ├── counter.js
│ │ │ ├── counter.ts
│ │ │ └── log.ts
│ │ ├── cross-contract-calls/
│ │ │ ├── cross-contract-call-loop.js
│ │ │ ├── cross-contract-call.js
│ │ │ └── cross-contract-call.ts
│ │ ├── fungible-token/
│ │ │ ├── fungible-token-helper.ts
│ │ │ ├── fungible-token-lockable.js
│ │ │ ├── fungible-token.ts
│ │ │ └── my-ft.ts
│ │ ├── nested-collections.ts
│ │ ├── non-fungible-token/
│ │ │ ├── my-nft.ts
│ │ │ ├── non-fungible-token-receiver.js
│ │ │ ├── non-fungible-token.js
│ │ │ ├── test-approval-receiver.ts
│ │ │ └── test-token-receiver.ts
│ │ ├── parking-lot.ts
│ │ ├── programmatic-updates/
│ │ │ ├── programmatic-update-after.ts
│ │ │ └── programmatic-update-before.ts
│ │ ├── state-migration/
│ │ │ ├── state-migration-new.ts
│ │ │ └── state-migration-original.ts
│ │ ├── status-deserialize-class.js
│ │ └── status-message/
│ │ ├── status-message-borsh.js
│ │ ├── status-message-collections.js
│ │ ├── status-message-deserialize-err.js
│ │ ├── status-message-migrate-add-field.js
│ │ ├── status-message-serialize-err.js
│ │ └── status-message.js
│ └── tsconfig.json
├── generate-docs-markdown.js
├── near-sdk-js@2.0.0-diff-1.0.0.md
├── package.json
├── packages/
│ ├── near-contract-standards/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── ava.config.cjs
│ │ ├── lib/
│ │ │ ├── event.d.ts
│ │ │ ├── event.js
│ │ │ ├── fungible_token/
│ │ │ │ ├── core.d.ts
│ │ │ │ ├── core.js
│ │ │ │ ├── core_impl.d.ts
│ │ │ │ ├── core_impl.js
│ │ │ │ ├── events.d.ts
│ │ │ │ ├── events.js
│ │ │ │ ├── index.d.ts
│ │ │ │ ├── index.js
│ │ │ │ ├── metadata.d.ts
│ │ │ │ ├── metadata.js
│ │ │ │ ├── receiver.d.ts
│ │ │ │ ├── receiver.js
│ │ │ │ ├── resolver.d.ts
│ │ │ │ └── resolver.js
│ │ │ ├── index.d.ts
│ │ │ ├── index.js
│ │ │ ├── non_fungible_token/
│ │ │ │ ├── approval/
│ │ │ │ │ ├── approval_receiver.d.ts
│ │ │ │ │ ├── approval_receiver.js
│ │ │ │ │ ├── index.d.ts
│ │ │ │ │ └── index.js
│ │ │ │ ├── core/
│ │ │ │ │ ├── index.d.ts
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── receiver.d.ts
│ │ │ │ │ ├── receiver.js
│ │ │ │ │ ├── resolver.d.ts
│ │ │ │ │ └── resolver.js
│ │ │ │ ├── enumeration/
│ │ │ │ │ ├── index.d.ts
│ │ │ │ │ └── index.js
│ │ │ │ ├── events.d.ts
│ │ │ │ ├── events.js
│ │ │ │ ├── impl.d.ts
│ │ │ │ ├── impl.js
│ │ │ │ ├── index.d.ts
│ │ │ │ ├── index.js
│ │ │ │ ├── metadata.d.ts
│ │ │ │ ├── metadata.js
│ │ │ │ ├── token.d.ts
│ │ │ │ ├── token.js
│ │ │ │ ├── utils.d.ts
│ │ │ │ └── utils.js
│ │ │ ├── storage_management/
│ │ │ │ ├── index.d.ts
│ │ │ │ └── index.js
│ │ │ ├── util.d.ts
│ │ │ └── util.js
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── event.ts
│ │ │ ├── fungible_token/
│ │ │ │ ├── core.ts
│ │ │ │ ├── core_impl.ts
│ │ │ │ ├── events.ts
│ │ │ │ ├── index.ts
│ │ │ │ ├── metadata.ts
│ │ │ │ ├── receiver.ts
│ │ │ │ └── resolver.ts
│ │ │ ├── index.ts
│ │ │ ├── non_fungible_token/
│ │ │ │ ├── approval/
│ │ │ │ │ ├── approval_receiver.ts
│ │ │ │ │ └── index.ts
│ │ │ │ ├── core/
│ │ │ │ │ ├── index.ts
│ │ │ │ │ ├── receiver.ts
│ │ │ │ │ └── resolver.ts
│ │ │ │ ├── enumeration/
│ │ │ │ │ └── index.ts
│ │ │ │ ├── events.ts
│ │ │ │ ├── impl.ts
│ │ │ │ ├── index.ts
│ │ │ │ ├── metadata.ts
│ │ │ │ ├── token.ts
│ │ │ │ └── utils.ts
│ │ │ ├── storage_management/
│ │ │ │ └── index.ts
│ │ │ └── util.ts
│ │ └── tsconfig.json
│ └── near-sdk-js/
│ ├── .eslintrc.cjs
│ ├── .prettierignore
│ ├── README.md
│ ├── builder/
│ │ └── builder.c
│ ├── lib/
│ │ ├── api.d.ts
│ │ ├── api.js
│ │ ├── cli/
│ │ │ ├── abi.d.ts
│ │ │ ├── abi.js
│ │ │ ├── build-tools/
│ │ │ │ ├── include-bytes.d.ts
│ │ │ │ ├── include-bytes.js
│ │ │ │ ├── near-bindgen-exporter.d.ts
│ │ │ │ └── near-bindgen-exporter.js
│ │ │ ├── cli.d.ts
│ │ │ ├── cli.js
│ │ │ ├── post-install.d.ts
│ │ │ ├── post-install.js
│ │ │ ├── utils.d.ts
│ │ │ └── utils.js
│ │ ├── collections/
│ │ │ ├── index.d.ts
│ │ │ ├── index.js
│ │ │ ├── lookup-map.d.ts
│ │ │ ├── lookup-map.js
│ │ │ ├── lookup-set.d.ts
│ │ │ ├── lookup-set.js
│ │ │ ├── subtype.d.ts
│ │ │ ├── subtype.js
│ │ │ ├── unordered-map.d.ts
│ │ │ ├── unordered-map.js
│ │ │ ├── unordered-set.d.ts
│ │ │ ├── unordered-set.js
│ │ │ ├── vector.d.ts
│ │ │ └── vector.js
│ │ ├── index.d.ts
│ │ ├── index.js
│ │ ├── near-bindgen.d.ts
│ │ ├── near-bindgen.js
│ │ ├── promise.d.ts
│ │ ├── promise.js
│ │ ├── types/
│ │ │ ├── account_id.d.ts
│ │ │ ├── account_id.js
│ │ │ ├── collections.d.ts
│ │ │ ├── collections.js
│ │ │ ├── gas.d.ts
│ │ │ ├── gas.js
│ │ │ ├── index.d.ts
│ │ │ ├── index.js
│ │ │ ├── primitives.d.ts
│ │ │ ├── primitives.js
│ │ │ ├── public_key.d.ts
│ │ │ ├── public_key.js
│ │ │ ├── vm_types.d.ts
│ │ │ └── vm_types.js
│ │ ├── utils.d.ts
│ │ ├── utils.js
│ │ ├── version.d.ts
│ │ └── version.js
│ ├── package.json
│ ├── src/
│ │ ├── api.ts
│ │ ├── cli/
│ │ │ ├── abi.ts
│ │ │ ├── build-tools/
│ │ │ │ ├── include-bytes.ts
│ │ │ │ └── near-bindgen-exporter.ts
│ │ │ ├── cli.ts
│ │ │ ├── post-install.ts
│ │ │ └── utils.ts
│ │ ├── collections/
│ │ │ ├── index.ts
│ │ │ ├── lookup-map.ts
│ │ │ ├── lookup-set.ts
│ │ │ ├── subtype.ts
│ │ │ ├── unordered-map.ts
│ │ │ ├── unordered-set.ts
│ │ │ └── vector.ts
│ │ ├── index.ts
│ │ ├── near-bindgen.ts
│ │ ├── promise.ts
│ │ ├── types/
│ │ │ ├── account_id.ts
│ │ │ ├── collections.ts
│ │ │ ├── gas.ts
│ │ │ ├── index.ts
│ │ │ ├── primitives.ts
│ │ │ ├── public_key.ts
│ │ │ └── vm_types.ts
│ │ ├── utils.ts
│ │ └── version.ts
│ ├── tsconfig.json
│ └── typedoc.json
├── pnpm-workspace.yaml
├── tests/
│ ├── .gitignore
│ ├── README.md
│ ├── __tests__/
│ │ ├── abi/
│ │ │ ├── abi.ava.js
│ │ │ ├── testcases/
│ │ │ │ ├── json_schema.ts
│ │ │ │ ├── modifiers.ts
│ │ │ │ ├── return.ts
│ │ │ │ └── simple_function.ts
│ │ │ └── util.js
│ │ ├── bytes.ava.js
│ │ ├── constructor_validation.ava.js
│ │ ├── decorators/
│ │ │ ├── migrate.ava.js
│ │ │ ├── near_bindgen.ava.js
│ │ │ ├── payable.ava.js
│ │ │ └── private.ava.js
│ │ ├── function-params.ava.js
│ │ ├── lookup-map.ava.js
│ │ ├── lookup-set.ava.js
│ │ ├── test-bigint-serialization.ava.js
│ │ ├── test-date-serialization.ava.js
│ │ ├── test-middlewares.ava.js
│ │ ├── test-public-key.ava.js
│ │ ├── test_alt_bn128_api.ava.js
│ │ ├── test_context_api.ava.js
│ │ ├── test_highlevel_promise.ava.js
│ │ ├── test_log_panic_api.ava.js
│ │ ├── test_math_api.ava.js
│ │ ├── test_promise_api.ava.js
│ │ ├── test_storage_api.ava.js
│ │ ├── typescript.ava.js
│ │ ├── unordered-map.ava.js
│ │ ├── unordered-set.ava.js
│ │ └── vector.ava.js
│ ├── ava.config.cjs
│ ├── jsconfig.json
│ ├── package.json
│ ├── src/
│ │ ├── alt_bn128_api.js
│ │ ├── bigint-serialization.ts
│ │ ├── bytes.js
│ │ ├── constructor-validation/
│ │ │ ├── 1-parameter-not-set-in-constructor.ts
│ │ │ ├── all-parameters-set-in-constructor.ts
│ │ │ ├── no-constructor.ts
│ │ │ └── no-parameters-set-in-constructor.ts
│ │ ├── context_api.js
│ │ ├── date-serialization.ts
│ │ ├── decorators/
│ │ │ ├── payable.ts
│ │ │ ├── private.ts
│ │ │ ├── require_init_false.ts
│ │ │ └── require_init_true.ts
│ │ ├── function-params.js
│ │ ├── highlevel-promise.js
│ │ ├── log_panic_api.js
│ │ ├── lookup-map.js
│ │ ├── lookup-set.js
│ │ ├── math_api.js
│ │ ├── middlewares.ts
│ │ ├── migrate.ts
│ │ ├── model.js
│ │ ├── promise_api.js
│ │ ├── promise_batch_api.js
│ │ ├── public-key.js
│ │ ├── storage_api.js
│ │ ├── typescript.ts
│ │ ├── unordered-map.js
│ │ ├── unordered-set.js
│ │ └── vector.js
│ └── tsconfig.json
├── turbo.json
└── typedoc.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
pnpm-lock.yaml linguist-generated=true -diff
/**/lib/**/*.js linguist-generated=true -diff
/**/lib/**/*.d.ts linguist-generated=true -diff
near-contract-standards/lib/**/*.js linguist-generated=true -diff
near-contract-standards/lib/**/*.d.ts linguist-generated=true -diff
================================================
FILE: .github/ISSUE_TEMPLATE/bug.yml
================================================
name: Bug Report
description: Submit a bug report to help us improve
labels: [bug, 'status: needs triage']
body:
- type: markdown
attributes:
value: |
Before filing your issue, ask yourself:
- Is this clearly a NEAR JavaScript SDK defect?
- Do I have basic ideas about where it goes wrong? (For example, if there are stack traces, are they pointing to one file?)
**Please don't use issues for just questions**. For support please use [GitHub discussions](https://github.com/near/near-sdk-js/discussions).
The quickest way to verify whether it's a NEAR JavaScript SDK defect is through a **reproduction**, starting with a fresh project and making changes until the bug is reproduced.
- type: checkboxes
attributes:
label: Prerequisites
description: Please check the following items before creating a issue, these are basic sanity checks to make sure that the problem isn't something too obvious.
options:
- label: I'm using the latest version of `near-sdk-js`.
required: true
- label: I have tried to start with a fresh project and reproduce the defect with minimal code changes.
- label: I have read the console error messages carefully (if applicable).
- type: textarea
attributes:
label: Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: input
attributes:
label: Reproducible demo
description: |
(Optional) Paste the link to an example repo.
- type: textarea
attributes:
label: Steps to reproduce
description: Write down the steps to reproduce the bug.
placeholder: |
1. Step 1...
2. Step 2...
3. Step 3...
validations:
required: true
- type: textarea
attributes:
label: Expected behavior
description: |
How did you expect your project to behave? If you’re unsure, write down what you thought would happen.
placeholder: Write what you thought would happen.
validations:
required: true
- type: textarea
attributes:
label: Actual behavior
description: |
Did something go wrong? Is something broken, or not behaving as you expected?
Describe this section in detail. Please submit complete log messages with the stack traces.
placeholder: Write what happened with any error messages.
validations:
required: true
- type: textarea
attributes:
label: Your environment
description: Include as many relevant details about the environment you experienced the bug in.
value: |
- NEAR JavaScript SDK version used:
- Relevant dependencies (if applicable):
- type: checkboxes
attributes:
label: Self-service
description: |
If you feel like you could contribute to this issue, please check the box below.
If you do check this box, please send a pull request within 7 days so we can still delegate this to someone else.
options:
- label: I'd be willing to fix this bug myself.
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: 🚀 Feature request & ❓ Questions
url: https://github.com/near/near-sdk-js/discussions
about: Use GitHub discussions for feature requests and questions.
================================================
FILE: .github/ISSUE_TEMPLATE/feature.yml
================================================
name: Feature design / RFC
description: Submit a detailed feature request with a concrete proposal, including an exhaustive API design
labels: [ feature, 'status: needs triage' ]
body:
- type: markdown
attributes:
value: |
Important things:
- This is for feature request including a real API design, not just a basic idea.
- The design does not have to be perfect, we'll discuss it if needed.
- For a more "casual" feature request, consider using GitHub Discussions instead: https://github.com/near/near-sdk-js/discussions/categories/ideas
- type: checkboxes
attributes:
label: Have you read the Contributing Guidelines?
options:
- label: I have read the [Contributing Guidelines on issues](https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md).
required: true
- type: textarea
attributes:
label: Description
description: A clear and concise description of what the feature is.
validations:
required: true
- type: input
attributes:
label: Has this been requested on GitHub Discussions?
description: Please post the [GitHub Discussions](https://github.com/near/near-sdk-js/discussions/categories/ideas) link, it is helpful to see how much interest there is for this feature.
- type: textarea
attributes:
label: Motivation
description: Please outline the motivation for the proposal and why it should be implemented.
validations:
required: true
- type: textarea
attributes:
label: API design
description: |
Please describe how users will use this feature.
Please explain in an exhaustive way what are the config options and their respective effects.
> **What happens if you skip this step?** This issue may be closed without any in-depth discussion. Your feature request is just an idea for now, please use GitHub Discussions for that: https://github.com/near/near-sdk-js/discussions/categories/ideas
- type: checkboxes
attributes:
label: Self-service
description: |
If you feel like you could contribute to this issue, please check the box below.
If you do check this box, please send a pull request within 7 days so we can still delegate this to someone else.
Note that for feature issues, we still require you to fully fill out this form and reach consensus with the maintainers on API design before rushing to implement it, so that you don't waste your time.
options:
- label: I'd be willing to contribute and develop this feature myself.
================================================
FILE: .github/pull_request_template.md
================================================
<!--
Thank you for sending the PR! We appreciate you spending the time to work on these changes.
You can learn more about contributing to NEAR JavaScript SDK here: https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md
Happy contributing!
-->
## Pre-flight checklist
- [ ] I have read the [Contributing Guidelines on pull requests](https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md).
- [ ] Commit messages follow the [conventional commits](https://www.conventionalcommits.org/) spec
- [ ] **If this is a code change**: I have written unit tests.
- [ ] **If this is a new API or substantial change**: the PR has an accompanying issue (closes #0000) and the maintainers have approved on my working plan.
## Motivation
<!-- Help us understand your motivation by explaining why you decided to make this change. Does this fix a bug? Does it close an issue? -->
## Test Plan
<!-- Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. -->
## Related issues/PRs
<!-- If you haven't already, link to issues/PRs that are related to this change. This helps us develop the context and keep a rich repo history. If this PR is a continuation of a past PR's work, link to that PR. If the PR addresses part of the problem in a meta-issue, mention that issue. -->
================================================
FILE: .github/workflows/add-to-devtools.yml
================================================
name: 'Add to DevTools Project'
on:
issues:
types:
- opened
- reopened
pull_request_target:
types:
- opened
- reopened
jobs:
add-to-project:
name: Add issue/PR to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.0
with:
# add to DevTools Project #156
project-url: https://github.com/orgs/near/projects/156
github-token: ${{ secrets.PROJECT_GH_TOKEN }}
================================================
FILE: .github/workflows/tests.yml
================================================
name: Test
on:
pull_request:
push:
branches:
- master
- develop
jobs:
tests:
strategy:
matrix:
platform: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: pnpm
- name: Install dependencies
run: pnpm install
- name: Lint code
run: pnpm lint
- name: Format code
run: pnpm format
- name: Run git status
run: git status
- name: Check that lints where commited
run: test -z "$(git status --porcelain)"
- name: Build
run: pnpm build
- name: Check that all build artifacts where commited
run: test -z "$(git status --porcelain)"
- name: Run tests
run: export NEAR_WORKSPACES_DEBUG=true && pnpm test
================================================
FILE: .github/workflows/typedoc-generate-gitbook-docs.yml
================================================
name: Deploy TypeDoc to GitBook
on:
push:
branches:
- develop
env:
NODE_VERSION: 18.x
ENTRY_FILE: "packages"
CONFIG_PATH: "tsconfig.base.json"
USES_PNPM: "true"
jobs:
deploy:
concurrency: ci-${{ github.ref }}
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[skip ci]')"
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Build project
run: pnpm build
- name: Build documentation
run: pnpm docs:generate-markdown
- name: Deploy to GitBook
run: |
git clone --branch=git-book https://frol:${{ secrets.MY_GITHUB_TOKEN }}@github.com/near/near-sdk-js.git book
rsync -av --delete --exclude=.git markdown-docs/ book/
cd book
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git add .
git commit -m "Update documentation [skip ci]"
git push https://frol:${{ secrets.MY_GITHUB_TOKEN }}@github.com/near/near-sdk-js.git git-book
================================================
FILE: .github/workflows/typedoc-generator.yml
================================================
name: Deploy TypeDoc on GitHub pages
on:
push:
branches:
develop
env:
NODE_VERSION: 18.x
ENTRY_FILE: 'packages'
CONFIG_PATH: 'tsconfig.base.json'
USES_PNPM: 'true'
jobs:
deploy:
concurrency: ci-${{ github.ref }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 7
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Build project
run: pnpm build
- name: Build documentation
run: pnpm docs:generate
- name: Deploy to GitHub pages
uses: JamesIves/github-pages-deploy-action@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: gh-pages
folder: docs
clean: true
================================================
FILE: .gitignore
================================================
node_modules
vendor
.idea
deps
.turbo
yarn.lock
package-lock.json
================================================
FILE: .npmrc
================================================
save-exact=true
================================================
FILE: AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md
================================================
# JSON Schemas for Automatic Decoding of the State
A limitation that we early detected in the `near-sdk-js` is that Classes and Nested Structures (e.g. Vectors of Maps) are valid to declare as attributes of a contract, but hard to correctly deserialize.
This doc explains a new solution currently implemented in the SDK and how to use it to simplify hanlding stored Classes and Nested Structures.
## The Problem
NEAR smart contracts store information in their state, which they read when an execution starts and write when an execution finished. In particular, all the information stored in the contract is (de)serialized as a `utf8` `JSON-String`.
Since Javascript does **not** handle types, it is actually very hard to infer the type of the data that is stored when the contract is loaded at the start of an execution. Imagine for example a contract storing a class `Car` defined as follows:
```typescript
Class Car {
name: string;
speed: number;
run() {
// ...
}
}
```
A particular instance of that Car (e.g. new Car("Audi", 200)) will be stored in the contract as the JSON string:
```json
{"name": "Audi", "speed": 200}
```
Next time the contract is called, the state will be parsed using `JSON.parse()`, and the result will be an `Object {name: "Audi", speed:200}`, which is an instance of `object` and **not an instance of Car**. This would happen both if the user wrote the contract in `javascript` or `typescript`, since casting in `Typescript` is just sugarcoating, it does not actually cast the object! What this means is that:
```js
// the SDK parses the String into an Object
this.car.run() # This will fail!
```
This problem is particularly painful when the class is nested in another Class, e.g. a `LookupMap` of `Cars`.
## The (non-elegant) Solution
Before, the SDK mitigated this problem by requiring the user to manually reconstruct the JS `Object` to an instance of the original class.
## A More Elegant Solution: JSON Schemas
To help the SDK know which type it should decode, we can add a `static schema` map, which tells the SDK what type of data it should read:
```ts
Class Car {
// Schema to (de)serialize
static schema = {
name: "string",
speed: "number",
};
// Properties
name: string;
speed: number;
// methods
run() {
// ...
}
}
```
If a `Class` defines an schema, the SDK will recursively reconstruct it, by creating a new instance of `Car` and filling its attributes with the right values. In this way, the deserialized object will effectively be **an instance of the Class**. This means that we can call all its methods:
```js
// the SDK iteratively reconstructs the Car
this.car.run() # This now works!
```
## The schema format
The Schema supports multiple types:
* Primitive types: `string`, `number`, `boolean`. We can remove schema format of `Primitive types` since is no need to reconstruct them.
* Built-in object types: `Date`, `BigInt`.
* Built-in collections: `array`, `map`
* Arrays need to be declared as `{array: {value: valueType}}`, there are no reconstruct for `Primitive types`, for the value type is `Primitive types`, we can remove this field.
* Maps need to declared as `{map: {key: 'keyType', value: 'valueType'}}`, there are no reconstruct for `Primitive types`, for the key and value type are `Primitive types`, we can remove this field.
* Custom classes are denoted by their name, e.g. `Car`
* Near SDK Collections (i.e. `Vector`, `LookupMap`, `LookupSet`, `UnorderedMap`, `UnorderedSet`) need to be declared as `{class: ClassType, value: ValueType}` if we need to reconstruct value or we can simplify to mark `ClassType` if we no need to reconstruct value for `Primitive types`.
You can see a complete example in the [status-deserialize-class](./examples/src/status-deserialize-class.js) file, which contains the following Class declaration:
```js
export class StatusDeserializeClass {
static schema = {
truck: Truck,
efficient_recordes: UnorderedMap,
nested_efficient_recordes: {class: UnorderedMap, value: UnorderedMap},
nested_lookup_recordes: {class: UnorderedMap, value: LookupMap},
vector_nested_group: {class: Vector, value: LookupMap},
lookup_nest_vec: { class: LookupMap, value: Vector },
unordered_set: UnorderedSet,
user_car_map: {class: UnorderedMap, value: Car },
big_num: 'bigint',
date: 'date'
};
constructor() {
this.is_inited = false;
this.records = {};
this.truck = new Truck();
this.messages = [];
this.efficient_recordes = new UnorderedMap("a");
this.nested_efficient_recordes = new UnorderedMap("b");
this.nested_lookup_recordes = new UnorderedMap("c");
this.vector_nested_group = new Vector("d");
this.lookup_nest_vec = new LookupMap("e");
this.unordered_set = new UnorderedSet("f");
this.user_car_map = new UnorderedMap("g");
this.big_num = 1n;
this.date = new Date();
this.message_without_schema_defined = "";
this.number_without_schema_defined = 0;
this.records_without_schema_defined = {};
}
// other methods
}
```
---
#### What happens with the old `reconstructor`?
Until now, users needed to call a `reconstructor` method in order for **Nested Collections** to be properly decoded:
```typescript
@NearBindgen({})
export class Contract {
outerMap: UnorderedMap<UnorderedMap<string>>;
constructor() {
this.outerMap = new UnorderedMap("o");
}
@view({})
get({id, accountId}: { id: string; accountId: string }) {
const innerMap = this.outerMap.get(id, {
reconstructor: UnorderedMap.reconstruct, // we need to announce reconstructor explicit
});
if (innerMap === null) {
return null;
}
return innerMap.get(accountId);
}
}
```
With schemas, this is no longer needed, as the SDK can correctly infer how to decode the Nested Collections:
```typescript
@NearBindgen({})
export class Contract {
static schema = {
outerMap: {class: UnorderedMap, value: UnorderedMap}
};
outerMap: UnorderedMap<UnorderedMap<string>>;
constructor() {
this.outerMap = new UnorderedMap("o");
}
@view({})
get({id, accountId}: { id: string; accountId: string }) {
const innerMap = this.outerMap.get(id); // reconstructor can be infered from static schema
if (innerMap === null) {
return null;
}
return innerMap.get(accountId);
}
}
```
---
#### How Does the Reconstruction Work?
The `_reconstruct` method in [near-bindgen.ts](./packages/near-sdk-js/src/near-bindgen.ts) will check whether an schema exists in the **contract's class**. If such schema exists, it will try to decode it by invoking `decodeObj2class`:
```typescript
static _reconstruct(classObject: object, plainObject: AnyObject): object {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (classObject.constructor.schema === undefined) {
for (const item in classObject) {
const reconstructor = classObject[item].constructor?.reconstruct;
classObject[item] = reconstructor
? reconstructor(plainObject[item])
: plainObject[item];
}
return classObject;
}
return decodeObj2class(classObject, plainObject);
}
```
================================================
FILE: CODEOWNERS
================================================
* @ailisp @volovyks
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at social@nearprotocol.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Near JavaScript SDK
First off, thanks for taking the time to contribute! We look forward to to your contributions. 🎉
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them.
We take community contributions very seriously, as we understand you invest precious time and effort. That is why we have this guide to set mutual expectations, to avoid unfortunate situation where we can't accept a contribution because it may not fit project's goals, or lacks needed quality standards. There is one important rule to follow - please let us know ahead about what you plan to do, and get an OK from our team so that we can prepare for accepting your contribution.
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
## Table of Contents
- [I Have a Question](#i-have-a-question)
- [Get Involved](#get-involved)
- [Our Development Process](#our-development-process)
- [Development](#development)
- [Pull Requests](#pull-requests)
- [Tests](#tests)
- [What Happens Next?](#what-happens-next)
## I Have a Question
If you want to ask a question please use the following resources available for you:
- [Docs site](https://docs.near.org/sdk/js/introduction)
- Post a question on [GitHub Discussions](https://github.com/near/near-sdk-js/discussions)
- Post a question on [StackOverflow with `[nearprotocol]` tag](https://stackoverflow.com/questions/tagged/nearprotocol)
## Get Involved
There are many ways to contribute to this project, and many of them do not involve writing any code. Here's a few ideas to get started:
- Simply start using the library. Go through the [user guide](https://docs.near.org/sdk/js/introduction). Does everything work as expected? If not, we're always looking for improvements. Let us know on [GitHub Discussions](https://github.com/near/near-sdk-js/discussions).
- Look through the [open issues](https://github.com/near/near-sdk-js/issues). Provide workarounds or ask for clarification.
- If you find an issue you would like to fix, [open a pull request](#pull-requests). Issues tagged as [_Good first issue_](https://github.com/near/near-sdk-js/labels/good_first_issue) are a good place to get started.
- Take a look at the [enhancements requested](https://github.com/near/near-sdk-js/labels/enhancement) by others in the community and consider opening a pull request if you see something you want to work on.
If you think you need help planning your contribution, please ping us on [Discord](https://near.chat) and let us know you are looking for a bit of help.
### Join our Discord Channel
We have the [`#dev-feedback`](https://discord.gg/XKGrd9h9TB) channel on [Discord](https://near.chat) to discuss all things about NEAR development. You can also be of great help by helping other users in the [`#dev-support`](https://discord.gg/Fy4WzwRgun) channel.
### Join our Telegram User Group
You can have near-sdk-js related discussions with other users, contributors and maintainers on [Telegram]( https://t.me/near_sdk_js).
### Triaging Issues and Pull Requests
One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.
You can review code, or ask for more information if you believe the issue does not provide all the details required to solve it.
## Our Development Process
Our core team works directly in the public repo, and pull requests are checked by the continuous integration system, GitHub actions. There are unit tests and end-to-end tests.
**Branch organization**: This project has one primary branch `develop` and we use feature branches to deliver new features with pull requests.
**Issue templates**: When [opening a new issue](https://github.com/near/near-sdk-js/issues/new/choose), always **make sure to fill out the issue template**. The issue template is very important, as it sets mutual expectations about what you plan to do, and help us prepare to accept your contribution.
**Bugs**: If you would like to report a problem use the [bug report](https://github.com/near/near-sdk-js/issues/new?assignees=&template=bug.yml) issue template.
**Security Bugs**: To report security issues in this project please email [security@near.org](mailto:security@near.org)
**New features and enhancements**:
If you have a casual feature request or proposal, you can raise it in our [GitHub Discussions](https://github.com/near/near-sdk-js/discussions/categories/ideas).
If you'd like to work on a PR with an implementation of your proposal, please file an issue with the [feature template](https://github.com/near/near-sdk-js/issues/new?template=feature.yml) in the form of an **elaborated RFC**. Please wait for our team to respond with an approval before you start working on it, as we can only accept PRs that are aligned with project's goals and roadmap, so we really want to avoid situations where we reject something you worked hard on. (BTW, if you think that project's goals or roadmap should change in some way, do feel free to raise it in [GitHub Discussions](https://github.com/near/near-sdk-js/discussions/) :) and we'll talk about it).
### Claiming issues
We have a list of [beginner-friendly issues](https://github.com/near/near-sdk-js/labels/good_first_issue) to help you get started with the codebase and get familiar with our contribution process. This is a great place to start.
Apart from the `good first issue`, the following labels are also worth looking at:
- [`help wanted`](https://github.com/near/near-sdk-js/labels/help%20wanted): if you have specific knowledge in one domain, working on these issues can make your expertise shine.
- [`accepting pr`](https://github.com/near/near-sdk-js/labels/status%3A%20accepting%20pr): community contributors can feel free to claim any of these.
If you want to work on any of these issues, just drop a message saying "I'd like to work on this", and we will assign the issue to you and update the issue's status as "claimed". **You are expected to send a pull request within seven days** after that, so we can still delegate the issue to someone else if you are unavailable.
## Development
### Online one-click setup for contributing
You can use Gitpod (a free, online, VSCode-like IDE) for contributing. With a single click, it will launch a workspace and automatically:
- clone the repo.
- install the dependencies.
So that you can start contributing straight away.
[](https://gitpod.io/#https://github.com/near/near-sdk-js)
## Pull Requests
We appreciate the time and effort you invested! 🙏 We will do our best to work with you and get the PR looked at.
> Working on your first-ever Pull Request? You can learn how from this free video series:
> [**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
Please make sure the following is done when submitting a pull request:
1. **Keep your PR small.** Small pull requests (~300 lines of diff) are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
2. **Use descriptive titles.** It is recommended to follow semantic commit conventions: https://www.conventionalcommits.org/en/v1.0.0/
3. **Test your changes.** Include unit tests for any public API you touch.
All pull requests should be opened against the `develop` branch.
### Tests
Please include unit tests for any public api you add or touch. We use [AVA](https://github.com/avajs/ava) for tests.
### What Happens Next?
Our team will be monitoring pull requests. Do help us by keeping pull requests consistent by following the guidelines above.
================================================
FILE: LICENSE
================================================
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
================================================
FILE: README.md
================================================
# NEAR JavaScript SDK
<p>
<a href="https://docs.near.org/tools/sdk" target="_blank">
<img alt="Documentation" src="https://img.shields.io/badge/documentation-JS/TS-brightgreen.svg" />
</a>
<a href="https://www.npmjs.com/package/near-sdk-js" target="_blank">
<img alt="Version" src="https://img.shields.io/npm/v/near-sdk-js.svg">
</a>
<img src="https://img.shields.io/badge/node-%3E%3D14%20%3C16.6.0%20%7C%7C%20%3E16.6.0-blue.svg" />
<a href="https://github.com/near/near-sdk-js/blob/develop/LICENSE" target="_blank">
<img alt="License: LICENSE" src="https://img.shields.io/badge/License-MIT-yellow.svg" />
</a>
<a href="https://github.com/near/near-sdk-js/blob/develop/LICENSE-APACHE" target="_blank">
<img alt="License: LICENSE" src="https://img.shields.io/badge/License-Apache-yellow.svg" />
</a>
</p>
A JavaScript library for writing NEAR smart contracts.
```typescript
import { NearBindgen, near, call, view } from 'near-sdk-js';
@NearBindgen({})
class HelloNear {
greeting: string = 'Hello';
@view({}) // This method is read-only and can be called for free
get_greeting(): string {
return this.greeting;
}
@call({}) // This method changes the state, for which it cost gas
set_greeting({ greeting }: { greeting: string }): void {
near.log(`Saving greeting ${greeting}`);
this.greeting = greeting;
}
}
```
See more in the [Anatomy of a Contract](https://docs.near.org/build/smart-contracts/anatomy/).
## 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)
- Find [source code examples](https://github.com/near/near-sdk-js/tree/develop/examples) with common use cases
- Lookup available features in [API reference](https://near.github.io/near-sdk-js/)
- 🏠 Learn more about NEAR on our [Documentation website](https://docs.near.org/)
- Breaking features diff from [SDK 2.0.0 to 1.0.0](https://github.com/near/near-sdk-js/tree/develop/near-sdk-js@2.0.0-diff-1.0.0.md)
## Prerequisites
- node >=14 <16.6.0 || >16.6.0
- pnpm >=7
## Quick Start
Use [`create-near-app`](https://github.com/near/create-near-app) to quickly get started writing smart contracts in JavaScript on NEAR.
npx create-near-app
This will scaffold a basic template for you 😎
## Contributing
If you are interested in contributing, please look at the [contributing guidelines](https://github.com/near/near-sdk-js/tree/develop/CONTRIBUTING.md).
- [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞
- [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡
- [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪
## License
This repository is distributed under the terms of both the [MIT license](https://github.com/near/near-sdk-js/blob/develop/LICENSE) and the [Apache License](https://github.com/near/near-sdk-js/blob/develop/LICENSE-APACHE) (Version 2.0).
See [LICENSE](https://github.com/near/near-sdk-js/tree/develop/LICENSE) and [LICENSE-APACHE](https://github.com/near/near-sdk-js/tree/develop/LICENSE-APACHE) for details.
================================================
FILE: RELEASE.md
================================================
# Release
This document describes step to do a new pre-release or formal release.
## Release Requirement
- A formal release must be directly bump from a tested, DevRel Team approved pre-release, with no commits other than bump the version.
- Pre-release can come with arbitrary commits to fix packaging and update documentations. Several pre-release can be released before a formal release to fix issues and address feedbacks.
## Steps for pre-release
1. Create a new branch for the release.
2. Bump version in packages/near-sdk-js/package.json and packages/near-contract-standards/package.json to the version about to release. It should be `x.y.z-0`, and next pre-release `x.y.z-1`, etc.
3. Run `pnpm publish` in packages/near-sdk-js and in packages/near-contract-standards.
4. Copy examples folder in this repo to another place, drop `node_modules`, change its package.json from:
```
"near-contract-standards": "workspace:*",
"near-sdk-js": "workspace:*",
```
to the version you just released, e.g. `x.y.z-1`.
5. Build and run example tests to ensure the packaging is correct.
6. If it works, go to https://github.com/near/near-sdk-js/releases/new, create a tag for the new release from the branch you created in step 1, and write the release highlights.
7. Ask the DevRel team to test the pre-release.
## Steps for formal release
1. Create a new release branch from the candidate pre-release branch
2. Bump version in packages/near-sdk-js/package.json and packages/near-contract-standards/package.json to the version about to release. It should be `x.y.z`.
3. Run `pnpm publish` in packages/near-sdk-js and in packages/near-contract-standards.
4. Go to https://github.com/near/near-sdk-js/releases/new, create a tag for the new release branch from the branch you created in step 1, and copy the highlights from latest pre-release candidate.
5. Advertise it to the community!
================================================
FILE: RUNTIME_INVESTIGATE.md
================================================
# Runtime Investigate
Investigate how to compile js/ts to wasm by any tools, and the output wasm file can be executed on wasm runtime in [nearcore](https://github.com/near/nearcore)
## Table of Contents
- [quickjs](#quickjs)
- [hermes](#hermes)
- [wasmnizer-ts](#wasmnizer-ts)
### quickjs
:white_check_mark: Currently our near-sdk-js use [quickjs engine](https://bellard.org/quickjs/) to compile js->C/C++->wasm.
### hermes
:x: We can't find any tools to compile [hermes engine](https://github.com/facebook/hermes) and it's api to C/C++ or wasm directly. Hermes is not support to execute wasm.
### wasmnizer-ts
:x: [Wasmnizer-ts](https://github.com/intel/Wasmnizer-ts) implements the [WasmGC proposal](https://github.com/WebAssembly/gc), but wasm runtime in nearcore doesn't support it.
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Reporting a Vulnerability
To report security issues in this project please send an email to [security@near.org](mailto:security@near.org)
================================================
FILE: TOOLING.md
================================================
# Tooling
This document describes at a high level some the key tools used across `near-js`.
## Package Manager - [PNPM](https://pnpm.io/)
PNPM is a package manager focused on fast installations while still being disk efficient. It manages dependency installations across the monorepo as well as linking interdependent packages. Unlike other package managers, PNPM creates a non-flat `node_modules` structure which ensures packages only have access to dependencies defined in their `package.json`.
## Build System - [Turborepo](https://turborepo.org/)
Turborepo provides tooling for orchestrating commands across the monorepo. Similar to Yarn Workspaces, Turborepo can run tasks within each project via a single command, but rather than executing serially, Turborepo has various performance enhancing features such as task parallelization and local/remote caching.
## Automation - [GitHub Actions](https://github.com/features/actions)
Github Actions is used to automate various tasks including PR checks (linting, type checks, and tests).
================================================
FILE: benchmark/.gitignore
================================================
build
================================================
FILE: benchmark/README.md
================================================
# Gas and size benchmark compare to NEAR-SDK-RS
## Summary
NEAR-SDK-JS bundles a bytecode VM with the contract bytecode to a wasm file. Currently, the bytecode VM is the QuickJS runtime with interface to NEAR and the contract bytecode is compiled from JavaScript source code with QuickJS Compiler (QJSC).
This results in:
- Size of a minimal contract is 500K, which is also the size of the bytecode VM.
- Bytecode is more compact than wasm. Complex contract in JS adds less bytes to the equivalent wasm compiled from Rust, but due to the initial 500K size, the result contract is still bigger and within same order of magnitude: several hundred KB.
- For contract that bottlenecks at calling the host functions are using similar gas in JS and Rust.
- For contract that does a lot of computation in JS, the JS bytecode uses significantly more gas.
- For a real world contract, if it doesn't including complex logic in JavaScript, it's usually sufficient, consider the complexity of the near contract standards.
- For more complex logic, We suggest to bench the most expensive contract call, including most complex path of cross contract calls, to determine whether it fits 300T Gas limit.
## Detailed gas benchmark
### A minimal contract
- RS lowlevel minimal contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 2.43T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.00005T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 5.08T
- JS lowlevel minimal contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 7.07T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11132T
- WASM_INSTRUCTION : 4.53T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 9.72T
In the very minimal contract the JS adds about `1.8T` gas. The major difference is loading the QuickJS VM and near-sdk-js uses 4.53T Gas. The 500K contract loading just adds 0.1T Gas.
### A highlevel minimal contract (using nearbindgen)
- highlevel-minimal.ava › RS highlevel minimal contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 2.63T
- BASE : 0.79G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 35.46G
- READ_CACHED_TRIE_NODE : 4.56G
- READ_MEMORY_BASE : 7.83G
- READ_MEMORY_BYTE : 0.04G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- TOUCHING_TRIE_NODE : 32.2G
- WASM_INSTRUCTION : 0.46G
- WRITE_MEMORY_BASE : 2.8G
- WRITE_MEMORY_BYTE : 0.04G
- Gas used to refund unused gas: 223.18G
- Total gas used: 5.28T
- highlevel-minimal.ava › JS highlevel minimal contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 8.39T
- BASE : 1.59G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 112.03G
- READ_CACHED_TRIE_NODE : 6.84G
- READ_MEMORY_BASE : 7.83G
- READ_MEMORY_BYTE : 0.05G
- READ_REGISTER_BASE : 2.52G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- STORAGE_WRITE_VALUE_BYTE : 0.06G
- TOUCHING_TRIE_NODE : 48.31G
- WASM_INSTRUCTION : 5.66T
- WRITE_MEMORY_BASE : 5.61G
- WRITE_MEMORY_BYTE : 0.05G
- WRITE_REGISTER_BASE : 2.87G
- WRITE_REGISTER_BYTE : 0.01G
- Gas used to refund unused gas: 223.18G
- Total gas used: 11.05T
JS `@NearBindgen` is more expensive, the major difference is in `WASM_INSTRUCTION`, because `@NearBindgen` does some class, object manipulation work, but Rust `near_bindgen` is a compile time code generation macro. Deduct the 4.5T loading VM and near-sdk-js, it's about 1T gas overhead.
### Low level API
- RS lowlevel API contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 2.53T
- BASE : 0.00026T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.00008T
- READ_MEMORY_BASE : 0.00522T
- READ_MEMORY_BYTE : 0.00008T
- STORAGE_WRITE_BASE : 0.0642T
- STORAGE_WRITE_KEY_BYTE : 0.0007T
- STORAGE_WRITE_VALUE_BYTE : 0.00031T
- TOUCHING_TRIE_NODE : 0.0322T
- WASM_INSTRUCTION : 0.00002T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 5.18T
- JS lowlevel API contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 7.8T
- BASE : 0.00026T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11119T
- READ_MEMORY_BASE : 0.00522T
- READ_MEMORY_BYTE : 0.00008T
- STORAGE_WRITE_BASE : 0.0642T
- STORAGE_WRITE_EVICTED_BYTE : 0.00032T
- STORAGE_WRITE_KEY_BYTE : 0.0007T
- STORAGE_WRITE_VALUE_BYTE : 0.00031T
- TOUCHING_TRIE_NODE : 0.09661T
- WASM_INSTRUCTION : 5.09T
- WRITE_REGISTER_BASE : 0.00287T
- WRITE_REGISTER_BYTE : 0.00004T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 10.45T
- JS lowlevel API contract, call many
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 8.47T
- BASE : 0.00265T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11119T
- READ_MEMORY_BASE : 0.0522T
- READ_MEMORY_BYTE : 0.00076T
- STORAGE_WRITE_BASE : 0.64197T
- STORAGE_WRITE_EVICTED_BYTE : 0.00289T
- STORAGE_WRITE_KEY_BYTE : 0.00705T
- STORAGE_WRITE_VALUE_BYTE : 0.0031T
- TOUCHING_TRIE_NODE : 0.04831T
- WASM_INSTRUCTION : 5.14T
- WRITE_REGISTER_BASE : 0.02579T
- WRITE_REGISTER_BYTE : 0.00034T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 11.12T
In this case, JS lowlevel API contract uses same gas in the storage write API part (`STORAGE_WRITE_BASE` / `STORAGE_WRITE_KEY_BYTE` / `STORAGE_WRITE_VALUE_BYTE` ). The major excessive gas is due to the overhead of initialize QuickJS VM and loading near-sdk-js. We can see this more obviously by calling storage write for 10 times ("call many tests" in above).
### Highlevel collection
- RS highlevel collection contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 3.32T
- BASE : 3.18G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 70.94G
- READ_CACHED_TRIE_NODE : 95.76G
- READ_MEMORY_BASE : 26.1G
- READ_MEMORY_BYTE : 1.87G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0.03G
- STORAGE_READ_BASE : 112.71G
- STORAGE_READ_KEY_BYTE : 3.44G
- STORAGE_READ_VALUE_BYTE : 0.19G
- STORAGE_WRITE_BASE : 256.79G
- STORAGE_WRITE_EVICTED_BYTE : 1.09G
- STORAGE_WRITE_KEY_BYTE : 9.23G
- STORAGE_WRITE_VALUE_BYTE : 7.75G
- TOUCHING_TRIE_NODE : 257.63G
- WASM_INSTRUCTION : 16.36G
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.74G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 1.1G
- Gas used to refund unused gas: 223.18G
- Total gas used: 5.97T
- JS highlevel collection contract
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 10.06T
- BASE : 2.91G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 113.46G
- READ_CACHED_TRIE_NODE : 72.96G
- READ_MEMORY_BASE : 20.88G
- READ_MEMORY_BYTE : 2G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0.03G
- STORAGE_READ_BASE : 112.71G
- STORAGE_READ_KEY_BYTE : 3.31G
- STORAGE_READ_VALUE_BYTE : 0.53G
- STORAGE_WRITE_BASE : 192.59G
- STORAGE_WRITE_EVICTED_BYTE : 3.02G
- STORAGE_WRITE_KEY_BYTE : 7.96G
- STORAGE_WRITE_VALUE_BYTE : 9.49G
- TOUCHING_TRIE_NODE : 209.33G
- WASM_INSTRUCTION : 6.86T
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.9G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 1.55G
- Gas used to refund unused gas: 223.18G
- Total gas used: 12.71T
JS SDK's collection has about 1T overhead, deduct the 4.5T VM/near-sdk-js loading and 1T `@NearBindgen`. Note this benches the most complicated `UnorderedMap`, which gas usage is strictly greater than the other collections. And the gas used in actual writing the collection to storage is similar (`STORAGE_WRITE_BASE` / `STORAGE_WRITE_KEY_BYTE` / `STORAGE_WRITE_VALUE_BYTE` ).
### Computational expensive contract
- JS expensive contract, iterate 20000 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 123.26T
- BASE : 1.85G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 112.09G
- READ_CACHED_TRIE_NODE : 4.56G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.07G
- READ_REGISTER_BASE : 2.52G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- STORAGE_WRITE_VALUE_BYTE : 0.06G
- TOUCHING_TRIE_NODE : 32.2G
- WASM_INSTRUCTION : 120.54T
- WRITE_MEMORY_BASE : 5.61G
- WRITE_MEMORY_BYTE : 0.07G
- WRITE_REGISTER_BASE : 2.87G
- WRITE_REGISTER_BYTE : 0.04G
- Gas used to refund unused gas: 223.18G
- Total gas used: 125.91T
- RS expensive contract. iterate 20000 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 3.01T
- BASE : 1.85G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 67.77G
- READ_CACHED_TRIE_NODE : 6.84G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.06G
- READ_REGISTER_BASE : 2.52G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- TOUCHING_TRIE_NODE : 48.31G
- WASM_INSTRUCTION : 315.17G
- WRITE_MEMORY_BASE : 5.61G
- WRITE_MEMORY_BYTE : 0.07G
- WRITE_REGISTER_BASE : 2.87G
- WRITE_REGISTER_BYTE : 0.04G
- Gas used to refund unused gas: 223.18G
- Total gas used: 5.66T
- RS expensive contract. iterate 10000 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 2.9T
- BASE : 2.38G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 67.77G
- READ_CACHED_TRIE_NODE : 13.68G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.06G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- TOUCHING_TRIE_NODE : 80.51G
- WASM_INSTRUCTION : 158.89G
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.07G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 0.04G
- Gas used to refund unused gas: 223.18G
- Total gas used: 5.56T
- RS expensive contract. iterate 100 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 2.75T
- BASE : 2.38G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 67.77G
- READ_CACHED_TRIE_NODE : 13.68G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.05G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- TOUCHING_TRIE_NODE : 80.51G
- WASM_INSTRUCTION : 4.02G
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.07G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 0.03G
- Gas used to refund unused gas: 223.18G
- Total gas used: 5.4T
- JS expensive contract, iterate 100 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 9.09T
- BASE : 2.38G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 112.09G
- READ_CACHED_TRIE_NODE : 13.68G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.06G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_READ_VALUE_BYTE : 0.01G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_EVICTED_BYTE : 0.06G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- STORAGE_WRITE_VALUE_BYTE : 0.06G
- TOUCHING_TRIE_NODE : 80.51G
- WASM_INSTRUCTION : 6.3T
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.07G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 0.05G
- Gas used to refund unused gas: 223.18G
- Total gas used: 11.75T
- JS expensive contract, iterate 10000 times
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 65.94T
- BASE : 2.38G
- CONTRACT_LOADING_BASE : 0.04G
- CONTRACT_LOADING_BYTES : 112.09G
- READ_CACHED_TRIE_NODE : 13.68G
- READ_MEMORY_BASE : 10.44G
- READ_MEMORY_BYTE : 0.06G
- READ_REGISTER_BASE : 5.03G
- READ_REGISTER_BYTE : 0G
- STORAGE_READ_BASE : 56.36G
- STORAGE_READ_KEY_BYTE : 0.15G
- STORAGE_READ_VALUE_BYTE : 0.01G
- STORAGE_WRITE_BASE : 64.2G
- STORAGE_WRITE_EVICTED_BYTE : 0.06G
- STORAGE_WRITE_KEY_BYTE : 0.35G
- STORAGE_WRITE_VALUE_BYTE : 0.06G
- TOUCHING_TRIE_NODE : 80.51G
- WASM_INSTRUCTION : 63.15T
- WRITE_MEMORY_BASE : 8.41G
- WRITE_MEMORY_BYTE : 0.08G
- WRITE_REGISTER_BASE : 8.6G
- WRITE_REGISTER_BYTE : 0.06G
- Gas used to refund unused gas: 223.18G
- Total gas used: 68.59T
In this case, JS uses much more gas. Because JS Number is object and that's a lot of overhead compare to native integer arithmetic. It's even a lot of overhead compare to native float arithmetic. Also in QuickJS there's no JIT. If your contract does a lot of calculation or complex algorithm in JavaScript, it'd be better to do a similar benchmark.
### Deploy and cross contract call
- JS promise batch deploy contract and call
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 25.86T
- CREATE_ACCOUNT : 0.09961T
- DEPLOY_CONTRACT : 3.71T
- FUNCTION_CALL : 2.32T
- NEW_RECEIPT : 0.10806T
- TRANSFER : 0.11512T
- BASE : 0.00159T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.22386T
- PROMISE_RETURN : 0.00056T
- READ_MEMORY_BASE : 0.01566T
- READ_MEMORY_BYTE : 1.97T
- UTF8_DECODING_BASE : 0.00311T
- UTF8_DECODING_BYTE : 0.00525T
- WASM_INSTRUCTION : 14.86T
- Gas used to execute the cross contract call: 41.9T
- BASE : 0.00344T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11228T
- READ_MEMORY_BASE : 0.00261T
- READ_MEMORY_BYTE : 0.0005T
- READ_REGISTER_BASE : 0.01007T
- READ_REGISTER_BYTE : 0T
- WASM_INSTRUCTION : 5.47T
- WRITE_MEMORY_BASE : 0.01122T
- WRITE_MEMORY_BYTE : 0.00014T
- WRITE_REGISTER_BASE : 0.01146T
- WRITE_REGISTER_BYTE : 0.00019T
- Gas used to refund unused gas for cross contract call: 0.22318T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 70.63T
- RS promise batch deploy contract and call
- Gas used to convert transaction to receipt: 2.43T
- Gas used to execute the receipt (actual contract call): 10.89T
- CREATE_ACCOUNT : 0.09961T
- DEPLOY_CONTRACT : 3.71T
- FUNCTION_CALL : 2.32T
- NEW_RECEIPT : 0.10806T
- TRANSFER : 0.11512T
- BASE : 0.00159T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11283T
- PROMISE_RETURN : 0.00056T
- READ_MEMORY_BASE : 0.01566T
- READ_MEMORY_BYTE : 1.97T
- UTF8_DECODING_BASE : 0.00311T
- UTF8_DECODING_BYTE : 0.00525T
- WASM_INSTRUCTION : 0.00038T
- Gas used to execute the cross contract call: 41.9T
- BASE : 0.00344T
- CONTRACT_LOADING_BASE : 0.00004T
- CONTRACT_LOADING_BYTES : 0.11228T
- READ_MEMORY_BASE : 0.00261T
- READ_MEMORY_BYTE : 0.0005T
- READ_REGISTER_BASE : 0.01007T
- READ_REGISTER_BYTE : 0T
- WASM_INSTRUCTION : 5.47T
- WRITE_MEMORY_BASE : 0.01122T
- WRITE_MEMORY_BYTE : 0.00014T
- WRITE_REGISTER_BASE : 0.01146T
- WRITE_REGISTER_BYTE : 0.00019T
- Gas used to refund unused gas for cross contract call: 0.22318T
- Gas used to refund unused gas: 0.22318T
- Total gas used: 55.67T
In this test, we use a JS contract and RS contract to both deploy a JS contract and cross contract call this newly deployed contract. We can see the gas to do the cross contract call is the same. JS SDK has a `~10T` overhead to parse a `~500K` contract in byte. This is because JS, either represent code in Uint8Array or string has some overhead while rust compiler can directly turn it into data section in wasm. In practice, a 10T overhead for a one time contract deploy is not a big deal.
## Tips to do your own benchmark
If the above cases don't cover use case or you have a complex algorithm to implement in JavaScript, it's a good idea to benchmark your specific algorithm before choose near-sdk-js for your project.
You don't have to implement the exact algorithm to estimate the gas usage. Instead, you can find out the most expensive execution path of the algorithm, and estimate it by using the upper bound. For example, store the biggest possible objects into the collection and iterate for most possible times. Then goes to write the benchmark and the total gas cannot be more than 300T to be a valid contract. Also, if it has cross contract call, make sure the total gas, that's a sum of all cross contract calls, is less than 300T.
To add your benchmark, write a one function contract of your most expensive operation. And write a test to call this function. If it doesn't involve cross contract call or promises, creating such test is simple. You can refer to `bench/src/expensive-calc.js` and `bench/__tests__/test-expensive-calc.ava.js` on how to write such test and print the gas breakdown. If it involves create promises or cross contract calls, printing the gas breakdown is a little bit more complex, you can refer to `bench/__tests__/test-deploy-contract.ava.js` for the recipe.
## Details of size benchmark
### JS Contract
```
-rwxrwxr-x 1 bo bo 1009K Feb 9 10:49 ./build/deploy-contract.wasm
-rwxrwxr-x 1 bo bo 506K Feb 8 12:11 ./build/expensive-calc.wasm
-rwxrwxr-x 1 bo bo 512K Feb 7 15:57 ./build/highlevel-collection.wasm
-rwxrwxr-x 1 bo bo 505K Feb 7 10:53 ./build/highlevel-minimal.wasm
-rwxrwxr-x 1 bo bo 502K Feb 10 11:32 ./build/lowlevel-api.wasm
-rwxrwxr-x 1 bo bo 502K Feb 10 11:47 ./build/lowlevel-minimal.wasm
```
### Rust Contract
```
-rwxrwxr-x 1 bo bo 509K Feb 10 10:02 ./res/deploy_contract.wasm
-rwxrwxr-x 1 bo bo 306K Feb 8 12:18 ./res/expensive_calc.wasm
-rwxrwxr-x 1 bo bo 320K Feb 8 11:26 ./res/highlevel_collection.wasm
-rwxrwxr-x 1 bo bo 160K Feb 7 10:51 ./res/highlevel_minimal.wasm
-rwxrwxr-x 1 bo bo 387 Feb 7 11:56 ./res/lowlevel_api.wasm
-rwxrwxr-x 1 bo bo 219 Feb 7 10:33 ./res/lowlevel_minimal.wasm
```
## Appendix
- Source code of the rust benchmark: https://github.com/near/sdk-rs-gas-benchmark
================================================
FILE: benchmark/__tests__/test-collections-performance.ava.js
================================================
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);
});
================================================
FILE: benchmark/__tests__/test-deploy-contract.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import {
formatGas,
gasBreakdown,
logGasBreakdown,
logGasDetail,
} from "./util.js";
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 contract.
const callerContract = await root.createSubAccount("caller", {
initialBalance: "1000N",
});
await callerContract.deploy("build/deploy-contract.wasm");
const callerContractRs = await root.createSubAccount("callrs", {
initialBalance: "1000N",
});
await callerContractRs.deploy("res/deploy_contract.wasm");
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
callerContract,
ali,
bob,
carl,
callerContractRs,
};
});
test("JS promise batch deploy contract and call", async (t) => {
const { bob, callerContract } = t.context.accounts;
let r = await bob.callRaw(callerContract, "deploy_contract", "", {
gas: "300 Tgas",
});
// console.log(JSON.stringify(r, null, 2));
let deployed = callerContract.getSubAccount("a");
t.deepEqual(JSON.parse(Buffer.from(r.result.status.SuccessValue, "base64")), {
currentAccountId: deployed.accountId,
signerAccountId: bob.accountId,
predecessorAccountId: callerContract.accountId,
input: "abc",
});
t.log(
"Gas used to convert transaction to receipt: ",
formatGas(r.result.transaction_outcome.outcome.gas_burnt)
);
t.log(
"Gas used to execute the receipt (actual contract call): ",
formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)
);
let map = gasBreakdown(r.result.receipts_outcome[0].outcome);
logGasBreakdown(map, t);
t.log(
"Gas used to execute the cross contract call: ",
formatGas(r.result.receipts_outcome[1].outcome.gas_burnt)
);
map = gasBreakdown(r.result.receipts_outcome[1].outcome);
logGasBreakdown(map, t);
t.log(
"Gas used to refund unused gas for cross contract call: ",
formatGas(r.result.receipts_outcome[2].outcome.gas_burnt)
);
t.log(
"Gas used to refund unused gas: ",
// TODO: fix after near-workspaces is updated
formatGas(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)
);
t.log(
"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 +
r.result.receipts_outcome[2].outcome.gas_burnt +
// TODO: fix after near-workspaces is updated
(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)
)
);
});
test("RS promise batch deploy contract and call", async (t) => {
const { bob, callerContractRs } = t.context.accounts;
let r = await bob.callRaw(callerContractRs, "deploy_contract", "", {
gas: "300 Tgas",
});
// console.log(JSON.stringify(r, null, 2));
let deployed = callerContractRs.getSubAccount("a");
t.deepEqual(JSON.parse(Buffer.from(r.result.status.SuccessValue, "base64")), {
currentAccountId: deployed.accountId,
signerAccountId: bob.accountId,
predecessorAccountId: callerContractRs.accountId,
input: "abc",
});
t.log(
"Gas used to convert transaction to receipt: ",
formatGas(r.result.transaction_outcome.outcome.gas_burnt)
);
t.log(
"Gas used to execute the receipt (actual contract call): ",
formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)
);
let map = gasBreakdown(r.result.receipts_outcome[0].outcome);
logGasBreakdown(map, t);
t.log(
"Gas used to execute the cross contract call: ",
formatGas(r.result.receipts_outcome[1].outcome.gas_burnt)
);
map = gasBreakdown(r.result.receipts_outcome[1].outcome);
logGasBreakdown(map, t);
t.log(
"Gas used to refund unused gas for cross contract call: ",
formatGas(r.result.receipts_outcome[2].outcome.gas_burnt)
);
t.log(
"Gas used to refund unused gas: ",
// TODO: fix after near-workspaces is updated
formatGas(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)
);
t.log(
"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 +
r.result.receipts_outcome[2].outcome.gas_burnt +
// TODO: fix after near-workspaces is updated
(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)
)
);
});
================================================
FILE: benchmark/__tests__/test-expensive-calc.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import { logGasDetail } from "./util.js";
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 contract.
const expensiveContract = await root.devDeploy("build/expensive-calc.wasm");
const expensiveContractRs = await root.devDeploy("res/expensive_calc.wasm");
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
expensiveContract,
expensiveContractRs,
ali,
bob,
carl,
};
});
test("JS expensive contract, iterate 100 times", async (t) => {
const { bob, expensiveContract } = t.context.accounts;
let r = await bob.callRaw(expensiveContract, "expensive", { n: 100 });
t.is(r.result.status.SuccessValue, "LTUw");
logGasDetail(r, t);
});
test("RS expensive contract. iterate 100 times", async (t) => {
const { bob, expensiveContractRs } = t.context.accounts;
let r = await bob.callRaw(expensiveContractRs, "expensive", { n: 100 });
t.is(r.result.status.SuccessValue, "LTUw");
logGasDetail(r, t);
});
test("JS expensive contract, iterate 10000 times", async (t) => {
const { bob, expensiveContract } = t.context.accounts;
let r = await bob.callRaw(
expensiveContract,
"expensive",
{ n: 10000 },
{ gas: BigInt(300 * 10 ** 12) }
);
t.is(r.result.status.SuccessValue, "LTUwMDA=");
logGasDetail(r, t);
});
test("RS expensive contract. iterate 10000 times", async (t) => {
const { bob, expensiveContractRs } = t.context.accounts;
let r = await bob.callRaw(expensiveContractRs, "expensive", { n: 10000 });
t.is(r.result.status.SuccessValue, "LTUwMDA=");
logGasDetail(r, t);
});
test("JS expensive contract, iterate 20000 times", async (t) => {
const { bob, expensiveContract } = t.context.accounts;
let r = await bob.callRaw(
expensiveContract,
"expensive",
{ n: 20000 },
{ gas: BigInt(300 * 10 ** 12) }
);
t.is(r.result.status.SuccessValue, "LTEwMDAw");
logGasDetail(r, t);
});
test("RS expensive contract. iterate 20000 times", async (t) => {
const { bob, expensiveContractRs } = t.context.accounts;
let r = await bob.callRaw(expensiveContractRs, "expensive", { n: 20000 });
t.is(r.result.status.SuccessValue, "LTEwMDAw");
logGasDetail(r, t);
});
================================================
FILE: benchmark/__tests__/test-highlevel-collection.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import { logGasDetail } from "./util.js";
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 contract.
const highlevelContract = await root.devDeploy(
"build/highlevel-collection.wasm"
);
const highlevelContractRs = await root.devDeploy(
"res/highlevel_collection.wasm"
);
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
highlevelContract,
highlevelContractRs,
ali,
bob,
carl,
};
});
test("JS highlevel collection contract", async (t) => {
const { bob, highlevelContract } = t.context.accounts;
let r = await bob.callRaw(highlevelContract, "set", {
key: "a".repeat(100),
value: "b".repeat(100),
});
r = await bob.callRaw(highlevelContract, "set", {
key: "b".repeat(100),
value: "c".repeat(100),
});
r = await bob.callRaw(highlevelContract, "set", {
key: "c".repeat(100),
value: "d".repeat(100),
});
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
test("RS highlevel collection contract", async (t) => {
const { bob, highlevelContractRs } = t.context.accounts;
let r = await bob.callRaw(highlevelContractRs, "set", {
key: "a".repeat(100),
value: "b".repeat(100),
});
r = await bob.callRaw(highlevelContractRs, "set", {
key: "b".repeat(100),
value: "c".repeat(100),
});
r = await bob.callRaw(highlevelContractRs, "set", {
key: "c".repeat(100),
value: "d".repeat(100),
});
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
================================================
FILE: benchmark/__tests__/test-highlevel-minimal.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import { logGasDetail } from "./util.js";
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 contract.
const highlevelContract = await root.devDeploy(
"build/highlevel-minimal.wasm"
);
const highlevelContractRs = await root.devDeploy(
"res/highlevel_minimal.wasm"
);
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
highlevelContract,
highlevelContractRs,
ali,
bob,
carl,
};
});
test("JS highlevel minimal contract", async (t) => {
const { bob, highlevelContract } = t.context.accounts;
let r = await bob.callRaw(highlevelContract, "empty", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
test("RS highlevel minimal contract", async (t) => {
const { bob, highlevelContractRs } = t.context.accounts;
let r = await bob.callRaw(highlevelContractRs, "empty", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
================================================
FILE: benchmark/__tests__/test-lowlevel-api.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import { logGasDetail } from "./util.js";
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 contract.
const lowlevelContract = await root.devDeploy("build/lowlevel-api.wasm");
const lowlevelContractRs = await root.devDeploy("res/lowlevel_api.wasm");
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
lowlevelContract,
lowlevelContractRs,
ali,
bob,
carl,
};
});
test("JS lowlevel API contract", async (t) => {
const { bob, lowlevelContract } = t.context.accounts;
let r = await bob.callRaw(lowlevelContract, "lowlevel_storage_write", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
test("RS lowlevel API contract", async (t) => {
const { bob, lowlevelContractRs } = t.context.accounts;
let r = await bob.callRaw(lowlevelContractRs, "lowlevel_storage_write", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
test("JS lowlevel API contract, call many", async (t) => {
const { bob, lowlevelContract } = t.context.accounts;
let r = await bob.callRaw(
lowlevelContract,
"lowlevel_storage_write_many",
""
);
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
================================================
FILE: benchmark/__tests__/test-lowlevel-minimal.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import { logGasDetail } from "./util.js";
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 contract.
const lowlevelContract = await root.devDeploy("build/lowlevel-minimal.wasm");
const lowlevelContractRs = await root.devDeploy("res/lowlevel_minimal.wasm");
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = {
root,
lowlevelContract,
lowlevelContractRs,
ali,
bob,
carl,
};
});
test("JS lowlevel minimal contract", async (t) => {
const { bob, lowlevelContract } = t.context.accounts;
let r = await bob.callRaw(lowlevelContract, "empty", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
test("RS lowlevel minimal contract", async (t) => {
const { bob, lowlevelContractRs } = t.context.accounts;
let r = await bob.callRaw(lowlevelContractRs, "empty", "");
t.is(r.result.status.SuccessValue, "");
logGasDetail(r, t);
});
================================================
FILE: benchmark/__tests__/util.js
================================================
// Functions consumed by the benchmark contracts tests
export function formatGas(gas) {
if (gas < 10 ** 12) {
let tGas = gas / 10 ** 12;
let roundTGas = Math.round(tGas * 100000) / 100000;
return roundTGas + "T";
}
let tGas = gas / 10 ** 12;
let roundTGas = Math.round(tGas * 100) / 100;
return roundTGas + "T";
}
export function gasBreakdown(outcome) {
return new Map(
outcome.metadata.gas_profile.map((g) => {
return [g.cost, Number(g.gas_used)];
})
);
}
export function logGasBreakdown(map, t) {
map.forEach((v, k) => {
t.log(" ", k, ": ", formatGas(v));
});
}
export function logGasDetail(r, t) {
t.log(
"Gas used to convert transaction to receipt: ",
formatGas(r.result.transaction_outcome.outcome.gas_burnt)
);
t.log(
"Gas used to execute the receipt (actual contract call): ",
formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)
);
let map = gasBreakdown(r.result.receipts_outcome[0].outcome);
logGasBreakdown(map, t);
t.log(
"Gas used to refund unused gas: ",
// TODO: fix after near-workspaces is updated
formatGas(r.result.receipts_outcome[1]?.outcome.gas_burnt || 0)
);
t.log(
"Total gas used: ",
formatGas(
r.result.transaction_outcome.outcome.gas_burnt +
r.result.receipts_outcome[0].outcome.gas_burnt +
// TODO: fix after near-workspaces is updated
(r.result.receipts_outcome[1]?.outcome.gas_burnt || 0)
)
);
}
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);
}
================================================
FILE: benchmark/ava.config.cjs
================================================
require("util").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth
module.exports = {
timeout: "300000",
files: ["**/*.ava.js"],
failWithoutAssertions: false,
extensions: ["js"],
};
================================================
FILE: benchmark/example-outcome.json
================================================
{
"result": {
"receipts_outcome": [
{
"block_hash": "B5zQjLFz1zu36xoUd37Bghzeanw8YfbkLk9amcVdPX4H",
"id": "7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi",
"outcome": {
"executor_id": "dev-14843.test.near",
"gas_burnt": 4217783714059,
"logs": [],
"metadata": {
"gas_profile": [
{
"cost": "CONTRACT_LOADING_BASE",
"cost_category": "WASM_HOST_COST",
"gas_used": "35445963"
},
{
"cost": "CONTRACT_LOADING_BYTES",
"cost_category": "WASM_HOST_COST",
"gas_used": "108947436750"
},
{
"cost": "WASM_INSTRUCTION",
"cost_category": "WASM_HOST_COST",
"gas_used": "1680864179808"
}
],
"version": 1
},
"receipt_ids": ["8FYdTYgNnz5jnCDFFHfbyrBVq5rp9beStZYjxjrXvQ5F"],
"status": {
"SuccessValue": ""
},
"tokens_burnt": "4217783714059000000000"
},
"proof": []
},
{
"block_hash": "4oUZamxqDyUuMp47xfGE7FTnRBRC28VdMuPCS3oSCKpw",
"id": "8FYdTYgNnz5jnCDFFHfbyrBVq5rp9beStZYjxjrXvQ5F",
"outcome": {
"executor_id": "bob.test.near",
"gas_burnt": 223182562500,
"logs": [],
"metadata": {
"gas_profile": [],
"version": 1
},
"receipt_ids": [],
"status": {
"SuccessValue": ""
},
"tokens_burnt": "0"
},
"proof": []
}
],
"status": {
"SuccessValue": ""
},
"transaction": {
"actions": [
{
"FunctionCall": {
"args": "IiI=",
"deposit": "0",
"gas": 30000000000000,
"method_name": "empty"
}
}
],
"hash": "9TvjxGooYJ7A1Ju6NHocss2uCqPeUKiEv1EwPoiXUsS2",
"nonce": 10000001,
"public_key": "ed25519:5iyD5kpiWwBgW3vunXJdmj66ArJAZBhGUxHEud6UKbyr",
"receiver_id": "dev-14843.test.near",
"signature": "ed25519:5jb67kd3VoTnBWxpSgyHENdWerGwLaa5QJHaKVvaxrZosymia2cKf3DNC4ES3PHZ7mXHkky5JTheqnzzjCpop7fx",
"signer_id": "bob.test.near"
},
"transaction_outcome": {
"block_hash": "FQAFEjJVuBJK6Mf64DxfpMPWifP8jyEUJc6zW3yn1rca",
"id": "9TvjxGooYJ7A1Ju6NHocss2uCqPeUKiEv1EwPoiXUsS2",
"outcome": {
"executor_id": "bob.test.near",
"gas_burnt": 2427936651538,
"logs": [],
"metadata": {
"gas_profile": null,
"version": 1
},
"receipt_ids": ["7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi"],
"status": {
"SuccessReceiptId": "7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi"
},
"tokens_burnt": "2427936651538000000000"
},
"proof": []
}
},
"startMs": 1675654730297,
"endMs": 1675654732818,
"config": {
"network": "sandbox",
"rootAccountId": "test.near",
"rpcAddr": "http://localhost:6163",
"initialBalance": "100000000000000000000000000",
"homeDir": "/tmp/sandbox/7a047a19-1712-48ba-9704-d5831cf91f2a",
"port": 6163,
"rm": false,
"refDir": null
}
}
================================================
FILE: benchmark/jsconfig.json
================================================
{
"compilerOptions": {
"experimentalDecorators": true
},
"exclude": ["node_modules"]
}
================================================
FILE: benchmark/package.json
================================================
{
"name": "bench",
"version": "1.0.0",
"description": "near-sdk-js benchmark",
"main": "index.js",
"type": "module",
"scripts": {
"build": "run-s build:*",
"build:lowlevel-minimal": "near-sdk-js build src/lowlevel-minimal.js build/lowlevel-minimal.wasm",
"build:highlevel-minimal": "near-sdk-js build src/highlevel-minimal.js build/highlevel-minimal.wasm",
"build:lowlevel-api": "near-sdk-js build src/lowlevel-api.js build/lowlevel-api.wasm",
"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:collections": "ava __tests__/test-collections-performance.ava.js"
},
"author": "Near Inc <hello@nearprotocol.com>",
"license": "Apache-2.0",
"devDependencies": {
"ava": "4.3.3",
"near-workspaces": "4.0.0",
"npm-run-all": "4.1.5"
},
"dependencies": {
"typescript": "4.7.4",
"near-sdk-js": "workspace:*"
}
}
================================================
FILE: benchmark/src/deploy-contract.js
================================================
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);
near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);
near.promiseBatchActionDeployContract(
promiseId,
includeBytes("../../tests/build/promise_api.wasm")
);
near.promiseBatchActionFunctionCall(
promiseId,
"cross_contract_callee",
"abc",
0,
2 * Math.pow(10, 13)
);
near.promiseReturn(promiseId);
}
================================================
FILE: benchmark/src/expensive-calc.js
================================================
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({})
expensive({ n }) {
let ret = 0;
let sign = 1;
for (let i = 0; i < n; i++) {
ret += i * sign;
sign *= -1;
}
near.valueReturn(ret.toString());
}
}
================================================
FILE: benchmark/src/highlevel-collection.js
================================================
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() {
this.unorderedMap = new UnorderedMap("a");
}
@call({})
set({ key, value }) {
this.unorderedMap.set(key, value);
}
}
================================================
FILE: benchmark/src/highlevel-minimal.js
================================================
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({})
empty({}) {}
}
================================================
FILE: benchmark/src/lookup-map.js
================================================
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);
}
}
================================================
FILE: benchmark/src/lookup-set.js
================================================
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);
}
}
================================================
FILE: benchmark/src/lowlevel-api.js
================================================
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);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
near.storageWriteRaw(data, data);
}
================================================
FILE: benchmark/src/lowlevel-minimal.js
================================================
import { near } from "near-sdk-js";
/**
* More information for that can be found in the README.md
* - A minimal contract
*/
export function empty() {}
================================================
FILE: benchmark/src/unordered-map.js
================================================
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);
}
}
}
================================================
FILE: benchmark/src/unordered-set.js
================================================
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);
}
}
}
================================================
FILE: benchmark/src/vector.js
================================================
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);
}
}
}
================================================
FILE: benchmark/tsconfig.json
================================================
{
"compilerOptions": {
"moduleResolution": "node",
"experimentalDecorators": true,
"target": "es2020",
"noEmit": true
},
"exclude": ["node_modules"]
}
================================================
FILE: examples/.gitignore
================================================
build
node_modules
================================================
FILE: examples/README.md
================================================
# 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)**<br />
A simple smart contract that can make basic state updates.
**[counter](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/counter)**<br />
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)**<br />
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)**<br />
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)**<br />
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)**<br />
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)**<br />
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)**<br />
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!
================================================
FILE: examples/__tests__/standard-ft/ft-tests.ava.js
================================================
import { NEAR, Worker } from "near-workspaces";
import test from "ava";
const INITIAL_BALANCE = NEAR.parse("10000 N").toJSON();
const ONE_YOCTO = "1";
const STOARAGE_BYTE_COST = 10_000_000_000_000_000_000n;
const ACCOUNT_STORAGE_BALANCE = String(STOARAGE_BYTE_COST * 138n);
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const ftContract = await root.devDeploy("./build/my-ft.wasm");
await ftContract.call(
ftContract,
"init_with_default_meta",
{
owner_id: ftContract.accountId,
total_supply: INITIAL_BALANCE
}
);
/**
* DEFI contract implemented in https://github.com/near/near-sdk-rs/tree/master/examples/fungible-token/test-contract-defi
* Iterface:
* pub fn new(fungible_token_account_id: AccountId) -> Self;
* fn ft_on_transfer(
&mut self,
sender_id: AccountId,
amount: U128,
msg: String,
) -> PromiseOrValue<U128>
* If given `msg: "take-my-money", immediately returns U128::From(0). Otherwise, makes a cross-contract call to own `value_please` function, passing `msg` value_please will attempt to parse `msg` as an integer and return a U128 version of it
*/
const defiContract = await root.devDeploy("./res/defi.wasm");
await defiContract.call(
defiContract,
"new",
{
fungible_token_account_id: ftContract.accountId
}
);
const alice = await root.createSubAccount("alice", { initialBalance: NEAR.parse("10 N").toJSON() });
await registerUser(ftContract, alice.accountId);
t.context.worker = worker;
t.context.accounts = {
root,
ftContract,
alice,
defiContract,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
async function registerUser(contract, account_id) {
const deposit = String(ACCOUNT_STORAGE_BALANCE);
await contract.call(contract, "storage_deposit", { account_id: account_id }, { attachedDeposit: deposit });
}
test("test_total_supply", async (t) => {
const { ftContract } = t.context.accounts;
const res = await ftContract.view("ft_total_supply", {});
t.is(BigInt(res), BigInt(INITIAL_BALANCE));
});
test("test_storage_deposit", async (t) => {
const { ftContract, root } = t.context.accounts;
const bob = await root.createSubAccount("bob", { initialBalance: NEAR.parse("10 N").toJSON() });
await registerUser(ftContract, bob.accountId);
const bobStorageBalance = await ftContract.view("storage_balance_of", { account_id: bob.accountId });
t.is(bobStorageBalance.total, String(ACCOUNT_STORAGE_BALANCE));
});
test("test_simple_transfer", async (t) => {
const TRANSFER_AMOUNT = NEAR.parse("1000 N").toJSON();
const EXPECTED_ROOT_BALANCE = NEAR.parse("9000 N").toJSON();
const { ftContract, alice } = t.context.accounts;
await ftContract.call(
ftContract,
"ft_transfer",
{
receiver_id: alice.accountId,
amount: TRANSFER_AMOUNT,
memo: null
},
{
attachedDeposit: ONE_YOCTO
}
);
let root_balance = await ftContract.view("ft_balance_of", { account_id: ftContract.accountId });
let alice_balance = await ftContract.view("ft_balance_of", { account_id: alice.accountId });
t.is(EXPECTED_ROOT_BALANCE, root_balance);
t.is(TRANSFER_AMOUNT, alice_balance);
});
test("test_close_account_empty_balance", async (t) => {
const { ftContract, alice } = t.context.accounts;
let res = await alice.call(ftContract, "storage_unregister", {}, { attachedDeposit: ONE_YOCTO });
t.is(res, true); // TODO: doublecheck
});
test("test_close_account_non_empty_balance", async (t) => {
const { ftContract } = t.context.accounts;
try {
await ftContract.call(ftContract, "storage_unregister", {}, { attachedDeposit: ONE_YOCTO });
throw Error("Unreachable string");
} catch (e) {
t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes("Can't unregister the account with the positive balance without force"), true);
}
try {
await ftContract.call(ftContract, "storage_unregister", { force: false }, { attachedDeposit: ONE_YOCTO });
throw Error("Unreachable string");
} catch (e) {
t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes("Can't unregister the account with the positive balance without force"), true);
}
});
test("simulate_close_account_force_non_empty_balance", async (t) => {
const { ftContract } = t.context.accounts;
await ftContract.call(
ftContract,
"storage_unregister",
{ force: true },
{ attachedDeposit: ONE_YOCTO }
);
const res = await ftContract.view("ft_total_supply", {});
t.is(res, "0");
});
test("simulate_transfer_call_with_burned_amount", async (t) => {
const TRANSFER_AMOUNT = NEAR.parse("100 N").toJSON();
const { ftContract, defiContract } = t.context.accounts;
// defi contract must be registered as a FT account
await registerUser(ftContract, defiContract.accountId);
const result = await ftContract
.batch(ftContract)
.functionCall(
'ft_transfer_call',
{
receiver_id: defiContract.accountId,
amount: TRANSFER_AMOUNT,
memo: null,
msg: "10",
},
{
attachedDeposit: '1',
gas: '150 Tgas'
},
)
.functionCall(
'storage_unregister',
{
force: true
},
{
attachedDeposit: '1',
gas: '150 Tgas',
},
)
.transact();
const logs = JSON.stringify(result);
let expected = `Account @${ftContract.accountId} burned ${10}`;
t.is(logs.includes("The account of the sender was deleted"), true);
t.is(logs.includes(expected), true);
const new_total_supply = await ftContract.view("ft_total_supply", {});
t.is(BigInt(new_total_supply), BigInt(TRANSFER_AMOUNT) - 10n);
const defi_balance = await ftContract.view("ft_balance_of", { account_id: defiContract.accountId });
t.is(BigInt(defi_balance), BigInt(TRANSFER_AMOUNT) - 10n);
});
test("simulate_transfer_call_with_immediate_return_and_no_refund", async (t) => {
const TRANSFER_AMOUNT = NEAR.parse("100 N").toJSON();
const { ftContract, defiContract } = t.context.accounts;
// defi ftContract must be registered as a FT account
await registerUser(ftContract, defiContract.accountId);
// root invests in defi by calling `ft_transfer_call`
await ftContract.call(
ftContract,
"ft_transfer_call",
{
receiver_id: defiContract.accountId,
amount: TRANSFER_AMOUNT,
memo: null,
msg: "take-my-money"
},
{
attachedDeposit: ONE_YOCTO,
gas: 300000000000000,
}
);
let root_balance = await ftContract.view("ft_balance_of", { account_id: ftContract.accountId });
let defi_balance = await ftContract.view("ft_balance_of", { account_id: defiContract.accountId });
t.is(BigInt(INITIAL_BALANCE) - BigInt(TRANSFER_AMOUNT), BigInt(root_balance));
t.is(TRANSFER_AMOUNT, defi_balance);
});
test("simulate_transfer_call_when_called_contract_not_registered_with_ft", async (t) => {
const TRANSFER_AMOUNT = NEAR.parse("100 N").toJSON();
const { ftContract, defiContract } = t.context.accounts;
// call fails because DEFI contract is not registered as FT user
try {
await ftContract.call(
ftContract,
"ft_transfer_call",
{
receiver_id: defiContract.accountId,
amount: TRANSFER_AMOUNT,
memo: null,
msg: "take-my-money"
},
{
attachedDeposit: ONE_YOCTO,
gas: 50000000000000n,
}
);
t.is(true, false); // Unreachable
} catch (e) {
t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes("is not registered"), true);
}
// balances remain unchanged
let root_balance = await ftContract.view("ft_balance_of", { account_id: ftContract.accountId });
let defi_balance = await ftContract.view("ft_balance_of", { account_id: defiContract.accountId });
t.is(BigInt(INITIAL_BALANCE), BigInt(root_balance));
t.is("0", defi_balance);
});
test("simulate_transfer_call_with_promise_and_refund", async (t) => {
const REFUND_AMOUNT = NEAR.parse("50 N").toJSON();
const TRANSFER_AMOUNT = NEAR.parse("100 N").toJSON();
const TRANSFER_CALL_GAS = String(300_000_000_000_000n);
const { ftContract, defiContract } = t.context.accounts;
// defi contract must be registered as a FT account
await registerUser(ftContract, defiContract.accountId);
await ftContract.call(ftContract, "ft_transfer_call", {
receiver_id: defiContract.accountId,
amount: TRANSFER_AMOUNT,
memo: null,
msg: REFUND_AMOUNT,
}, {
attachedDeposit: ONE_YOCTO,
gas: TRANSFER_CALL_GAS,
});
let root_balance = await ftContract.view("ft_balance_of", { account_id: ftContract.accountId });
let defi_balance = await ftContract.view("ft_balance_of", { account_id: defiContract.accountId });
t.is(BigInt(INITIAL_BALANCE) - BigInt(TRANSFER_AMOUNT) + BigInt(REFUND_AMOUNT), BigInt(root_balance));
t.is(BigInt(TRANSFER_AMOUNT) - BigInt(REFUND_AMOUNT), BigInt(defi_balance));
});
test("simulate_transfer_call_promise_panics_for_a_full_refund", async (t) => {
const TRANSFER_AMOUNT = NEAR.parse("100 N").toJSON();
const { ftContract, defiContract } = t.context.accounts;
// defi contract must be registered as a FT account
await registerUser(ftContract, defiContract.accountId);
// root invests in defi by calling `ft_transfer_call`
const res = await ftContract.callRaw(
ftContract,
"ft_transfer_call",
{
receiver_id: defiContract.accountId,
amount: TRANSFER_AMOUNT,
memo: null,
msg: "no parsey as integer big panic oh no",
},
{
attachedDeposit: ONE_YOCTO,
gas: 50000000000000n,
}
);
t.is(JSON.stringify(res).includes("ParseIntError"), true);
// balances remain unchanged
let root_balance = await ftContract.view("ft_balance_of", { account_id: ftContract.accountId });
let defi_balance = await ftContract.view("ft_balance_of", { account_id: defiContract.accountId });
t.is(INITIAL_BALANCE, root_balance);
t.is("0", defi_balance);
});
================================================
FILE: examples/__tests__/standard-nft/test_approval.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 status-message the contract.
const nft = await root.devDeploy("./build/my-nft.wasm");
// Create test accounts
const ali = await root.createSubAccount("alice");
const bob = await root.createSubAccount("bob");
const nftOwner = await root.createSubAccount("owner");
const nftReceiver = await root.devDeploy("./build/nft-receiver.wasm");
const approvalReceiver = await root.devDeploy(
"./build/nft-approval-receiver.wasm"
);
await nft.call(nft, "init", {
owner_id: nftOwner.accountId,
metadata: { spec: "nft-1.0.0", name: "My NFT", symbol: "NFT" },
});
await nftReceiver.call(nftReceiver, "init", {
non_fungible_token_account_id: nft.accountId,
});
await approvalReceiver.call(approvalReceiver, "init", {
non_fungible_token_account_id: nft.accountId,
});
let token_metadata = {
title: "Olympus Mons",
description: "The tallest mountain in the charted solar system",
media: null,
media_hash: null,
copies: 1,
issued_at: null,
expires_at: null,
starts_at: null,
updated_at: null,
extra: null,
reference: null,
reference_hash: null,
};
await nftOwner.call(
nft,
"nft_mint",
{
token_id: "0",
token_owner_id: nftOwner.accountId,
token_metadata,
},
{ attachedDeposit: "10 mN" }
);
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
nft,
ali,
bob,
nftOwner,
nftReceiver,
approvalReceiver,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Simple approve", async (t) => {
const { ali, bob, nft, nftOwner } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: ali.accountId,
},
{ attachedDeposit: "510000000000000000000" }
);
t.assert(res.result.status.SuccessValue);
let alice_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
});
t.assert(alice_approved);
let alice_approval_id_is_1 = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
approval_id: "1",
});
t.assert(alice_approval_id_is_1);
let alice_approval_id_is_2 = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
approval_id: "2",
});
t.assert(!alice_approval_id_is_2);
res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: ali.accountId,
},
{
attachedDeposit: "1",
}
);
t.assert(res.result.status.SuccessValue);
alice_approval_id_is_2 = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
approval_id: "2",
});
t.assert(alice_approval_id_is_2);
res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: bob.accountId,
},
{
attachedDeposit: "550000000000000000000",
}
);
t.assert(res.result.status.SuccessValue);
let bob_approval_id_is_3 = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: bob.accountId,
approval_id: "3",
});
t.assert(bob_approval_id_is_3);
});
test("Approve call", async (t) => {
const { nft, nftOwner, approvalReceiver } = t.context.accounts;
let res = await nftOwner.call(
nft,
"nft_approve",
{
token_id: "0",
account_id: approvalReceiver.accountId,
msg: "return-now",
},
{ attachedDeposit: "610000000000000000000", gas: "300 Tgas" }
);
t.is(res, "cool");
res = await nftOwner.call(
nft,
"nft_approve",
{
token_id: "0",
account_id: approvalReceiver.accountId,
msg: "hahaha",
},
{ attachedDeposit: "1", gas: "300 Tgas" }
);
t.is(res, "hahaha");
});
test("Approved account transfers token", async (t) => {
const { ali, nft, nftOwner } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: ali.accountId,
},
{ attachedDeposit: "510000000000000000000" }
);
t.assert(res.result.status.SuccessValue);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
res = await ali.callRaw(
nft,
"nft_transfer",
{
receiver_id: ali.accountId,
token_id: "0",
memo: "gotcha! bahahaha",
},
{ attachedDeposit: "1" }
);
t.is(res.result.status.SuccessValue, "");
token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, ali.accountId);
});
test("revoke", async (t) => {
const { ali, bob, nft, nftOwner } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: ali.accountId,
},
{ attachedDeposit: "510000000000000000000" }
);
t.assert(res.result.status.SuccessValue);
res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
account_id: bob.accountId,
},
{
attachedDeposit: "510000000000000000000",
}
);
t.assert(res.result.status.SuccessValue);
res = await nftOwner.callRaw(
nft,
"nft_revoke",
{
token_id: "0",
account_id: ali.accountId,
},
{
attachedDeposit: "1",
}
);
t.is(res.result.status.SuccessValue, "");
let alice_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
});
t.assert(!alice_approved);
let bob_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: bob.accountId,
});
t.assert(bob_approved);
res = await nftOwner.callRaw(
nft,
"nft_revoke",
{
token_id: "0",
account_id: bob.accountId,
},
{
attachedDeposit: "1",
}
);
t.is(res.result.status.SuccessValue, "");
alice_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
});
t.assert(!alice_approved);
bob_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: bob.accountId,
});
t.assert(!bob_approved);
});
test("revoke all", async (t) => {
const { ali, bob, nft, nftOwner } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
accountId: ali.accountId,
},
{ attachedDeposit: "510000000000000000000" }
);
t.assert(res.result.status.SuccessValue);
res = await nftOwner.callRaw(
nft,
"nft_approve",
{
token_id: "0",
accountId: bob.accountId,
},
{
attachedDeposit: "510000000000000000000",
}
);
t.assert(res.result.status.SuccessValue);
res = await nftOwner.callRaw(
nft,
"nft_revoke_all",
{ token_id: "0" },
{
attachedDeposit: "1",
}
);
t.is(res.result.status.SuccessValue, "");
let alice_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: ali.accountId,
});
t.assert(!alice_approved);
let bob_approved = await nft.view("nft_is_approved", {
token_id: "0",
approved_account_id: bob.accountId,
});
t.assert(!bob_approved);
});
================================================
FILE: examples/__tests__/standard-nft/test_core.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
const MAX_GAS = 300_000_000_000_000n;
test.beforeEach(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 status-message the contract.
const nft = await root.devDeploy("./build/my-nft.wasm");
// Create test accounts
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const nftOwner = await root.createSubAccount("owner");
const nftReceiver = await root.devDeploy("./build/nft-receiver.wasm");
await nft.call(nft, "init", {
owner_id: nftOwner.accountId,
metadata: { spec: "nft-1.0.0", name: "My NFT", symbol: "NFT" },
});
await nftReceiver.call(nftReceiver, "init", {
non_fungible_token_account_id: nft.accountId,
});
let token_metadata = {
title: "Olympus Mons",
description: "The tallest mountain in the charted solar system",
media: null,
media_hash: null,
copies: 1,
issued_at: null,
expires_at: null,
starts_at: null,
updated_at: null,
extra: null,
reference: null,
reference_hash: null,
};
await nftOwner.call(
nft,
"nft_mint",
{
token_id: "0",
token_owner_id: nftOwner.accountId,
token_metadata,
},
{ attachedDeposit: "10 mN" }
);
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
nft,
ali,
bob,
nftOwner,
nftReceiver,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Simple transfer", async (t) => {
const { ali, nft, nftOwner } = t.context.accounts;
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
let res = await nftOwner.callRaw(
nft,
"nft_transfer",
{
receiver_id: ali.accountId,
token_id: "0",
memo: "simple transfer",
},
{ attachedDeposit: "1" }
);
t.is(res.result.status.SuccessValue, "");
t.is(res.logs.length, 1);
token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, ali.accountId);
});
test("Transfer call fast return to sender", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "return-it-now",
},
{ attachedDeposit: "1", gas: MAX_GAS }
);
t.is(
Buffer.from(res.result.status.SuccessValue, "base64").toString(),
"false"
);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
});
test("Transfer call slow return to sender", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "return-it-later",
},
{ attachedDeposit: "1", gas: MAX_GAS }
);
t.is(
Buffer.from(res.result.status.SuccessValue, "base64").toString(),
"false"
);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
});
test("Transfer call fast keep with sender", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "keep-it-now",
},
{ attachedDeposit: "1", gas: MAX_GAS }
);
t.is(
Buffer.from(res.result.status.SuccessValue, "base64").toString(),
"true"
);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftReceiver.accountId);
});
test("Transfer call slow keep with sender", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "keep-it-later",
},
{ attachedDeposit: "1", gas: MAX_GAS }
);
t.is(
Buffer.from(res.result.status.SuccessValue, "base64").toString(),
"true"
);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftReceiver.accountId);
});
test("Transfer call receiver panics", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "incorrect message",
},
{ attachedDeposit: "1", gas: MAX_GAS }
);
t.is(
Buffer.from(res.result.status.SuccessValue, "base64").toString(),
"false"
);
t.is(res.logs.length, 3);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
});
test("Transfer call receiver panics and nft_resolve_transfer produces no log if not enough gas", async (t) => {
const { nft, nftOwner, nftReceiver } = t.context.accounts;
let res = await nftOwner.callRaw(
nft,
"nft_transfer_call",
{
receiver_id: nftReceiver.accountId,
token_id: "0",
memo: "transfer & call",
msg: "incorrect message",
},
{ attachedDeposit: "1", gas: 30_000_000_000_000n }
);
t.assert(res.result.status.Failure !== undefined);
t.is(res.logs.length, 0);
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
});
test("Simple transfer no logs on failure", async (t) => {
const { nft, nftOwner } = t.context.accounts;
let token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
// transfer to the current owner should fail and not print log
let res = await nftOwner.callRaw(
nft,
"nft_transfer",
{
receiver_id: nftOwner.accountId,
token_id: "0",
memo: "simple transfer",
},
{ attachedDeposit: "1" }
);
t.assert(res.result.status.Failure !== undefined);
t.is(res.logs.length, 0);
token = await nft.view("nft_token", { token_id: "0" });
t.is(token.owner_id, nftOwner.accountId);
});
================================================
FILE: examples/__tests__/standard-nft/test_enumeration.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
async function helper_mint(nft, nftOwner, id, title, description) {
let token_metadata = {
title,
description,
media: null,
media_hash: null,
copies: 1,
issued_at: null,
expires_at: null,
starts_at: null,
updated_at: null,
extra: null,
reference: null,
reference_hash: null,
};
await nftOwner.call(
nft,
"nft_mint",
{
token_id: id,
token_owner_id: nftOwner.accountId,
token_metadata,
},
{ attachedDeposit: "10 mN" }
);
}
test.beforeEach(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 status-message the contract.
const nft = await root.devDeploy("./build/my-nft.wasm");
// Create test accounts
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const nftOwner = await root.createSubAccount("owner");
const nftReceiver = await root.devDeploy("./build/nft-receiver.wasm");
await nft.call(nft, "init", {
owner_id: nftOwner.accountId,
metadata: { spec: "nft-1.0.0", name: "My NFT", symbol: "NFT" },
});
await nftReceiver.call(nftReceiver, "init", {
non_fungible_token_account_id: nft.accountId,
});
await helper_mint(
nft,
nftOwner,
"0",
"Olympus Mons",
"The tallest mountain in the charted solar system"
);
await helper_mint(nft, nftOwner, "1", "Black as the Night", "In charcoal");
await helper_mint(nft, nftOwner, "2", "Hamakua", "Vintage recording");
await helper_mint(nft, nftOwner, "3", "Aloha ke akua", "Original with piano");
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
nft,
ali,
bob,
nftOwner,
nftReceiver,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Enumerate NFT tokens total supply", async (t) => {
const { nft } = t.context.accounts;
let totalSupply = await nft.view("nft_total_supply");
t.is(totalSupply, 4);
});
test("Enumerate NFT tokens", async (t) => {
const { nft } = t.context.accounts;
let nftTokens = await nft.view("nft_tokens", { from_index: 1 });
t.is(nftTokens.length, 3);
t.is(nftTokens[0].token_id, "1");
t.is(nftTokens[1].token_id, "2");
t.is(nftTokens[2].token_id, "3");
nftTokens = await nft.view("nft_tokens", { limit: 2 });
t.is(nftTokens.length, 2);
t.is(nftTokens[0].token_id, "0");
t.is(nftTokens[1].token_id, "1");
});
test("Enumerate NFT tokens supply for owner", async (t) => {
const { ali, nft, nftOwner } = t.context.accounts;
let aliNfts = await nft.view("nft_supply_for_owner", {
account_id: ali.accountId,
});
t.is(aliNfts, 0);
let ownerNfts = await nft.view("nft_supply_for_owner", {
account_id: nftOwner.accountId,
});
t.is(ownerNfts, 4);
});
test("Enumerate NFT tokens for owner", async (t) => {
const { ali, nft, nftOwner } = t.context.accounts;
let nftTokens = await nft.view("nft_tokens_for_owner", {
account_id: nftOwner.accountId,
});
t.is(nftTokens.length, 4);
t.is(nftTokens[0].token_id, "0");
t.is(nftTokens[1].token_id, "1");
t.is(nftTokens[2].token_id, "2");
t.is(nftTokens[3].token_id, "3");
nftTokens = await nft.view("nft_tokens_for_owner", {
account_id: nftOwner.accountId,
from_index: 1,
});
t.is(nftTokens.length, 3);
t.is(nftTokens[0].token_id, "1");
t.is(nftTokens[1].token_id, "2");
t.is(nftTokens[2].token_id, "3");
nftTokens = await nft.view("nft_tokens_for_owner", {
account_id: nftOwner.accountId,
limit: 2,
});
t.is(nftTokens.length, 2);
t.is(nftTokens[0].token_id, "0");
t.is(nftTokens[1].token_id, "1");
let res = await nftOwner.callRaw(
nft,
"nft_transfer",
{
receiver_id: ali.accountId,
token_id: "0",
memo: "simple transfer",
},
{ attachedDeposit: "1" }
);
t.is(res.result.status.SuccessValue, "");
nftTokens = await nft.view("nft_tokens_for_owner", {
account_id: ali.accountId,
});
t.is(nftTokens.length, 1);
nftTokens = await nft.view("nft_tokens_for_owner", {
account_id: nftOwner.accountId,
});
t.is(nftTokens.length, 3);
t.is(nftTokens[0].token_id, "3");
t.is(nftTokens[1].token_id, "1");
t.is(nftTokens[2].token_id, "2");
});
================================================
FILE: examples/__tests__/test-basic-updates.ava.js
================================================
import {NEAR, Worker} from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const contract = await root.devDeploy("./build/basic-updates-base.wasm");
const ali = await root.createSubAccount("ali");
t.context.worker = worker;
t.context.accounts = { root, contract, ali };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("migration basic updates works", async (t) => {
const { contract, ali } = t.context.accounts;
await ali.call(contract, "add_message", { text: "hello" }, { attachedDeposit: NEAR.parse("1 N").toJSON() });
let message0 = await contract.view("get_message", { index: 0 });
let payment0 = await contract.view("get_payment", { index: 0 });
console.log("message0= ", message0," payment0=", payment0)
t.assert(
message0.text === "hello" && message0.premium && message0.sender === ali.accountId
);
t.assert(payment0 == NEAR.parse("1 N"));
await contract.deploy("./build/basic-updates-update.wasm");
await ali.call(contract, "migrateState", {});
let messageUpdated0 = await contract.view("get_message", { index: 0 });
console.log("messageUpdated0= ", messageUpdated0);
t.assert(
message0.text === messageUpdated0.text && message0.premium === messageUpdated0.premium && message0.sender === messageUpdated0.sender && payment0 == messageUpdated0.payment
);
});
================================================
FILE: examples/__tests__/test-clean-state.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 clean-state contract.
const cleanState = await root.devDeploy("./build/clean-state.wasm");
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
cleanState,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Clean state after storing", async (t) => {
const { root, cleanState } = t.context.accounts;
await root.call(cleanState, "put", { key: "1", value: 1 });
const value1 = await cleanState.view("get", { key: "1" });
t.is(value1, "1");
await cleanState.call(cleanState, "clean", { keys: ["1"] });
const value2 = await cleanState.view("get", { key: "1" });
t.is(value2, null);
});
================================================
FILE: examples/__tests__/test-counter.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
// Init the worker and start a Sandbox server
const worker = await Worker.init();
// Prepare sandbox for tests, create accounts, deploy contracts, etc.
const root = worker.rootAccount;
// Deploy the counter contract.
const counter = await root.devDeploy(
process.env["COUNTER_LOWLEVEL"]
? "./build/counter-lowlevel.wasm"
: process.env["COUNTER_TS"]
? "./build/counter-ts.wasm"
: "./build/counter.wasm"
);
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, counter, ali, bob };
});
// If the environment is reused, use test.after to replace test.afterEach
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Initial count is 0", async (t) => {
const { counter } = t.context.accounts;
const result = await counter.view("getCount", {});
t.is(result, 0);
});
test("Increase works", async (t) => {
const { counter, ali, bob } = t.context.accounts;
await ali.call(counter, "increase", {});
let result = await counter.view("getCount", {});
t.is(result, 1);
await bob.call(counter, "increase", { n: 4 });
result = await counter.view("getCount", {});
t.is(result, 5);
});
test("Decrease works", async (t) => {
const { counter, ali, bob } = t.context.accounts;
await ali.call(counter, "decrease", {});
let result = await counter.view("getCount", {});
t.is(result, -1);
let dec = await bob.callRaw(counter, "decrease", { n: 4 });
// ensure imported log does work, not silent failure
t.is(
dec.result.receipts_outcome[0].outcome.logs[0],
"Counter decreased to -5"
);
result = await counter.view("getCount", {});
t.is(result, -5);
});
================================================
FILE: examples/__tests__/test-cross-contract-call-loop.ava.js
================================================
import { Worker, NEAR } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const xccLoop = await root.createSubAccount("xcc-loop");
await xccLoop.deploy("./build/cross-contract-call-loop.wasm");
const firstContract = await root.createSubAccount("first-contract");
const secondContract = await root.createSubAccount("second-contract");
const thirdContract = await root.createSubAccount("third-contract");
await firstContract.deploy("./build/counter.wasm");
await secondContract.deploy("./build/counter.wasm");
await thirdContract.deploy("./build/counter.wasm");
await root.call(firstContract, "increase", {});
await root.call(secondContract, "increase", {});
await root.call(thirdContract, "increase", {});
const alice = await root.createSubAccount("alice", {
initialBalance: NEAR.parse("100 N").toJSON(),
});
t.context.worker = worker;
t.context.accounts = { root, alice, xccLoop };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("should have a count of 3 after calling incrementCount", async (t) => {
const { xccLoop, alice } = t.context.accounts;
const expected = 3;
const callbackResult = await alice.call(
xccLoop,
"incrementCount",
{},
{ gas: "300" + "0".repeat(12) }
);
t.is(callbackResult, 3);
const result = await xccLoop.view("getCount");
t.deepEqual(result, expected);
});
================================================
FILE: examples/__tests__/test-cross-contract-call-ts.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 status-message the contract.
const statusMessage = await root.devDeploy("./build/status-message.wasm");
// Deploy the onCall contract.
const onCall = await root.devDeploy("./build/cross-contract-call-ts.wasm");
// Init the contract
await onCall.call(onCall, "init", {
statusMessageContract: statusMessage.accountId,
});
// Create test accounts
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
statusMessage,
onCall,
ali,
bob,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Nobody is on-call in the beginning", async (t) => {
const { onCall } = t.context.accounts;
const result = await onCall.view("person_on_call", {});
t.is(result, "");
});
test("Person can be set on-call if AVAILABLE", async (t) => {
const { ali, bob, onCall, statusMessage } = t.context.accounts;
// Ali set her status as AVAILABLE
await ali.call(statusMessage, "set_status", { message: "AVAILABLE" });
// Bob sets Ali on-call
await bob.call(
onCall,
"set_person_on_call",
{ accountId: ali.accountId },
{ gas: 120000000000000 }
);
// Check that Ali is on-call
t.is(await onCall.view("person_on_call", {}), ali.accountId);
});
test("Person can NOT be set on-call if UNAVAILABLE", async (t) => {
const { ali, bob, onCall, statusMessage } = t.context.accounts;
// Ali set her status as AVAILABLE
await ali.call(statusMessage, "set_status", { message: "UNAVAILABLE" });
// Bob tries to sets Ali on-call
await bob.call(
onCall,
"set_person_on_call",
{ accountId: ali.accountId },
{ gas: 120000000000000 }
);
// Check that Ali is NOT on-call
t.not(await onCall.view("person_on_call", {}), ali.accountId);
});
================================================
FILE: examples/__tests__/test-cross-contract-call.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 status-message the contract.
const statusMessage = await root.devDeploy("./build/status-message.wasm");
// Deploy the onCall contract.
const onCall = await root.devDeploy("./build/cross-contract-call.wasm");
// Init the contract
await onCall.call(onCall, "init", {
statusMessageContract: statusMessage.accountId,
});
// Create test accounts
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = {
root,
statusMessage,
onCall,
ali,
bob,
};
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Nobody is on-call in the beginning", async (t) => {
const { onCall } = t.context.accounts;
const result = await onCall.view("person_on_call", {});
t.is(result, "undefined");
});
test("Person can be set on-call if AVAILABLE", async (t) => {
const { ali, bob, onCall, statusMessage } = t.context.accounts;
// Ali set her status as AVAILABLE
await ali.call(statusMessage, "set_status", { message: "AVAILABLE" });
// Bob sets Ali on-call
await bob.call(
onCall,
"set_person_on_call",
{ accountId: ali.accountId },
{ gas: 120000000000000 }
);
// Check that Ali is on-call
t.is(await onCall.view("person_on_call", {}), ali.accountId);
});
test("Person can NOT be set on-call if UNAVAILABLE", async (t) => {
const { ali, bob, onCall, statusMessage } = t.context.accounts;
// Ali set her status as AVAILABLE
await ali.call(statusMessage, "set_status", { message: "UNAVAILABLE" });
// Bob tries to sets Ali on-call
await bob.call(
onCall,
"set_person_on_call",
{ accountId: ali.accountId },
{ gas: 120000000000000 }
);
// Check that Ali is NOT on-call
t.not(await onCall.view("person_on_call", {}), ali.accountId);
});
================================================
FILE: examples/__tests__/test-fungible-token-lockable.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 lockable-ft contract.
const lockableFt = await root.devDeploy(
"./build/fungible-token-lockable.wasm"
);
// Init the contract
await lockableFt.call(lockableFt, "init", {
prefix: "prefix",
totalSupply: 10000,
});
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, lockableFt, ali, bob };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Owner initial details", async (t) => {
const { lockableFt } = t.context.accounts;
const totalSupply = await lockableFt.view("getTotalSupply", {});
t.is(totalSupply, 10000);
const totalBalance = await lockableFt.view("getTotalBalance", {
ownerId: lockableFt.accountId,
});
t.is(totalBalance, 10000);
const unlockedBalance = await lockableFt.view("getUnlockedBalance", {
ownerId: lockableFt.accountId,
});
t.is(unlockedBalance, 10000);
const allowance = await lockableFt.view("getAllowance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(allowance, 0);
const lockedBalance = await lockableFt.view("getLockedBalance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(lockedBalance, 0);
});
test("Set allowance", async (t) => {
const { lockableFt, ali } = t.context.accounts;
await lockableFt.call(lockableFt, "setAllowance", {
escrowAccountId: ali.accountId,
allowance: 100,
});
const aliAllowance = await lockableFt.view("getAllowance", {
ownerId: lockableFt.accountId,
escrowAccountId: ali.accountId,
});
t.is(aliAllowance, 100);
const contractAllowance = await lockableFt.view("getAllowance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(contractAllowance, 0);
});
test("Fail to set allowance for oneself", async (t) => {
const { lockableFt } = t.context.accounts;
const error = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "setAllowance", {
escrowAccountId: lockableFt.accountId,
allowance: 100,
})
);
t.assert(error.message.includes(`Can't set allowance for yourself`));
});
test("Lock owner", async (t) => {
const { lockableFt } = t.context.accounts;
await lockableFt.call(lockableFt, "lock", {
ownerId: lockableFt.accountId,
lockAmount: 100,
});
const unlockedBalance = await lockableFt.view("getUnlockedBalance", {
ownerId: lockableFt.accountId,
});
t.is(unlockedBalance, 9900);
const allowance = await lockableFt.view("getAllowance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(allowance, 0);
const lockedBalance = await lockableFt.view("getLockedBalance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(lockedBalance, 100);
});
test("Lock failures", async (t) => {
const { lockableFt, ali } = t.context.accounts;
const error1 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "lock", {
ownerId: lockableFt.accountId,
lockAmount: 0,
})
);
t.assert(error1.message.includes(`Can't lock 0 or less tokens`));
const error2 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "lock", {
ownerId: lockableFt.accountId,
lockAmount: 10001,
})
);
t.assert(error2.message.includes(`Not enough unlocked balance`));
const error3 = await t.throwsAsync(() =>
ali.call(lockableFt, "lock", {
ownerId: lockableFt.accountId,
lockAmount: 10,
})
);
t.assert(error3.message.includes(`Not enough allowance`));
});
test("Unlock owner", async (t) => {
const { lockableFt } = t.context.accounts;
await lockableFt.call(lockableFt, "lock", {
ownerId: lockableFt.accountId,
lockAmount: 100,
});
await lockableFt.call(lockableFt, "unlock", {
ownerId: lockableFt.accountId,
unlockAmount: 100,
});
const unlockedBalance = await lockableFt.view("getUnlockedBalance", {
ownerId: lockableFt.accountId,
});
t.is(unlockedBalance, 10000);
const allowance = await lockableFt.view("getAllowance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(allowance, 0);
const lockedBalance = await lockableFt.view("getLockedBalance", {
ownerId: lockableFt.accountId,
escrowAccountId: lockableFt.accountId,
});
t.is(lockedBalance, 0);
});
test("Unlock failures", async (t) => {
const { lockableFt } = t.context.accounts;
const error1 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "unlock", {
ownerId: lockableFt.accountId,
unlockAmount: 0,
})
);
t.assert(error1.message.includes(`Can't unlock 0 or less tokens`));
const error2 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "unlock", {
ownerId: lockableFt.accountId,
unlockAmount: 1,
})
);
t.assert(error2.message.includes(`Not enough locked tokens`));
});
test("Simple transfer", async (t) => {
const { lockableFt, ali } = t.context.accounts;
await lockableFt.call(lockableFt, "transfer", {
newOwnerId: ali.accountId,
amount: 100,
});
const ownerUnlockedBalance = await lockableFt.view("getUnlockedBalance", {
ownerId: lockableFt.accountId,
});
t.is(ownerUnlockedBalance, 9900);
const aliUnlockedBalance = await lockableFt.view("getUnlockedBalance", {
ownerId: ali.accountId,
});
t.is(aliUnlockedBalance, 100);
});
test("Transfer failures", async (t) => {
const { lockableFt, ali } = t.context.accounts;
const error1 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "transfer", {
newOwnerId: ali.accountId,
amount: 0,
})
);
t.assert(error1.message.includes(`Can't transfer 0 or less tokens`));
const error2 = await t.throwsAsync(() =>
lockableFt.call(lockableFt, "transfer", {
newOwnerId: ali.accountId,
amount: 10001,
})
);
t.assert(error2.message.includes(`Not enough unlocked balance`));
});
================================================
FILE: examples/__tests__/test-fungible-token.ava.js
================================================
import { Worker, NEAR } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const totalSupply = 1000;
const yoctoAccountStorage = "90";
const root = worker.rootAccount;
const xcc = await root.devDeploy("./build/fungible-token-helper.wasm");
const ft = await root.createSubAccount("ft");
await ft.deploy("./build/fungible-token.wasm");
await root.call(ft, "init", {
owner_id: root.accountId,
total_supply: totalSupply.toString(),
});
const alice = await root.createSubAccount("alice", {
initialBalance: NEAR.parse("10 N").toJSON(),
});
t.context.worker = worker;
t.context.accounts = { root, ft, alice, xcc };
t.context.variables = { totalSupply, yoctoAccountStorage };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("should register account and pay for storage", async (t) => {
const { ft, alice } = t.context.accounts;
const { yoctoAccountStorage } = t.context.variables;
const result = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
const aliceAfterBalance = await alice.balance();
const expected = {
message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,
};
t.deepEqual(result, expected);
t.true(
aliceAfterBalance.total > NEAR.parse("9 N").toJSON(),
"alice should have received a refund"
);
});
test("should return message when account is already registered and not refund when no deposit is attached", async (t) => {
const { ft, alice } = t.context.accounts;
const { yoctoAccountStorage } = t.context.variables;
const result = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
const expected = {
message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,
};
t.deepEqual(result, expected);
const result2 = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("0 N").toJSON() }
);
t.is(result2.message, "Account is already registered");
});
test("should return message and refund predecessor caller when trying to pay for storage for an account that is already registered", async (t) => {
const { ft, alice } = t.context.accounts;
const { yoctoAccountStorage } = t.context.variables;
const result = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
const expected = {
message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,
};
t.deepEqual(result, expected);
const result2 = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
t.is(
result2.message,
"Account is already registered, deposit refunded to predecessor"
);
const aliceBalance = await alice.balance();
t.is(
aliceBalance.total > NEAR.parse("9 N"),
true,
"alice should have received a refund"
);
});
test("should return message when trying to pay for storage with less than the required amount and refund predecessor caller", async (t) => {
const { ft, alice } = t.context.accounts;
const { yoctoAccountStorage } = t.context.variables;
const result = await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.from("40").toJSON() }
);
t.is(
result.message,
`Not enough attached deposit to cover storage cost. Required: ${yoctoAccountStorage}`
);
});
test("should throw when trying to transfer for an unregistered account", async (t) => {
const { ft, alice, root } = t.context.accounts;
try {
await root.call(
ft,
"ft_transfer",
{ receiver_id: alice.accountId, amount: "1" },
{ attachedDeposit: NEAR.from("1").toJSON() }
);
} catch (error) {
t.true(
error.message.includes(`Account ${alice.accountId} is not registered`)
);
}
});
test("Owner has all balance in the beginning", async (t) => {
const { ft, root } = t.context.accounts;
const result = await ft.view("ft_balance_of", { account_id: root.accountId });
t.is(result, "1000");
});
test("Can transfer if balance is sufficient", async (t) => {
const { alice, ft, root } = t.context.accounts;
await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
await root.call(
ft,
"ft_transfer",
{ receiver_id: alice.accountId, amount: "100" },
{ attachedDeposit: NEAR.from("1").toJSON() }
);
const aliBalance = await ft.view("ft_balance_of", {
account_id: alice.accountId,
});
t.is(aliBalance, "100");
const ownerBalance = await ft.view("ft_balance_of", {
account_id: root.accountId,
});
t.is(ownerBalance, "900");
});
test("Cannot transfer if balance is not sufficient", async (t) => {
const { alice, root, ft } = t.context.accounts;
await alice.call(
ft,
"storage_deposit",
{ account_id: alice.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
try {
await alice.call(
ft,
"ft_transfer",
{
receiverId: root.accountId,
amount: "100",
},
{ attachedDeposit: NEAR.from("1").toJSON() }
);
} catch (e) {
t.assert(
e
.toString()
.indexOf(
"Smart contract panicked: assertion failed: The account doesn't have enough balance"
) >= 0
);
}
});
test("Cross contract transfer", async (t) => {
const { xcc, ft, root } = t.context.accounts;
await xcc.call(
ft,
"storage_deposit",
{ account_id: xcc.accountId },
{ attachedDeposit: NEAR.parse("1 N").toJSON() }
);
await root.call(
ft,
"ft_transfer_call",
{ receiver_id: xcc.accountId, amount: "900", memo: null, msg: "test msg" },
{ gas: 200000000000000, attachedDeposit: NEAR.from("1").toJSON() }
);
const xccBalance = await ft.view("ft_balance_of", {
account_id: xcc.accountId,
});
t.is(xccBalance, "900");
const aliSubContractData = await xcc.view("get_contract_data");
t.is(
aliSubContractData,
`[900 from ${root.accountId} to ${xcc.accountId}] test msg `
);
const ownerBalance = await ft.view("ft_balance_of", {
account_id: root.accountId,
});
t.is(ownerBalance, "100");
});
================================================
FILE: examples/__tests__/test-nested-collections.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
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 contract.
const nestedCollections = await root.devDeploy(
"./build/nested-collections.wasm"
);
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, nestedCollections, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Ali sets then gets text", async (t) => {
const { ali, nestedCollections } = t.context.accounts;
await ali.call(nestedCollections, "add", { id: "1", text: "hello" });
await ali.call(nestedCollections, "add", { id: "2", text: "world" });
t.is(
await nestedCollections.view("get", { id: "1", accountId: ali.accountId }),
"hello"
);
t.is(
await nestedCollections.view("get", { id: "2", accountId: ali.accountId }),
"world"
);
});
test("Bob and Carl have different statuses", async (t) => {
const { nestedCollections, bob, carl } = t.context.accounts;
await bob.call(nestedCollections, "add", { id: "1", text: "hello" });
await carl.call(nestedCollections, "add", { id: "1", text: "world" });
t.is(
await nestedCollections.view("get", { id: "1", accountId: bob.accountId }),
"hello"
);
t.is(
await nestedCollections.view("get", { id: "1", accountId: carl.accountId }),
"world"
);
});
test("sets then gets nested nested collection", async (t) => {
const { ali, bob, nestedCollections } = t.context.accounts;
await ali.call(nestedCollections, "add_to_group", {
group: "x",
id: "1",
text: "hello",
});
await ali.call(nestedCollections, "add_to_group", {
group: "x",
id: "2",
text: "world",
});
await ali.call(nestedCollections, "add_to_group", {
group: "y",
id: "2",
text: "cat",
});
await bob.call(nestedCollections, "add_to_group", {
group: "y",
id: "2",
text: "dog",
});
t.is(
await nestedCollections.view("get_from_group", {
group: "x",
id: "1",
accountId: ali.accountId,
}),
"hello"
);
t.is(
await nestedCollections.view("get_from_group", {
group: "x",
id: "2",
accountId: ali.accountId,
}),
"world"
);
t.is(
await nestedCollections.view("get_from_group", {
group: "y",
id: "2",
accountId: ali.accountId,
}),
"cat"
);
t.is(
await nestedCollections.view("get_from_group", {
group: "y",
id: "2",
accountId: bob.accountId,
}),
"dog"
);
});
================================================
FILE: examples/__tests__/test-non-fungible-token.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 nft contract.
const nft = await root.devDeploy("./build/non-fungible-token.wasm");
// Init the contract
await nft.call(nft, "init", {
owner_id: nft.accountId,
owner_by_id_prefix: "a",
});
// Deploy the tokenReceiver contract.
const tokenReceiver = await root.devDeploy(
"./build/non-fungible-token-receiver.wasm"
);
// Init the contract
await tokenReceiver.call(tokenReceiver, "init", {
nonFungibleTokenAccountId: nft.accountId,
});
// Mint an NFT
let tokenId = "my-cool-nft";
await nft.call(nft, "nftMint", {
token_id: tokenId,
token_owner_id: nft.accountId,
});
// Create test accounts
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = { root, nft, tokenReceiver, tokenId, ali, bob };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed tear down the worker:", error);
});
});
test("Owner has the NFT in the beginning", async (t) => {
const { nft, tokenId } = t.context.accounts;
const result = await nft.view("nftToken", { token_id: tokenId });
t.deepEqual(result, { owner_id: nft.accountId, token_id: tokenId });
});
test("Simple transfer", async (t) => {
const { nft, tokenId, ali } = t.context.accounts;
await nft.call(nft, "nftTransfer", {
receiver_id: ali.accountId,
token_id: tokenId,
});
const result = await nft.view("nftToken", { token_id: tokenId });
t.deepEqual(result, { owner_id: ali.accountId, token_id: tokenId });
});
test("Transfer failures", async (t) => {
const { nft, tokenId, ali } = t.context.accounts;
const error1 = await t.throwsAsync(() =>
ali.call(nft, "nftTransfer", {
receiver_id: nft.accountId,
token_id: "non-existent-id",
})
);
t.assert(error1.message.includes(`Token not found`));
const error2 = await t.throwsAsync(() =>
ali.call(nft, "nftTransfer", {
receiver_id: nft.accountId,
token_id: tokenId,
})
);
t.assert(error2.message.includes(`Sender must be the current owner`));
const error3 = await t.throwsAsync(() =>
nft.call(nft, "nftTransfer", {
receiver_id: nft.accountId,
token_id: tokenId,
})
);
t.assert(error3.message.includes(`Current and next owner must differ`));
});
test("Transfer call where receiver returns the token", async (t) => {
const { nft, tokenReceiver, tokenId } = t.context.accounts;
await nft.call(
nft,
"nftTransferCall",
{
receiver_id: tokenReceiver.accountId,
token_id: tokenId,
approval_id: null,
memo: null,
msg: "return-it-now",
},
{ gas: "120000000000000" }
);
const result = await nft.view("nftToken", { token_id: tokenId });
t.deepEqual(result, { owner_id: nft.accountId, token_id: tokenId });
});
test("Transfer call where receiver keeps the token", async (t) => {
const { nft, tokenReceiver, tokenId } = t.context.accounts;
await nft.call(
nft,
"nftTransferCall",
{
receiver_id: tokenReceiver.accountId,
token_id: tokenId,
approval_id: null,
memo: null,
msg: "keep-it-now",
},
{ gas: "120000000000000" }
);
const result = await nft.view("nftToken", { token_id: tokenId });
t.deepEqual(result, { owner_id: tokenReceiver.accountId, token_id: tokenId });
});
================================================
FILE: examples/__tests__/test-parking-lot.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const parkingLot = await root.devDeploy("build/parking-lot.wasm");
const ali = await root.createSubAccount("ali");
t.context.worker = worker;
t.context.accounts = { root, parkingLot, ali };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("No BMW in the beginning", async (t) => {
const { parkingLot } = t.context.accounts;
t.is(await parkingLot.view("getCarSpecs", { name: "BMW" }), null);
});
test("Can run the car after adding it", async (t) => {
const { ali, parkingLot } = t.context.accounts;
const bmwSpecs = {
id: 1,
color: "Black",
price: 100500,
engineHp: 500,
};
await ali.call(parkingLot, "addCar", {
name: "BMW",
...bmwSpecs,
});
t.is(await parkingLot.view("runCar", { name: "BMW" }), "boom");
});
================================================
FILE: examples/__tests__/test-programmatic-update.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
import * as fs from "fs";
import * as path from "path";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const ali = await root.createSubAccount("ali");
const contract = await root.devDeploy(
"build/programmatic-update-before.wasm"
);
await contract.call(contract, "init", { manager: ali.accountId });
t.context.worker = worker;
t.context.accounts = { root, contract, ali };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("the contract can be programmatically updated", async (t) => {
const { ali, contract } = t.context.accounts;
// ASSERT BEFORE CODE UPDATE
const codeBefore = await contract.viewCodeRaw();
const beforeDefaultGreeting = await contract.view("get_greeting", {});
t.is(beforeDefaultGreeting, "Hello");
// ACT (UPDATE CODE)
const code = fs.readFileSync(
path.resolve("./build/programmatic-update-after.wasm")
);
await ali.call(contract, "updateContract", code, {
gas: "300" + "0".repeat(12), // 300 Tgas
});
// ASSERT AFTER CODE UPDATE
const codeAfter = await contract.viewCodeRaw();
const afterDefaultGreeting = await contract.view("view_greeting", {});
t.not(codeBefore, codeAfter, "code should be different after update");
t.is(afterDefaultGreeting, "Hi");
});
================================================
FILE: examples/__tests__/test-state-message-migration-add-filed.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const contract = await root.devDeploy("./build/status-message.wasm");
const ali = await root.createSubAccount("ali");
t.context.worker = worker;
t.context.accounts = { root, contract, ali };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("migration works", async (t) => {
const { contract, ali } = t.context.accounts;
await ali.call(contract, "set_status", { message: "hello" });
t.is(
await contract.view("get_status", { account_id: ali.accountId }),
"hello"
);
await contract.deploy("./build/status-message-migrate-add-field.wasm");
await ali.call(contract, "migrateState", {});
t.is(
await contract.view("get_status", { account_id: ali.accountId }),
"hello"
);
await ali.call(contract, "set_new_status", { message: "hello" });
t.is(
await contract.view("get_new_status", { account_id: ali.accountId }),
"hello"
);
});
================================================
FILE: examples/__tests__/test-state-migration.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(async (t) => {
const worker = await Worker.init();
const root = worker.rootAccount;
const contract = await root.devDeploy("./build/state-migration-original.wasm");
const ali = await root.createSubAccount("ali");
t.context.worker = worker;
t.context.accounts = { root, contract, ali };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("migration works", async (t) => {
const { contract, ali } = t.context.accounts;
await ali.call(contract, "addMessage", { message: { sender: "ali", header: "h1", text: "hello" } });
await ali.call(contract, "addMessage", { message: { sender: "ali", header: "h2", text: "world" } });
await ali.call(contract, "addMessage", { message: { sender: "ali", header: "h3", text: "This message is too log for new standard" } });
await ali.call(contract, "addMessage", { message: { sender: "ali", header: "h4", text: "!" } });
const res1 = await contract.view("countMessages", {});
t.is(res1, 4);
await contract.deploy("./build/state-migration-new.wasm");
await ali.call(contract, "migrateState", {});
const res2 = await contract.view("countMessages", {});
t.is(res2, 3);
});
================================================
FILE: examples/__tests__/test-status-deserialize-class.ava.js
================================================
import {Worker} from "near-workspaces";
import test from "ava";
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 contract.
const statusMessage = await root.devDeploy("./build/status-deserialize-class.wasm");
await root.call(statusMessage, "init_contract", {});
const result = await statusMessage.view("is_contract_inited", {});
t.is(result, true);
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Ali sets then gets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_record", { message: "hello" });
t.is(
await statusMessage.view("get_record", { account_id: ali.accountId }),
"hello"
);
});
test("Ali set_truck_info and get_truck_info", async (t) => {
const { ali, statusMessage } = t.context.accounts;
let carName = "Mercedes-Benz";
let speed = 240;
await ali.call(statusMessage, "set_truck_info", { name: carName, speed: speed });
await ali.call(statusMessage, "add_truck_load", { name: "alice", load: "a box" });
await ali.call(statusMessage, "add_truck_load", { name: "bob", load: "a packet" });
t.is(
await statusMessage.view("get_truck_info", { }),
carName + " run with speed " + speed + " with loads length: 2"
);
t.is(
await statusMessage.view("get_user_car_info", { account_id: ali.accountId }),
carName + " run with speed " + speed
);
});
test("Ali push_message and get_messages", async (t) => {
const { ali, statusMessage } = t.context.accounts;
let message1 = 'Hello';
let message2 = 'World';
await ali.call(statusMessage, "push_message", { message: message1 });
await ali.call(statusMessage, "push_message", { message: message2 });
t.is(
await statusMessage.view("get_messages", { }),
'Hello,World'
);
});
test("Ali set_nested_efficient_recordes then get_nested_efficient_recordes text", async (t) => {
const { ali, bob, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_nested_efficient_recordes", { id: "1", message: "hello" }, { gas: 35_000_000_000_000n });
await bob.call(statusMessage, "set_nested_efficient_recordes", { id: "1", message: "hello" }, { gas: 35_000_000_000_000n });
await bob.call(statusMessage, "set_nested_efficient_recordes", { id: "2", message: "world" }, { gas: 35_000_000_000_000n });
t.is(
await statusMessage.view("get_efficient_recordes", { account_id: ali.accountId }),
"hello"
);
t.is(
await statusMessage.view("get_nested_efficient_recordes", { id: "1", account_id: bob.accountId }),
"hello"
);
t.is(
await statusMessage.view("get_nested_efficient_recordes", { id: "2", account_id: bob.accountId }),
"world"
);
t.is(
await statusMessage.view("get_nested_lookup_recordes", { id: "1", account_id: bob.accountId }),
"hello"
);
t.is(
await statusMessage.view("get_nested_lookup_recordes", { id: "2", account_id: bob.accountId }),
"world"
);
t.is(
await statusMessage.view("get_vector_nested_group", { idx: 0, account_id: bob.accountId }),
"world"
);
t.is(
await statusMessage.view("get_lookup_nested_vec", { account_id: bob.accountId, idx: 1 }),
"world"
);
t.is(
await statusMessage.view("get_is_contains_user", { account_id: bob.accountId}),
true
);
});
test("Ali set_big_num_and_date then gets", async (t) => {
const { ali, bob, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_big_num_and_date", { bigint_num: `${10n}`, new_date: new Date('August 19, 2023 23:15:30 GMT+00:00') });
const afterSetNum = await statusMessage.view("get_big_num", { });
t.is(afterSetNum, `${10n}`);
const afterSetDate = await statusMessage.view("get_date", { });
t.is(afterSetDate.toString(), '2023-08-19T23:15:30.000Z');
});
test("Ali set_extra_data without schema defined then gets", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_extra_data", { message: "Hello world!", number: 100 });
const messageWithoutSchemaDefined = await statusMessage.view("get_extra_msg", { });
t.is(messageWithoutSchemaDefined, "Hello world!");
const numberWithoutSchemaDefined = await statusMessage.view("get_extra_number", { });
t.is(numberWithoutSchemaDefined, 100);
});
test("Ali set_extra_record without schema defined then gets", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_extra_record", { message: "Hello world!"});
const recordWithoutSchemaDefined = await statusMessage.view("get_extra_record", { account_id: ali.accountId });
t.is(recordWithoutSchemaDefined, "Hello world!");
});
================================================
FILE: examples/__tests__/test-status-message-borsh.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
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 contract.
const statusMessage = await root.devDeploy("./build/status-message-borsh.wasm");
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Root gets null status", async (t) => {
const { statusMessage, root } = t.context.accounts;
const result = await statusMessage.view("get_status", {
account_id: root.accountId,
});
t.is(result, null);
});
test("Ali sets then gets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_status", { message: "hello" });
t.is(
await statusMessage.view("get_status", { account_id: ali.accountId }),
"hello"
);
});
test("Bob and Carl have different statuses", async (t) => {
const { statusMessage, bob, carl } = t.context.accounts;
await bob.call(statusMessage, "set_status", { message: "hello" });
await carl.call(statusMessage, "set_status", { message: "world" });
const bobStatus = await statusMessage.view("get_status", {
account_id: bob.accountId,
});
const carlStatus = await statusMessage.view("get_status", {
account_id: carl.accountId,
});
t.is(bobStatus, "hello");
t.is(carlStatus, "world");
});
================================================
FILE: examples/__tests__/test-status-message-collections.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
test.beforeEach(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 statis-message contract.
const statusMessage = await root.devDeploy(
"./build/status-message-collections.wasm"
);
// Test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.afterEach.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Root gets null status", async (t) => {
const { root, statusMessage } = t.context.accounts;
const result = await statusMessage.view("get_status", {
account_id: root.accountId,
});
t.is(result, null);
});
test("Ali sets then gets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_status", { message: "hello" });
t.is(
await statusMessage.view("get_status", { account_id: ali.accountId }),
"hello"
);
});
test("Bob and Carl have different statuses", async (t) => {
const { statusMessage, bob, carl } = t.context.accounts;
await bob.call(statusMessage, "set_status", { message: "hello" });
await carl.call(statusMessage, "set_status", { message: "world" });
const bobStatus = await statusMessage.view("get_status", {
account_id: bob.accountId,
});
const carlStatus = await statusMessage.view("get_status", {
account_id: carl.accountId,
});
t.is(bobStatus, "hello");
t.is(carlStatus, "world");
});
test("Get statuses from the contract", async (t) => {
const { statusMessage, bob, carl } = t.context.accounts;
await bob.call(statusMessage, "set_status", { message: "hello" });
await carl.call(statusMessage, "set_status", { message: "world" });
const statuses = await statusMessage.view("get_all_statuses", {});
t.deepEqual(statuses, [
[bob.accountId, "hello"],
[carl.accountId, "world"],
]);
});
test("message has stored by someone", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_status", { message: "hello" });
t.is(await statusMessage.view("has_status", { message: "hello" }), true);
t.is(await statusMessage.view("has_status", { message: "world" }), false);
});
================================================
FILE: examples/__tests__/test-status-message-deserialize-err.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
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 contract.
const statusMessage = await root.devDeploy("./build/status-message-deserialize-err.wasm");
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Root gets null status", async (t) => {
const { statusMessage, root } = t.context.accounts;
const result = await statusMessage.view("get_status", {
account_id: root.accountId,
});
t.is(result, null);
});
test("Ali sets then gets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_status", { message: "hello" });
let res = await ali.callRaw(statusMessage, "get_status", { account_id: ali.accountId });
t.assert(
res.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(
"Smart contract panicked: deserialize err"
)
);
});
================================================
FILE: examples/__tests__/test-status-message-serialize-err.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
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 contract.
const statusMessage = await root.devDeploy("./build/status-message-serialize-err.wasm");
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Root gets null status", async (t) => {
const { statusMessage, root } = t.context.accounts;
const result = await statusMessage.view("get_status", {
account_id: root.accountId,
});
t.is(result, null);
});
test("Ali sets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
let res = await ali.callRaw(statusMessage, "set_status", { message: "hello" });
t.assert(
res.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(
"Smart contract panicked: serialize err"
)
);
});
================================================
FILE: examples/__tests__/test-status-message.ava.js
================================================
import { Worker } from "near-workspaces";
import test from "ava";
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 contract.
const statusMessage = await root.devDeploy("./build/status-message.wasm");
// Create test users
const ali = await root.createSubAccount("ali");
const bob = await root.createSubAccount("bob");
const carl = await root.createSubAccount("carl");
// Save state for test runs
t.context.worker = worker;
t.context.accounts = { root, statusMessage, ali, bob, carl };
});
test.after.always(async (t) => {
await t.context.worker.tearDown().catch((error) => {
console.log("Failed to tear down the worker:", error);
});
});
test("Root gets null status", async (t) => {
const { statusMessage, root } = t.context.accounts;
const result = await statusMessage.view("get_status", {
account_id: root.accountId,
});
t.is(result, null);
});
test("Ali sets then gets status", async (t) => {
const { ali, statusMessage } = t.context.accounts;
await ali.call(statusMessage, "set_status", { message: "hello" });
t.is(
await statusMessage.view("get_status", { account_id: ali.accountId }),
"hello"
);
});
test("Bob and Carl have different statuses", async (t) => {
const { statusMessage, bob, carl } = t.context.accounts;
await bob.call(statusMessage, "set_status", { message: "hello" });
await carl.call(statusMessage, "set_status", { message: "world" });
const bobStatus = await statusMessage.view("get_status", {
account_id: bob.accountId,
});
const carlStatus = await statusMessage.view("get_status", {
account_id: carl.accountId,
});
t.is(bobStatus, "hello");
t.is(carlStatus, "world");
});
================================================
FILE: examples/ava.config.cjs
================================================
require("util").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth
module.exports = {
timeout: "300000",
files: ["**/*.ava.js"],
failWithoutAssertions: false,
extensions: ["js"],
};
================================================
FILE: examples/jsconfig.json
================================================
{
"compilerOptions": {
"experimentalDecorators": true
},
"exclude": ["node_modules"],
"files": ["src/counter.js"]
}
================================================
FILE: examples/package.json
================================================
{
"name": "examples",
"version": "1.0.0",
"description": "Status message example with near-sdk-js",
"main": "index.js",
"type": "module",
"scripts": {
"build": "run-s build:*",
"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/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-updates": "near-sdk-js
gitextract_uwvzvvaa/ ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug.yml │ │ ├── config.yml │ │ └── feature.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── add-to-devtools.yml │ ├── tests.yml │ ├── typedoc-generate-gitbook-docs.yml │ └── typedoc-generator.yml ├── .gitignore ├── .npmrc ├── AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-APACHE ├── README.md ├── RELEASE.md ├── RUNTIME_INVESTIGATE.md ├── SECURITY.md ├── TOOLING.md ├── benchmark/ │ ├── .gitignore │ ├── README.md │ ├── __tests__/ │ │ ├── test-collections-performance.ava.js │ │ ├── test-deploy-contract.ava.js │ │ ├── test-expensive-calc.ava.js │ │ ├── test-highlevel-collection.ava.js │ │ ├── test-highlevel-minimal.ava.js │ │ ├── test-lowlevel-api.ava.js │ │ ├── test-lowlevel-minimal.ava.js │ │ └── util.js │ ├── ava.config.cjs │ ├── example-outcome.json │ ├── jsconfig.json │ ├── package.json │ ├── res/ │ │ ├── deploy_contract.wasm │ │ ├── expensive_calc.wasm │ │ ├── highlevel_collection.wasm │ │ ├── highlevel_minimal.wasm │ │ ├── lowlevel_api.wasm │ │ └── lowlevel_minimal.wasm │ ├── src/ │ │ ├── deploy-contract.js │ │ ├── expensive-calc.js │ │ ├── highlevel-collection.js │ │ ├── highlevel-minimal.js │ │ ├── lookup-map.js │ │ ├── lookup-set.js │ │ ├── lowlevel-api.js │ │ ├── lowlevel-minimal.js │ │ ├── unordered-map.js │ │ ├── unordered-set.js │ │ └── vector.js │ └── tsconfig.json ├── examples/ │ ├── .gitignore │ ├── README.md │ ├── __tests__/ │ │ ├── standard-ft/ │ │ │ └── ft-tests.ava.js │ │ ├── standard-nft/ │ │ │ ├── test_approval.ava.js │ │ │ ├── test_core.ava.js │ │ │ └── test_enumeration.ava.js │ │ ├── test-basic-updates.ava.js │ │ ├── test-clean-state.ava.js │ │ ├── test-counter.ava.js │ │ ├── test-cross-contract-call-loop.ava.js │ │ ├── test-cross-contract-call-ts.ava.js │ │ ├── test-cross-contract-call.ava.js │ │ ├── test-fungible-token-lockable.ava.js │ │ ├── test-fungible-token.ava.js │ │ ├── test-nested-collections.ava.js │ │ ├── test-non-fungible-token.ava.js │ │ ├── test-parking-lot.ava.js │ │ ├── test-programmatic-update.ava.js │ │ ├── test-state-message-migration-add-filed.ava.js │ │ ├── test-state-migration.ava.js │ │ ├── test-status-deserialize-class.ava.js │ │ ├── test-status-message-borsh.ava.js │ │ ├── test-status-message-collections.ava.js │ │ ├── test-status-message-deserialize-err.ava.js │ │ ├── test-status-message-serialize-err.ava.js │ │ └── test-status-message.ava.js │ ├── ava.config.cjs │ ├── jsconfig.json │ ├── package.json │ ├── res/ │ │ └── defi.wasm │ ├── src/ │ │ ├── basic-updates/ │ │ │ ├── basic-updates-base.js │ │ │ └── basic-updates-update.js │ │ ├── clean-state.js │ │ ├── counter/ │ │ │ ├── counter-lowlevel.js │ │ │ ├── counter.js │ │ │ ├── counter.ts │ │ │ └── log.ts │ │ ├── cross-contract-calls/ │ │ │ ├── cross-contract-call-loop.js │ │ │ ├── cross-contract-call.js │ │ │ └── cross-contract-call.ts │ │ ├── fungible-token/ │ │ │ ├── fungible-token-helper.ts │ │ │ ├── fungible-token-lockable.js │ │ │ ├── fungible-token.ts │ │ │ └── my-ft.ts │ │ ├── nested-collections.ts │ │ ├── non-fungible-token/ │ │ │ ├── my-nft.ts │ │ │ ├── non-fungible-token-receiver.js │ │ │ ├── non-fungible-token.js │ │ │ ├── test-approval-receiver.ts │ │ │ └── test-token-receiver.ts │ │ ├── parking-lot.ts │ │ ├── programmatic-updates/ │ │ │ ├── programmatic-update-after.ts │ │ │ └── programmatic-update-before.ts │ │ ├── state-migration/ │ │ │ ├── state-migration-new.ts │ │ │ └── state-migration-original.ts │ │ ├── status-deserialize-class.js │ │ └── status-message/ │ │ ├── status-message-borsh.js │ │ ├── status-message-collections.js │ │ ├── status-message-deserialize-err.js │ │ ├── status-message-migrate-add-field.js │ │ ├── status-message-serialize-err.js │ │ └── status-message.js │ └── tsconfig.json ├── generate-docs-markdown.js ├── near-sdk-js@2.0.0-diff-1.0.0.md ├── package.json ├── packages/ │ ├── near-contract-standards/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── ava.config.cjs │ │ ├── lib/ │ │ │ ├── event.d.ts │ │ │ ├── event.js │ │ │ ├── fungible_token/ │ │ │ │ ├── core.d.ts │ │ │ │ ├── core.js │ │ │ │ ├── core_impl.d.ts │ │ │ │ ├── core_impl.js │ │ │ │ ├── events.d.ts │ │ │ │ ├── events.js │ │ │ │ ├── index.d.ts │ │ │ │ ├── index.js │ │ │ │ ├── metadata.d.ts │ │ │ │ ├── metadata.js │ │ │ │ ├── receiver.d.ts │ │ │ │ ├── receiver.js │ │ │ │ ├── resolver.d.ts │ │ │ │ └── resolver.js │ │ │ ├── index.d.ts │ │ │ ├── index.js │ │ │ ├── non_fungible_token/ │ │ │ │ ├── approval/ │ │ │ │ │ ├── approval_receiver.d.ts │ │ │ │ │ ├── approval_receiver.js │ │ │ │ │ ├── index.d.ts │ │ │ │ │ └── index.js │ │ │ │ ├── core/ │ │ │ │ │ ├── index.d.ts │ │ │ │ │ ├── index.js │ │ │ │ │ ├── receiver.d.ts │ │ │ │ │ ├── receiver.js │ │ │ │ │ ├── resolver.d.ts │ │ │ │ │ └── resolver.js │ │ │ │ ├── enumeration/ │ │ │ │ │ ├── index.d.ts │ │ │ │ │ └── index.js │ │ │ │ ├── events.d.ts │ │ │ │ ├── events.js │ │ │ │ ├── impl.d.ts │ │ │ │ ├── impl.js │ │ │ │ ├── index.d.ts │ │ │ │ ├── index.js │ │ │ │ ├── metadata.d.ts │ │ │ │ ├── metadata.js │ │ │ │ ├── token.d.ts │ │ │ │ ├── token.js │ │ │ │ ├── utils.d.ts │ │ │ │ └── utils.js │ │ │ ├── storage_management/ │ │ │ │ ├── index.d.ts │ │ │ │ └── index.js │ │ │ ├── util.d.ts │ │ │ └── util.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── event.ts │ │ │ ├── fungible_token/ │ │ │ │ ├── core.ts │ │ │ │ ├── core_impl.ts │ │ │ │ ├── events.ts │ │ │ │ ├── index.ts │ │ │ │ ├── metadata.ts │ │ │ │ ├── receiver.ts │ │ │ │ └── resolver.ts │ │ │ ├── index.ts │ │ │ ├── non_fungible_token/ │ │ │ │ ├── approval/ │ │ │ │ │ ├── approval_receiver.ts │ │ │ │ │ └── index.ts │ │ │ │ ├── core/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── receiver.ts │ │ │ │ │ └── resolver.ts │ │ │ │ ├── enumeration/ │ │ │ │ │ └── index.ts │ │ │ │ ├── events.ts │ │ │ │ ├── impl.ts │ │ │ │ ├── index.ts │ │ │ │ ├── metadata.ts │ │ │ │ ├── token.ts │ │ │ │ └── utils.ts │ │ │ ├── storage_management/ │ │ │ │ └── index.ts │ │ │ └── util.ts │ │ └── tsconfig.json │ └── near-sdk-js/ │ ├── .eslintrc.cjs │ ├── .prettierignore │ ├── README.md │ ├── builder/ │ │ └── builder.c │ ├── lib/ │ │ ├── api.d.ts │ │ ├── api.js │ │ ├── cli/ │ │ │ ├── abi.d.ts │ │ │ ├── abi.js │ │ │ ├── build-tools/ │ │ │ │ ├── include-bytes.d.ts │ │ │ │ ├── include-bytes.js │ │ │ │ ├── near-bindgen-exporter.d.ts │ │ │ │ └── near-bindgen-exporter.js │ │ │ ├── cli.d.ts │ │ │ ├── cli.js │ │ │ ├── post-install.d.ts │ │ │ ├── post-install.js │ │ │ ├── utils.d.ts │ │ │ └── utils.js │ │ ├── collections/ │ │ │ ├── index.d.ts │ │ │ ├── index.js │ │ │ ├── lookup-map.d.ts │ │ │ ├── lookup-map.js │ │ │ ├── lookup-set.d.ts │ │ │ ├── lookup-set.js │ │ │ ├── subtype.d.ts │ │ │ ├── subtype.js │ │ │ ├── unordered-map.d.ts │ │ │ ├── unordered-map.js │ │ │ ├── unordered-set.d.ts │ │ │ ├── unordered-set.js │ │ │ ├── vector.d.ts │ │ │ └── vector.js │ │ ├── index.d.ts │ │ ├── index.js │ │ ├── near-bindgen.d.ts │ │ ├── near-bindgen.js │ │ ├── promise.d.ts │ │ ├── promise.js │ │ ├── types/ │ │ │ ├── account_id.d.ts │ │ │ ├── account_id.js │ │ │ ├── collections.d.ts │ │ │ ├── collections.js │ │ │ ├── gas.d.ts │ │ │ ├── gas.js │ │ │ ├── index.d.ts │ │ │ ├── index.js │ │ │ ├── primitives.d.ts │ │ │ ├── primitives.js │ │ │ ├── public_key.d.ts │ │ │ ├── public_key.js │ │ │ ├── vm_types.d.ts │ │ │ └── vm_types.js │ │ ├── utils.d.ts │ │ ├── utils.js │ │ ├── version.d.ts │ │ └── version.js │ ├── package.json │ ├── src/ │ │ ├── api.ts │ │ ├── cli/ │ │ │ ├── abi.ts │ │ │ ├── build-tools/ │ │ │ │ ├── include-bytes.ts │ │ │ │ └── near-bindgen-exporter.ts │ │ │ ├── cli.ts │ │ │ ├── post-install.ts │ │ │ └── utils.ts │ │ ├── collections/ │ │ │ ├── index.ts │ │ │ ├── lookup-map.ts │ │ │ ├── lookup-set.ts │ │ │ ├── subtype.ts │ │ │ ├── unordered-map.ts │ │ │ ├── unordered-set.ts │ │ │ └── vector.ts │ │ ├── index.ts │ │ ├── near-bindgen.ts │ │ ├── promise.ts │ │ ├── types/ │ │ │ ├── account_id.ts │ │ │ ├── collections.ts │ │ │ ├── gas.ts │ │ │ ├── index.ts │ │ │ ├── primitives.ts │ │ │ ├── public_key.ts │ │ │ └── vm_types.ts │ │ ├── utils.ts │ │ └── version.ts │ ├── tsconfig.json │ └── typedoc.json ├── pnpm-workspace.yaml ├── tests/ │ ├── .gitignore │ ├── README.md │ ├── __tests__/ │ │ ├── abi/ │ │ │ ├── abi.ava.js │ │ │ ├── testcases/ │ │ │ │ ├── json_schema.ts │ │ │ │ ├── modifiers.ts │ │ │ │ ├── return.ts │ │ │ │ └── simple_function.ts │ │ │ └── util.js │ │ ├── bytes.ava.js │ │ ├── constructor_validation.ava.js │ │ ├── decorators/ │ │ │ ├── migrate.ava.js │ │ │ ├── near_bindgen.ava.js │ │ │ ├── payable.ava.js │ │ │ └── private.ava.js │ │ ├── function-params.ava.js │ │ ├── lookup-map.ava.js │ │ ├── lookup-set.ava.js │ │ ├── test-bigint-serialization.ava.js │ │ ├── test-date-serialization.ava.js │ │ ├── test-middlewares.ava.js │ │ ├── test-public-key.ava.js │ │ ├── test_alt_bn128_api.ava.js │ │ ├── test_context_api.ava.js │ │ ├── test_highlevel_promise.ava.js │ │ ├── test_log_panic_api.ava.js │ │ ├── test_math_api.ava.js │ │ ├── test_promise_api.ava.js │ │ ├── test_storage_api.ava.js │ │ ├── typescript.ava.js │ │ ├── unordered-map.ava.js │ │ ├── unordered-set.ava.js │ │ └── vector.ava.js │ ├── ava.config.cjs │ ├── jsconfig.json │ ├── package.json │ ├── src/ │ │ ├── alt_bn128_api.js │ │ ├── bigint-serialization.ts │ │ ├── bytes.js │ │ ├── constructor-validation/ │ │ │ ├── 1-parameter-not-set-in-constructor.ts │ │ │ ├── all-parameters-set-in-constructor.ts │ │ │ ├── no-constructor.ts │ │ │ └── no-parameters-set-in-constructor.ts │ │ ├── context_api.js │ │ ├── date-serialization.ts │ │ ├── decorators/ │ │ │ ├── payable.ts │ │ │ ├── private.ts │ │ │ ├── require_init_false.ts │ │ │ └── require_init_true.ts │ │ ├── function-params.js │ │ ├── highlevel-promise.js │ │ ├── log_panic_api.js │ │ ├── lookup-map.js │ │ ├── lookup-set.js │ │ ├── math_api.js │ │ ├── middlewares.ts │ │ ├── migrate.ts │ │ ├── model.js │ │ ├── promise_api.js │ │ ├── promise_batch_api.js │ │ ├── public-key.js │ │ ├── storage_api.js │ │ ├── typescript.ts │ │ ├── unordered-map.js │ │ ├── unordered-set.js │ │ └── vector.js │ └── tsconfig.json ├── turbo.json └── typedoc.json
SYMBOL INDEX (1714 symbols across 191 files)
FILE: benchmark/__tests__/test-collections-performance.ava.js
constant COLLECTION_SIZE (line 5) | const COLLECTION_SIZE = 20;
FILE: benchmark/__tests__/util.js
function formatGas (line 3) | function formatGas(gas) {
function gasBreakdown (line 14) | function gasBreakdown(outcome) {
function logGasBreakdown (line 22) | function logGasBreakdown(map, t) {
function logGasDetail (line 28) | function logGasDetail(r, t) {
function logTotalGas (line 55) | function logTotalGas(prefix = '', r, t) {
function randomInt (line 66) | function randomInt(max) {
FILE: benchmark/src/deploy-contract.js
function deploy_contract (line 8) | function deploy_contract() {
FILE: benchmark/src/expensive-calc.js
class ExpensiveCalc (line 9) | class ExpensiveCalc {
method expensive (line 10) | @call({})
FILE: benchmark/src/highlevel-collection.js
class HighlevelCollection (line 8) | class HighlevelCollection {
method constructor (line 9) | constructor() {
method set (line 13) | @call({})
FILE: benchmark/src/highlevel-minimal.js
class HighlevelMinimal (line 8) | class HighlevelMinimal {
method empty (line 9) | @call({})
FILE: benchmark/src/lookup-map.js
class LookupMapContract (line 4) | class LookupMapContract {
method constructor (line 5) | constructor() {
method addElement (line 9) | @call({})
method removeElement (line 14) | @call({})
method getElement (line 19) | @view({})
FILE: benchmark/src/lookup-set.js
class LookupSetContract (line 4) | class LookupSetContract {
method constructor (line 5) | constructor() {
method addElement (line 9) | @call({})
method removeElement (line 14) | @call({})
method containsElement (line 19) | @view({})
FILE: benchmark/src/lowlevel-api.js
function lowlevel_storage_write (line 7) | function lowlevel_storage_write() {
function lowlevel_storage_write_many (line 16) | function lowlevel_storage_write_many() {
FILE: benchmark/src/lowlevel-minimal.js
function empty (line 7) | function empty() {}
FILE: benchmark/src/unordered-map.js
class UnorderedMapContract (line 4) | class UnorderedMapContract {
method constructor (line 5) | constructor() {
method addElement (line 9) | @call({})
method removeElement (line 14) | @call({})
method getElement (line 19) | @view({})
method iterate (line 24) | @view({})
FILE: benchmark/src/unordered-set.js
class UnorderedSetContract (line 4) | class UnorderedSetContract {
method constructor (line 5) | constructor() {
method addElement (line 9) | @call({})
method removeElement (line 14) | @call({})
method containsElement (line 19) | @view({})
method iterate (line 24) | @view({})
FILE: benchmark/src/vector.js
class VectorContract (line 4) | class VectorContract {
method constructor (line 5) | constructor() {
method addElement (line 9) | @call({})
method removeElement (line 14) | @call({})
method getElement (line 19) | @view({})
method iterate (line 24) | @view({})
FILE: examples/__tests__/standard-ft/ft-tests.ava.js
constant INITIAL_BALANCE (line 4) | const INITIAL_BALANCE = NEAR.parse("10000 N").toJSON();
constant ONE_YOCTO (line 5) | const ONE_YOCTO = "1";
constant STOARAGE_BYTE_COST (line 6) | const STOARAGE_BYTE_COST = 10_000_000_000_000_000_000n;
constant ACCOUNT_STORAGE_BALANCE (line 7) | const ACCOUNT_STORAGE_BALANCE = String(STOARAGE_BYTE_COST * 138n);
function registerUser (line 65) | async function registerUser(contract, account_id) {
FILE: examples/__tests__/standard-nft/test_core.ava.js
constant MAX_GAS (line 4) | const MAX_GAS = 300_000_000_000_000n;
FILE: examples/__tests__/standard-nft/test_enumeration.ava.js
function helper_mint (line 4) | async function helper_mint(nft, nftOwner, id, title, description) {
FILE: examples/src/basic-updates/basic-updates-base.js
constant POINT_ONE (line 10) | const POINT_ONE = ONE_NEAR / 10000n;
class PostedMessage (line 12) | class PostedMessage {
method constructor (line 13) | constructor() {
method new (line 19) | static new(premium, sender, text) {
class GuestBook (line 29) | class GuestBook {
method constructor (line 30) | constructor() {
method add_message (line 35) | @call({payableFunction: true})
method get_message (line 45) | @view({})
method get_payment (line 50) | @view({})
FILE: examples/src/basic-updates/basic-updates-update.js
constant POINT_ONE (line 3) | const POINT_ONE = ONE_NEAR / 10000n;
class OldPostedMessage (line 5) | class OldPostedMessage {
method constructor (line 6) | constructor() {
class OldState (line 14) | class OldState {
method constructor (line 15) | constructor() {
class PostedMessage (line 21) | class PostedMessage {
method constructor (line 22) | constructor() {
method new (line 29) | static new(payment, premium, sender, text) {
class GuestBook (line 40) | class GuestBook {
method constructor (line 41) | constructor() {
method migrateState (line 45) | @migrate({})
method add_message (line 70) | @call({payableFunction: true})
method get_message (line 79) | @view({})
FILE: examples/src/clean-state.js
class CleanState (line 4) | class CleanState {
method clean (line 5) | @call({})
method put (line 10) | @call({})
method get (line 15) | @view({})
FILE: examples/src/counter/counter-lowlevel.js
function init (line 4) | function init() {
function deserialize (line 13) | function deserialize() {
function getCount (line 22) | function getCount() {
function increase (line 28) | function increase() {
function decrease (line 38) | function decrease() {
FILE: examples/src/counter/counter.js
class Counter (line 5) | class Counter {
method constructor (line 6) | constructor() {
method increase (line 10) | @call({})
method decrease (line 16) | @call({})
method getCount (line 28) | @view({})
FILE: examples/src/counter/counter.ts
class Counter (line 6) | class Counter {
method increase (line 10) | increase({ n = 1 }: { n: number }) {
method decrease (line 16) | decrease({ n }: { n: number }) {
method getCount (line 29) | getCount(): number {
FILE: examples/src/counter/log.ts
function log (line 3) | function log(msg: unknown) {
FILE: examples/src/cross-contract-calls/cross-contract-call-loop.js
constant CONTRACTS (line 3) | const CONTRACTS = [
constant NO_ARGS (line 8) | const NO_ARGS = "";
constant THIRTY_TGAS (line 9) | const THIRTY_TGAS = BigInt("30" + "0".repeat(12));
class LoopXCC (line 12) | class LoopXCC {
method constructor (line 13) | constructor() {
method incrementCount (line 17) | @call({})
method _incrementCountCallback (line 46) | @call({ privateFunction: true })
method getCount (line 57) | @view({})
FILE: examples/src/cross-contract-calls/cross-contract-call.js
class OnCall (line 4) | class OnCall {
method constructor (line 5) | constructor() {
method init (line 10) | @initialize({})
method set_person_on_call (line 16) | @call({})
method _set_person_on_call_private (line 37) | @call({ privateFunction: true })
method person_on_call (line 50) | @view({})
FILE: examples/src/cross-contract-calls/cross-contract-call.ts
class OnCall (line 4) | class OnCall {
method init (line 9) | init({ statusMessageContract }) {
method set_person_on_call (line 14) | set_person_on_call({ accountId }) {
method _set_person_on_call_private (line 35) | _set_person_on_call_private({ accountId }) {
method person_on_call (line 48) | person_on_call() {
FILE: examples/src/fungible-token/fungible-token-helper.ts
class _FungibleTokenHelper (line 3) | @NearBindgen({})
method ft_on_transfer (line 8) | ft_on_transfer({
method get_contract_data (line 24) | get_contract_data() {
FILE: examples/src/fungible-token/fungible-token-lockable.js
class Account (line 10) | class Account {
method constructor (line 11) | constructor(balance, allowances, lockedBalances) {
method setAllowance (line 17) | setAllowance(escrowAccountId, allowance) {
method getAllowance (line 27) | getAllowance(escrowAccountId) {
method setLockedBalance (line 31) | setLockedBalance(escrowAccountId, lockedBalance) {
method getLockedBalance (line 41) | getLockedBalance(escrowAccountId) {
method totalBalance (line 45) | totalBalance() {
class LockableFungibleToken (line 55) | class LockableFungibleToken {
method constructor (line 56) | constructor() {
method init (line 61) | @initialize({})
method getAccount (line 71) | getAccount(ownerId) {
method setAccount (line 83) | setAccount(accountId, account) {
method setAllowance (line 87) | @call({})
method lock (line 105) | @call({})
method unlock (line 135) | @call({})
method transferFrom (line 162) | @call({})
method transfer (line 208) | @call({})
method getTotalSupply (line 217) | @view({})
method getTotalBalance (line 222) | @view({})
method getUnlockedBalance (line 227) | @view({})
method getAllowance (line 232) | @view({})
method getLockedBalance (line 237) | @view({})
FILE: examples/src/fungible-token/fungible-token.ts
class FungibleToken (line 13) | class FungibleToken {
method constructor (line 19) | constructor() {
method init (line 27) | init({ owner_id, total_supply }: { owner_id: string; total_supply: str...
method internalGetAccountStorageUsage (line 34) | internalGetAccountStorageUsage(accountLength: number): bigint {
method internalRegisterAccount (line 45) | internalRegisterAccount({
method internalSendNEAR (line 63) | internalSendNEAR(receivingAccountId: string, amount: bigint) {
method internalGetBalance (line 75) | internalGetBalance(accountId: string): string {
method internalDeposit (line 83) | internalDeposit(accountId: string, amount: string) {
method internalWithdraw (line 91) | internalWithdraw(accountId: string, amount: string) {
method internalTransfer (line 105) | internalTransfer(
method storage_deposit (line 118) | storage_deposit({ account_id }: { account_id: string }) {
method ft_transfer (line 160) | ft_transfer({
method ft_transfer_call (line 178) | ft_transfer_call({
method ft_total_supply (line 220) | ft_total_supply() {
method ft_balance_of (line 225) | ft_balance_of({ account_id }: { account_id: string }) {
class Assertions (line 231) | class Assertions {
method hasAtLeastOneAttachedYocto (line 232) | static hasAtLeastOneAttachedYocto() {
method isLeftGreaterThanRight (line 239) | static isLeftGreaterThanRight(
FILE: examples/src/fungible-token/my-ft.ts
class FTPrefix (line 27) | class FTPrefix implements IntoStorageKey {
method into_storage_key (line 28) | into_storage_key(): string {
class MyFt (line 34) | class MyFt implements FungibleTokenCore, StorageManagement, FungibleToke...
method constructor (line 38) | constructor() {
method init (line 44) | init({
method init_with_default_meta (line 61) | init_with_default_meta({
method measure_account_storage_usage (line 86) | measure_account_storage_usage() {
method ft_transfer (line 91) | ft_transfer({
method ft_transfer_call (line 104) | ft_transfer_call({
method ft_total_supply (line 119) | ft_total_supply(): Balance {
method ft_balance_of (line 124) | ft_balance_of({ account_id }: { account_id: AccountId }): Balance {
method storage_deposit (line 129) | storage_deposit(
method storage_withdraw (line 142) | storage_withdraw({ amount }: { amount?: bigint }): StorageBalance {
method storage_unregister (line 147) | storage_unregister({ force }: { force?: boolean }): boolean {
method storage_balance_bounds (line 152) | storage_balance_bounds(): StorageBalanceBounds {
method storage_balance_of (line 157) | storage_balance_of({ account_id }: { account_id: AccountId }): Option<...
method ft_resolve_transfer (line 162) | ft_resolve_transfer({
FILE: examples/src/nested-collections.ts
class Contract (line 4) | class Contract {
method constructor (line 8) | constructor() {
method add (line 14) | add({ id, text }: { id: string; text: string }) {
method get (line 24) | get({ id, accountId }: { id: string; accountId: string }) {
method add_to_group (line 35) | add_to_group({
method get_from_group (line 58) | get_from_group({
FILE: examples/src/non-fungible-token/my-nft.ts
class StorageKey (line 31) | class StorageKey { }
class StorageKeyNonFungibleToken (line 33) | class StorageKeyNonFungibleToken extends StorageKey implements IntoStora...
method into_storage_key (line 34) | into_storage_key(): string {
class StorageKeyTokenMetadata (line 39) | class StorageKeyTokenMetadata extends StorageKey implements IntoStorageK...
method into_storage_key (line 40) | into_storage_key(): string {
class StorageKeyTokenEnumeration (line 45) | class StorageKeyTokenEnumeration extends StorageKey implements IntoStora...
method into_storage_key (line 46) | into_storage_key(): string {
class StorageKeyApproval (line 51) | class StorageKeyApproval extends StorageKey implements IntoStorageKey {
method into_storage_key (line 52) | into_storage_key(): string {
class MyNFT (line 58) | class MyNFT
method constructor (line 68) | constructor() {
method nft_total_supply (line 74) | nft_total_supply(): number {
method nft_tokens (line 79) | nft_tokens({
method nft_supply_for_owner (line 90) | nft_supply_for_owner({ account_id }: { account_id: string }): number {
method nft_tokens_for_owner (line 95) | nft_tokens_for_owner({
method nft_approve (line 108) | nft_approve({
method nft_revoke (line 121) | nft_revoke({
method nft_revoke_all (line 132) | nft_revoke_all({ token_id }: { token_id: string }) {
method nft_is_approved (line 137) | nft_is_approved({
method nft_resolve_transfer (line 154) | nft_resolve_transfer({
method nft_metadata (line 174) | nft_metadata(): NFTContractMetadata {
method nft_transfer (line 180) | nft_transfer({
method nft_transfer_call (line 195) | nft_transfer_call({
method nft_token (line 218) | nft_token({ token_id }: { token_id: string }): Option<Token> {
method init (line 223) | init({
method nft_mint (line 243) | nft_mint({
FILE: examples/src/non-fungible-token/non-fungible-token-receiver.js
class NftContract (line 4) | class NftContract {
method constructor (line 5) | constructor() {
method init (line 9) | @initialize({})
method nftOnTransfer (line 14) | @call({})
FILE: examples/src/non-fungible-token/non-fungible-token.js
class Token (line 11) | class Token {
method constructor (line 12) | constructor(token_id, owner_id) {
class NftContract (line 19) | class NftContract {
method constructor (line 20) | constructor() {
method init (line 25) | @initialize({})
method internalTransfer (line 31) | internalTransfer({
method nftTransfer (line 49) | @call({})
method nftTransferCall (line 61) | @call({})
method _nftResolveTransfer (line 98) | @call({ privateFunction: true })
method nftMint (line 130) | @call({})
method nftToken (line 141) | @view({})
FILE: examples/src/non-fungible-token/test-approval-receiver.ts
constant BASE_GAS (line 14) | const BASE_GAS = 20_000_000_000_000n;
constant PROMISE_CALL (line 15) | const PROMISE_CALL = 20_000_000_000_000n;
constant GAS_FOR_NFT_ON_APPROVE (line 16) | const GAS_FOR_NFT_ON_APPROVE = BASE_GAS + PROMISE_CALL;
type ValueReturnInterface (line 18) | interface ValueReturnInterface {
class ApprovalReceiver (line 23) | class ApprovalReceiver
method constructor (line 28) | constructor() {
method nft_on_approve (line 33) | nft_on_approve({
method ok_go (line 69) | ok_go({ msg }: { msg: string }): PromiseOrValue<string> {
method init (line 75) | init({
FILE: examples/src/non-fungible-token/test-token-receiver.ts
constant BASE_GAS (line 14) | const BASE_GAS = 10_000_000_000_000n;
constant PROMISE_CALL (line 15) | const PROMISE_CALL = 10_000_000_000_000n;
constant GAS_FOR_NFT_ON_TRANSFER (line 16) | const GAS_FOR_NFT_ON_TRANSFER = BASE_GAS + PROMISE_CALL;
type ValueReturnInterface (line 18) | interface ValueReturnInterface {
class TokenReceiver (line 23) | class TokenReceiver
method constructor (line 28) | constructor() {
method init (line 33) | init({
method nft_on_transfer (line 42) | nft_on_transfer({
method ok_go (line 91) | ok_go({ return_it }: { return_it: boolean }): PromiseOrValue<boolean> {
FILE: examples/src/parking-lot.ts
class CarSpecs (line 3) | class CarSpecs {
method constructor (line 9) | constructor(id: number, color: string, price: number, engine: Engine) {
class Engine (line 17) | class Engine {
method constructor (line 20) | constructor(hp: number) {
method run (line 24) | run(): string {
class ParkingLot (line 34) | class ParkingLot {
method constructor (line 37) | constructor() {
method addCar (line 42) | addCar({
method removeCar (line 64) | removeCar({ name }: { name: string }) {
method getCarSpecs (line 70) | getCarSpecs({ name }: { name: string }): CarSpecs {
method runCar (line 76) | runCar({ name }: { name: string }) {
FILE: examples/src/programmatic-updates/programmatic-update-after.ts
class ProgrammaticUpdateAfter (line 4) | class ProgrammaticUpdateAfter {
method init (line 8) | init({ manager }: { manager: string }) {
method view_greeting (line 14) | view_greeting(): string {
function updateContract (line 19) | function updateContract() {
FILE: examples/src/programmatic-updates/programmatic-update-before.ts
class ProgrammaticUpdateBefore (line 4) | class ProgrammaticUpdateBefore {
method init (line 8) | init({ manager }: { manager: string }) {
method get_greeting (line 14) | get_greeting(): string {
function updateContract (line 19) | function updateContract() {
FILE: examples/src/state-migration/state-migration-new.ts
type OldMessageFormat (line 4) | type OldMessageFormat = {
type NewMessageFormat (line 11) | type NewMessageFormat = {
class MigrationDemo (line 19) | class MigrationDemo {
method constructor (line 22) | constructor() {
method addMessage (line 27) | addMessage({ message }: {
method countMessages (line 35) | countMessages(): number {
method migrateState (line 41) | migrateState(): Vector<NewMessageFormat> {
FILE: examples/src/state-migration/state-migration-original.ts
type Message (line 4) | type Message = {
class MigrationDemo (line 11) | class MigrationDemo {
method constructor (line 14) | constructor() {
method addMessage (line 19) | addMessage({ message }: {
method countMessages (line 27) | countMessages(): number {
FILE: examples/src/status-deserialize-class.js
class Car (line 12) | class Car {
method constructor (line 17) | constructor() {
method info (line 22) | info() {
class Truck (line 27) | class Truck {
method constructor (line 33) | constructor() {
method info (line 39) | info() {
class StatusDeserializeClass (line 48) | class StatusDeserializeClass {
method constructor (line 61) | constructor() {
method init_contract (line 85) | @call({})
method is_contract_inited (line 94) | @view({})
method set_record (line 100) | @call({})
method get_record (line 107) | @view({})
method set_truck_info (line 114) | @call({})
method add_truck_load (line 129) | @call({})
method get_truck_info (line 136) | @view({})
method get_user_car_info (line 142) | @view({})
method push_message (line 152) | @call({})
method get_messages (line 159) | @view({})
method set_nested_efficient_recordes (line 165) | @call({})
method set_big_num_and_date (line 202) | @call({})
method get_big_num (line 210) | @view({})
method get_date (line 216) | @view({})
method get_efficient_recordes (line 222) | @view({})
method get_nested_efficient_recordes (line 228) | @view({})
method get_nested_lookup_recordes (line 236) | @view({})
method get_vector_nested_group (line 244) | @view({})
method get_lookup_nested_vec (line 250) | @view({})
method get_is_contains_user (line 256) | @view({})
method set_extra_data (line 262) | @call({})
method get_extra_msg (line 270) | @view({})
method get_extra_number (line 276) | @view({})
method set_extra_record (line 282) | @call({})
method get_extra_record (line 289) | @view({})
method get_subtype_of_efficient_recordes (line 295) | @view({})
method get_subtype_of_nested_efficient_recordes (line 301) | @view({})
method get_subtype_of_nested_lookup_recordes (line 307) | @view({})
FILE: examples/src/status-message/status-message-borsh.js
method serializer (line 9) | serializer(statusMessage) {
method deserializer (line 12) | deserializer(value) {
class StatusMessage (line 16) | class StatusMessage {
method constructor (line 17) | constructor() {
method set_status (line 21) | @call({})
method get_status (line 28) | @view({})
FILE: examples/src/status-message/status-message-collections.js
class StatusMessage (line 11) | class StatusMessage {
method constructor (line 12) | constructor() {
method set_status (line 17) | @call({})
method get_status (line 25) | @view({})
method has_status (line 31) | @view({})
method get_all_statuses (line 37) | @view({})
FILE: examples/src/status-message/status-message-deserialize-err.js
method deserializer (line 4) | deserializer(_value) {
class StatusMessage (line 8) | class StatusMessage {
method constructor (line 9) | constructor() {
method set_status (line 13) | @call({})
method get_status (line 20) | @view({})
FILE: examples/src/status-message/status-message-migrate-add-field.js
class OldStatusMessage (line 3) | class OldStatusMessage {
method constructor (line 4) | constructor() {
class StatusMessage (line 10) | class StatusMessage {
method constructor (line 11) | constructor() {
method set_status (line 16) | @call({})
method set_new_status (line 23) | @call({})
method get_status (line 30) | @view({})
method get_new_status (line 36) | @view({})
method migrateState (line 43) | @migrate({})
FILE: examples/src/status-message/status-message-serialize-err.js
method serializer (line 4) | serializer(_value) {
class StatusMessage (line 8) | class StatusMessage {
method constructor (line 9) | constructor() {
method set_status (line 13) | @call({})
method get_status (line 20) | @view({})
FILE: examples/src/status-message/status-message.js
class StatusMessage (line 4) | class StatusMessage {
method constructor (line 5) | constructor() {
method set_status (line 9) | @call({})
method get_status (line 16) | @view({})
FILE: packages/near-contract-standards/lib/event.js
class NearEvent (line 2) | class NearEvent {
method internal_to_json_string (line 3) | internal_to_json_string() {
method internal_to_json_event_string (line 6) | internal_to_json_event_string() {
method emit (line 13) | emit() {
FILE: packages/near-contract-standards/lib/fungible_token/core.d.ts
type FungibleTokenCore (line 54) | interface FungibleTokenCore {
FILE: packages/near-contract-standards/lib/fungible_token/core_impl.d.ts
class FungibleToken (line 16) | class FungibleToken implements FungibleTokenCore, StorageManagement, Fun...
FILE: packages/near-contract-standards/lib/fungible_token/core_impl.js
constant GAS_FOR_RESOLVE_TRANSFER (line 6) | const GAS_FOR_RESOLVE_TRANSFER = 15000000000000n;
constant GAS_FOR_FT_TRANSFER_CALL (line 7) | const GAS_FOR_FT_TRANSFER_CALL = 25000000000000n + GAS_FOR_RESOLVE_TRANS...
constant ERR_TOTAL_SUPPLY_OVERFLOW (line 8) | const ERR_TOTAL_SUPPLY_OVERFLOW = "Total supply overflow";
class FungibleToken (line 19) | class FungibleToken {
method constructor (line 20) | constructor() {
method init (line 27) | init(prefix) {
method measure_account_storage_usage (line 35) | measure_account_storage_usage() {
method internal_unwrap_balance_of (line 42) | internal_unwrap_balance_of(account_id) {
method internal_deposit (line 49) | internal_deposit(account_id, amount) {
method internal_withdraw (line 56) | internal_withdraw(account_id, amount) {
method internal_transfer (line 66) | internal_transfer(sender_id, receiver_id, amount, memo) {
method internal_register_account (line 73) | internal_register_account(account_id) {
method internal_ft_resolve_transfer (line 83) | internal_ft_resolve_transfer(sender_id, receiver_id, amount) {
method ft_transfer (line 134) | ft_transfer({ receiver_id, amount, memo }) {
method ft_transfer_call (line 140) | ft_transfer_call({ receiver_id, amount, memo, msg }) {
method ft_total_supply (line 155) | ft_total_supply() {
method ft_balance_of (line 158) | ft_balance_of({ account_id }) {
method internal_storage_unregister (line 165) | internal_storage_unregister(force) {
method internal_storage_balance_of (line 185) | internal_storage_balance_of(account_id) {
method storage_deposit (line 196) | storage_deposit({ account_id, registration_only, }) {
method storage_withdraw (line 226) | storage_withdraw({ amount }) {
method storage_unregister (line 241) | storage_unregister({ force }) {
method storage_balance_bounds (line 244) | storage_balance_bounds() {
method storage_balance_of (line 248) | storage_balance_of({ account_id }) {
method ft_resolve_transfer (line 252) | ft_resolve_transfer({ sender_id, receiver_id, amount }) {
method reconstruct (line 262) | static reconstruct(data) {
FILE: packages/near-contract-standards/lib/fungible_token/events.d.ts
type Nep141EventKind (line 20) | type Nep141EventKind = FtMint[] | FtTransfer[] | FtBurn[];
class Nep141Event (line 21) | class Nep141Event extends NearEvent {
class FtMint (line 29) | class FtMint {
class FtTransfer (line 46) | class FtTransfer {
class FtBurn (line 62) | class FtBurn {
FILE: packages/near-contract-standards/lib/fungible_token/events.js
class Nep141Event (line 19) | class Nep141Event extends NearEvent {
method constructor (line 20) | constructor(version, event_kind) {
class FtMint (line 29) | class FtMint {
method constructor (line 30) | constructor(owner_id, amount, memo) {
method emit (line 38) | emit() {
method emit_many (line 44) | emit_many(data) {
class FtTransfer (line 51) | class FtTransfer {
method constructor (line 52) | constructor(old_owner_id, new_owner_id, amount, memo) {
method emit (line 61) | emit() {
method emit_many (line 67) | emit_many(data) {
class FtBurn (line 72) | class FtBurn {
method constructor (line 73) | constructor(owner_id, amount, memo) {
method emit (line 81) | emit() {
method emit_many (line 87) | emit_many(data) {
function new_141 (line 91) | function new_141(version, event_kind) {
function new_141_v1 (line 94) | function new_141_v1(event_kind) {
FILE: packages/near-contract-standards/lib/fungible_token/metadata.d.ts
class FungibleTokenMetadata (line 5) | class FungibleTokenMetadata {
type FungibleTokenMetadataProvider (line 16) | interface FungibleTokenMetadataProvider {
FILE: packages/near-contract-standards/lib/fungible_token/metadata.js
constant FT_METADATA_SPEC (line 2) | const FT_METADATA_SPEC = "ft-1.0.0";
class FungibleTokenMetadata (line 6) | class FungibleTokenMetadata {
method constructor (line 7) | constructor(spec, name, symbol, icon, referance, referance_hash, decim...
method assert_valid (line 16) | assert_valid() {
FILE: packages/near-contract-standards/lib/fungible_token/receiver.d.ts
type FungibleTokenReceiver (line 31) | interface FungibleTokenReceiver {
FILE: packages/near-contract-standards/lib/fungible_token/resolver.d.ts
type FungibleTokenResolver (line 42) | interface FungibleTokenResolver {
FILE: packages/near-contract-standards/lib/non_fungible_token/approval/approval_receiver.d.ts
type NonFungibleTokenApprovalReceiver (line 4) | interface NonFungibleTokenApprovalReceiver {
FILE: packages/near-contract-standards/lib/non_fungible_token/approval/index.d.ts
type NonFungibleTokenApproval (line 14) | interface NonFungibleTokenApproval {
FILE: packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts
type NonFungibleTokenCore (line 59) | interface NonFungibleTokenCore {
FILE: packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts
type NonFungibleTokenReceiver (line 43) | interface NonFungibleTokenReceiver {
FILE: packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts
type NonFungibleTokenResolver (line 40) | interface NonFungibleTokenResolver {
FILE: packages/near-contract-standards/lib/non_fungible_token/enumeration/index.d.ts
type NonFungibleTokenEnumeration (line 4) | interface NonFungibleTokenEnumeration {
FILE: packages/near-contract-standards/lib/non_fungible_token/events.d.ts
type Nep171EventKind (line 19) | type Nep171EventKind = NftMint[] | NftTransfer[] | NftBurn[] | NftContra...
class Nep171Event (line 20) | class Nep171Event extends NearEvent {
class NftMint (line 28) | class NftMint {
class NftTransfer (line 42) | class NftTransfer {
class NftBurn (line 57) | class NftBurn {
class NftContractMetadataUpdate (line 71) | class NftContractMetadataUpdate {
FILE: packages/near-contract-standards/lib/non_fungible_token/events.js
class Nep171Event (line 3) | class Nep171Event extends NearEvent {
method constructor (line 4) | constructor(version, event_kind) {
class NftMint (line 13) | class NftMint {
method constructor (line 14) | constructor(owner_id, token_ids, memo) {
method emit (line 21) | emit() {
method emit_many (line 26) | static emit_many(data) {
class NftTransfer (line 32) | class NftTransfer {
method constructor (line 33) | constructor(old_owner_id, new_owner_id, token_ids, authorized_id, memo) {
method emit (line 42) | emit() {
method emit_many (line 47) | static emit_many(data) {
class NftBurn (line 52) | class NftBurn {
method constructor (line 53) | constructor(owner_id, token_ids, authorized_id, memo) {
method emit (line 61) | emit() {
method emit_many (line 66) | static emit_many(data) {
class NftContractMetadataUpdate (line 71) | class NftContractMetadataUpdate {
method constructor (line 72) | constructor(memo) {
method emit (line 77) | emit() {
method emit_many (line 82) | static emit_many(data) {
function new_171 (line 86) | function new_171(version, event_kind) {
function new_171_v1 (line 89) | function new_171_v1(event_kind) {
FILE: packages/near-contract-standards/lib/non_fungible_token/impl.d.ts
class NonFungibleToken (line 19) | class NonFungibleToken implements NonFungibleTokenCore, NonFungibleToken...
type StorageKey (line 96) | type StorageKey = TokensPerOwner | TokenPerOwnerInner;
class TokensPerOwner (line 97) | class TokensPerOwner implements IntoStorageKey {
class TokenPerOwnerInner (line 102) | class TokenPerOwnerInner implements IntoStorageKey {
FILE: packages/near-contract-standards/lib/non_fungible_token/impl.js
constant GAS_FOR_RESOLVE_TRANSFER (line 6) | const GAS_FOR_RESOLVE_TRANSFER = 16000000000000n;
constant GAS_FOR_NFT_TRANSFER_CALL (line 7) | const GAS_FOR_NFT_TRANSFER_CALL = 30000000000000n + GAS_FOR_RESOLVE_TRAN...
constant GAS_FOR_NFT_APPROVE (line 8) | const GAS_FOR_NFT_APPROVE = 21000000000000n;
function repeat (line 9) | function repeat(str, n) {
function expect_token_found (line 12) | function expect_token_found(option) {
function expect_approval (line 18) | function expect_approval(option) {
class NonFungibleToken (line 34) | class NonFungibleToken {
method constructor (line 35) | constructor() {
method nft_total_supply (line 44) | nft_total_supply() {
method enum_get_token (line 47) | enum_get_token(owner_id, token_id) {
method nft_tokens (line 56) | nft_tokens({ from_index, limit, }) {
method nft_supply_for_owner (line 70) | nft_supply_for_owner({ account_id }) {
method nft_tokens_for_owner (line 78) | nft_tokens_for_owner({ account_id, from_index, limit, }) {
method nft_approve (line 98) | nft_approve({ token_id, account_id, msg, }) {
method nft_revoke (line 121) | nft_revoke({ token_id, account_id, }) {
method nft_revoke_all (line 146) | nft_revoke_all({ token_id }) {
method nft_is_approved (line 161) | nft_is_approved({ token_id, approved_account_id, approval_id, }) {
method init (line 180) | init(owner_by_id_prefix, owner_id, token_metadata_prefix, enumeration_...
method reconstruct (line 205) | static reconstruct(data) {
method measure_min_token_storage_cost (line 223) | measure_min_token_storage_cost() {
method internal_transfer_unguarded (line 267) | internal_transfer_unguarded(token_id, from, to) {
method internal_transfer (line 293) | internal_transfer(sender_id, receiver_id, token_id, approval_id, memo) {
method emit_transfer (line 319) | static emit_transfer(owner_id, receiver_id, token_id, sender_id, memo) {
method internal_mint (line 322) | internal_mint(token_id, token_owner_id, token_metadata) {
method internal_mint_with_refund (line 327) | internal_mint_with_refund(token_id, token_owner_id, token_metadata, re...
method nft_transfer (line 358) | nft_transfer({ receiver_id, token_id, approval_id, memo, }) {
method nft_transfer_call (line 363) | nft_transfer_call({ receiver_id, token_id, approval_id, memo, msg, }) {
method nft_token (line 378) | nft_token({ token_id }) {
method nft_resolve_transfer (line 389) | nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, appro...
class TokensPerOwner (line 446) | class TokensPerOwner {
method constructor (line 447) | constructor(account_hash) {
method into_storage_key (line 450) | into_storage_key() {
class TokenPerOwnerInner (line 454) | class TokenPerOwnerInner {
method constructor (line 455) | constructor(account_id_hash) {
method into_storage_key (line 458) | into_storage_key() {
FILE: packages/near-contract-standards/lib/non_fungible_token/metadata.d.ts
class NFTContractMetadata (line 5) | class NFTContractMetadata {
class TokenMetadata (line 19) | class TokenMetadata {
type NonFungibleTokenMetadataProvider (line 48) | interface NonFungibleTokenMetadataProvider {
FILE: packages/near-contract-standards/lib/non_fungible_token/metadata.js
constant NFT_METADATA_SPEC (line 3) | const NFT_METADATA_SPEC = "nft-1.0.0";
class NFTContractMetadata (line 5) | class NFTContractMetadata {
method constructor (line 6) | constructor() {
method init (line 15) | init(spec, name, symbol, icon, base_uri, reference, reference_hash) {
method assert_valid (line 24) | assert_valid() {
method reconstruct (line 31) | static reconstruct(data) {
class TokenMetadata (line 38) | class TokenMetadata {
method constructor (line 39) | constructor(title, // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
method assert_valid (line 65) | assert_valid() {
method reconstruct (line 75) | static reconstruct(data) {
FILE: packages/near-contract-standards/lib/non_fungible_token/token.d.ts
type TokenId (line 4) | type TokenId = string;
class Token (line 6) | class Token {
FILE: packages/near-contract-standards/lib/non_fungible_token/token.js
class Token (line 2) | class Token {
method constructor (line 3) | constructor(token_id, owner_id, metadata, approved_account_ids) {
FILE: packages/near-contract-standards/lib/non_fungible_token/utils.d.ts
type Option (line 11) | type Option<T> = T | null;
FILE: packages/near-contract-standards/lib/non_fungible_token/utils.js
function refund_storage_deposit (line 2) | function refund_storage_deposit(account_id, storage_released) {
function refund_deposit_to_account (line 7) | function refund_deposit_to_account(storage_used, account_id) {
function refund_deposit (line 19) | function refund_deposit(storage_used) {
function hash_account_id (line 22) | function hash_account_id(account_id) {
function assert_at_least_one_yocto (line 26) | function assert_at_least_one_yocto() {
function assert_one_yocto (line 30) | function assert_one_yocto() {
FILE: packages/near-contract-standards/lib/storage_management/index.d.ts
class StorageBalance (line 3) | class StorageBalance {
class StorageBalanceBounds (line 8) | class StorageBalanceBounds {
type StorageManagement (line 13) | interface StorageManagement {
FILE: packages/near-contract-standards/lib/storage_management/index.js
class StorageBalance (line 1) | class StorageBalance {
method constructor (line 2) | constructor(total, available) {
class StorageBalanceBounds (line 7) | class StorageBalanceBounds {
method constructor (line 8) | constructor(min, max) {
FILE: packages/near-contract-standards/src/event.ts
method internal_to_json_string (line 5) | private internal_to_json_string(): string {
method internal_to_json_event_string (line 9) | private internal_to_json_event_string(): string {
method emit (line 17) | emit(): void {
FILE: packages/near-contract-standards/src/fungible_token/core.ts
type FungibleTokenCore (line 55) | interface FungibleTokenCore {
FILE: packages/near-contract-standards/src/fungible_token/core_impl.ts
constant GAS_FOR_RESOLVE_TRANSFER (line 23) | const GAS_FOR_RESOLVE_TRANSFER: Gas = 15_000_000_000_000n;
constant GAS_FOR_FT_TRANSFER_CALL (line 24) | const GAS_FOR_FT_TRANSFER_CALL: Gas = 25_000_000_000_000n + GAS_FOR_RESO...
constant ERR_TOTAL_SUPPLY_OVERFLOW (line 25) | const ERR_TOTAL_SUPPLY_OVERFLOW: string = "Total supply overflow";
class FungibleToken (line 37) | class FungibleToken implements FungibleTokenCore, StorageManagement, Fun...
method constructor (line 47) | constructor() {
method init (line 53) | init(prefix: IntoStorageKey) {
method measure_account_storage_usage (line 63) | measure_account_storage_usage() {
method internal_unwrap_balance_of (line 71) | internal_unwrap_balance_of(account_id: AccountId): Balance {
method internal_deposit (line 79) | internal_deposit(account_id: AccountId, amount: Balance) {
method internal_withdraw (line 87) | internal_withdraw(account_id: AccountId, amount: Balance) {
method internal_transfer (line 98) | internal_transfer(
method internal_register_account (line 111) | internal_register_account(account_id: AccountId) {
method internal_ft_resolve_transfer (line 122) | internal_ft_resolve_transfer(sender_id: AccountId, receiver_id: Accoun...
method ft_transfer (line 182) | ft_transfer({
method ft_transfer_call (line 197) | ft_transfer_call({
method ft_total_supply (line 231) | ft_total_supply(): Balance {
method ft_balance_of (line 235) | ft_balance_of({ account_id }: { account_id: AccountId }): Balance {
method internal_storage_unregister (line 243) | internal_storage_unregister(force?: boolean): Option<[AccountId, Balan...
method internal_storage_balance_of (line 263) | internal_storage_balance_of(account_id: AccountId): Option<StorageBala...
method storage_deposit (line 274) | storage_deposit(
method storage_withdraw (line 313) | storage_withdraw({ amount }: { amount?: bigint }): StorageBalance {
method storage_unregister (line 328) | storage_unregister({ force }: { force?: boolean }): boolean {
method storage_balance_bounds (line 332) | storage_balance_bounds(): StorageBalanceBounds {
method storage_balance_of (line 337) | storage_balance_of({ account_id }: { account_id: AccountId }): Option<...
method ft_resolve_transfer (line 342) | ft_resolve_transfer({
method reconstruct (line 364) | static reconstruct(data: FungibleToken): FungibleToken {
FILE: packages/near-contract-standards/src/fungible_token/events.ts
type Nep141EventKind (line 23) | type Nep141EventKind = FtMint[] | FtTransfer[] | FtBurn[];
class Nep141Event (line 25) | class Nep141Event extends NearEvent {
method constructor (line 31) | constructor(version: string, event_kind: Nep141EventKind) {
class FtMint (line 41) | class FtMint {
method constructor (line 46) | constructor(owner_id: AccountId, amount: number, memo: Option<string>) {
method emit (line 55) | emit() {
method emit_many (line 62) | emit_many(data: FtMint[]) {
class FtTransfer (line 70) | class FtTransfer {
method constructor (line 76) | constructor(old_owner_id: AccountId, new_owner_id: AccountId, amount: ...
method emit (line 86) | emit() {
method emit_many (line 93) | emit_many(data: FtTransfer[]) {
class FtBurn (line 99) | class FtBurn {
method constructor (line 104) | constructor(owner_id: AccountId, amount: Balance, memo: Option<string>) {
method emit (line 113) | emit() {
method emit_many (line 120) | emit_many(data: FtBurn[]) {
function new_141 (line 125) | function new_141(version: string, event_kind: Nep141EventKind): NearEvent {
function new_141_v1 (line 129) | function new_141_v1(event_kind: Nep141EventKind) : NearEvent {
FILE: packages/near-contract-standards/src/fungible_token/metadata.ts
constant FT_METADATA_SPEC (line 7) | const FT_METADATA_SPEC: string = "ft-1.0.0";
class FungibleTokenMetadata (line 12) | class FungibleTokenMetadata {
method constructor (line 21) | constructor(
method assert_valid (line 39) | assert_valid() {
type FungibleTokenMetadataProvider (line 50) | interface FungibleTokenMetadataProvider {
FILE: packages/near-contract-standards/src/fungible_token/receiver.ts
type FungibleTokenReceiver (line 32) | interface FungibleTokenReceiver {
FILE: packages/near-contract-standards/src/fungible_token/resolver.ts
type FungibleTokenResolver (line 43) | interface FungibleTokenResolver {
FILE: packages/near-contract-standards/src/non_fungible_token/approval/approval_receiver.ts
type NonFungibleTokenApprovalReceiver (line 5) | interface NonFungibleTokenApprovalReceiver {
FILE: packages/near-contract-standards/src/non_fungible_token/approval/index.ts
type NonFungibleTokenApproval (line 15) | interface NonFungibleTokenApproval {
FILE: packages/near-contract-standards/src/non_fungible_token/core/index.ts
type NonFungibleTokenCore (line 60) | interface NonFungibleTokenCore {
FILE: packages/near-contract-standards/src/non_fungible_token/core/receiver.ts
type NonFungibleTokenReceiver (line 5) | interface NonFungibleTokenReceiver {
FILE: packages/near-contract-standards/src/non_fungible_token/core/resolver.ts
type NonFungibleTokenResolver (line 41) | interface NonFungibleTokenResolver {
FILE: packages/near-contract-standards/src/non_fungible_token/enumeration/index.ts
type NonFungibleTokenEnumeration (line 5) | interface NonFungibleTokenEnumeration {
FILE: packages/near-contract-standards/src/non_fungible_token/events.ts
type Nep171EventKind (line 21) | type Nep171EventKind = NftMint[] | NftTransfer[] | NftBurn[] | NftContra...
class Nep171Event (line 23) | class Nep171Event extends NearEvent {
method constructor (line 29) | constructor(version: string, event_kind: Nep171EventKind) {
class NftMint (line 39) | class NftMint {
method constructor (line 40) | constructor(
method emit (line 48) | emit() {
method emit_many (line 54) | static emit_many(data: NftMint[]) {
class NftTransfer (line 61) | class NftTransfer {
method constructor (line 62) | constructor(
method emit (line 72) | emit() {
method emit_many (line 78) | static emit_many(data: NftTransfer[]) {
class NftBurn (line 84) | class NftBurn {
method constructor (line 85) | constructor(
method emit (line 94) | emit() {
method emit_many (line 100) | static emit_many(data: NftBurn[]) {
class NftContractMetadataUpdate (line 106) | class NftContractMetadataUpdate {
method constructor (line 107) | constructor(
method emit (line 113) | emit() {
method emit_many (line 119) | static emit_many(data: NftContractMetadataUpdate[]) {
function new_171 (line 124) | function new_171(version: string, event_kind: Nep171EventKind): NearEvent {
function new_171_v1 (line 128) | function new_171_v1(event_kind: Nep171EventKind): NearEvent {
FILE: packages/near-contract-standards/src/non_fungible_token/impl.ts
constant GAS_FOR_RESOLVE_TRANSFER (line 30) | const GAS_FOR_RESOLVE_TRANSFER = 16_000_000_000_000n;
constant GAS_FOR_NFT_TRANSFER_CALL (line 31) | const GAS_FOR_NFT_TRANSFER_CALL =
constant GAS_FOR_NFT_APPROVE (line 33) | const GAS_FOR_NFT_APPROVE = 21_000_000_000_000n;
function repeat (line 35) | function repeat(str: string, n: number) {
function expect_token_found (line 39) | function expect_token_found<T>(option: Option<T>): T {
function expect_approval (line 46) | function expect_approval<T>(option: Option<T>): T {
class NonFungibleToken (line 63) | class NonFungibleToken
method constructor (line 78) | constructor() {
method nft_total_supply (line 88) | nft_total_supply(): number {
method enum_get_token (line 92) | private enum_get_token(owner_id: AccountId, token_id: TokenId): Token {
method nft_tokens (line 102) | nft_tokens({
method nft_supply_for_owner (line 126) | nft_supply_for_owner({ account_id }: { account_id: AccountId }): number {
method nft_tokens_for_owner (line 139) | nft_tokens_for_owner({
method nft_approve (line 176) | nft_approve({
method nft_revoke (line 225) | nft_revoke({
method nft_revoke_all (line 266) | nft_revoke_all({ token_id }: { token_id: TokenId }) {
method nft_is_approved (line 291) | nft_is_approved({
method init (line 323) | init(
method reconstruct (line 357) | static reconstruct(data: NonFungibleToken): NonFungibleToken {
method measure_min_token_storage_cost (line 380) | measure_min_token_storage_cost() {
method internal_transfer_unguarded (line 448) | internal_transfer_unguarded(
method internal_transfer (line 482) | internal_transfer(
method emit_transfer (line 527) | static emit_transfer(
method internal_mint (line 543) | internal_mint(
method internal_mint_with_refund (line 558) | internal_mint_with_refund(
method nft_transfer (line 599) | nft_transfer({
method nft_transfer_call (line 615) | nft_transfer_call({
method nft_token (line 665) | nft_token({ token_id }: { token_id: TokenId }): Option<Token> {
method nft_resolve_transfer (line 679) | nft_resolve_transfer({
type StorageKey (line 758) | type StorageKey = TokensPerOwner | TokenPerOwnerInner;
class TokensPerOwner (line 760) | class TokensPerOwner implements IntoStorageKey {
method constructor (line 761) | constructor(public account_hash: Uint8Array) {}
method into_storage_key (line 763) | into_storage_key(): string {
class TokenPerOwnerInner (line 768) | class TokenPerOwnerInner implements IntoStorageKey {
method constructor (line 769) | constructor(public account_id_hash: Uint8Array) {}
method into_storage_key (line 771) | into_storage_key(): string {
FILE: packages/near-contract-standards/src/non_fungible_token/metadata.ts
constant NFT_METADATA_SPEC (line 5) | const NFT_METADATA_SPEC = "nft-1.0.0";
class NFTContractMetadata (line 8) | class NFTContractMetadata {
method constructor (line 17) | constructor() {
method init (line 27) | init(
method assert_valid (line 45) | assert_valid() {
method reconstruct (line 56) | static reconstruct(data: NFTContractMetadata): NFTContractMetadata {
class TokenMetadata (line 64) | class TokenMetadata {
method constructor (line 65) | constructor(
method assert_valid (line 80) | assert_valid() {
method reconstruct (line 101) | static reconstruct(data: TokenMetadata): TokenMetadata {
type NonFungibleTokenMetadataProvider (line 120) | interface NonFungibleTokenMetadataProvider {
FILE: packages/near-contract-standards/src/non_fungible_token/token.ts
type TokenId (line 5) | type TokenId = string;
class Token (line 8) | class Token {
method constructor (line 9) | constructor(
FILE: packages/near-contract-standards/src/non_fungible_token/utils.ts
function refund_storage_deposit (line 3) | function refund_storage_deposit(
function refund_deposit_to_account (line 15) | function refund_deposit_to_account(
function refund_deposit (line 36) | function refund_deposit(storage_used: bigint): void {
function hash_account_id (line 40) | function hash_account_id(account_id: AccountId): Uint8Array {
function assert_at_least_one_yocto (line 45) | function assert_at_least_one_yocto(): void {
function assert_one_yocto (line 53) | function assert_one_yocto(): void {
type Option (line 60) | type Option<T> = T | null;
FILE: packages/near-contract-standards/src/storage_management/index.ts
class StorageBalance (line 4) | class StorageBalance {
method constructor (line 8) | constructor(total: Balance, available: Balance) {
class StorageBalanceBounds (line 14) | class StorageBalanceBounds {
method constructor (line 15) | constructor(min: Balance, max: Option<Balance>) {
type StorageManagement (line 24) | interface StorageManagement {
FILE: packages/near-sdk-js/builder/builder.c
function JSContext (line 6) | static JSContext *JS_NewCustomContext(JSRuntime *rt)
function JSValue (line 162) | static JSValue near_read_register(JSContext *ctx, JSValueConst this_val,...
function JSValue (line 183) | static JSValue near_register_len(JSContext *ctx, JSValueConst this_val, ...
function JSValue (line 194) | static JSValue near_write_register(JSContext *ctx, JSValueConst this_val...
function JSValue (line 212) | static JSValue near_current_account_id(JSContext *ctx, JSValueConst this...
function JSValue (line 223) | static JSValue near_signer_account_id(JSContext *ctx, JSValueConst this_...
function JSValue (line 233) | static JSValue near_signer_account_pk(JSContext *ctx, JSValueConst this_...
function JSValue (line 243) | static JSValue near_predecessor_account_id(JSContext *ctx, JSValueConst ...
function JSValue (line 253) | static JSValue near_input(JSContext *ctx, JSValueConst this_val, int arg...
function JSValue (line 264) | static JSValue near_block_index(JSContext *ctx, JSValueConst this_val, i...
function JSValue (line 272) | static JSValue near_block_timestamp(JSContext *ctx, JSValueConst this_va...
function JSValue (line 280) | static JSValue near_epoch_height(JSContext *ctx, JSValueConst this_val, ...
function JSValue (line 288) | static JSValue near_storage_usage(JSContext *ctx, JSValueConst this_val,...
function JSValue (line 297) | static JSValue u128_to_quickjs(JSContext *ctx, uint64_t* ptr) {
function quickjs_bigint_to_u128 (line 317) | static int quickjs_bigint_to_u128(JSContext *ctx, JSValueConst val, uint...
function quickjs_int_to_u128 (line 341) | static int quickjs_int_to_u128(JSContext *ctx, JSValueConst val, uint64_...
function quickjs_to_u128 (line 349) | static int quickjs_to_u128(JSContext *ctx, JSValueConst val, uint64_t* p...
function JSValue (line 357) | static JSValue near_account_balance(JSContext *ctx, JSValueConst this_va...
function JSValue (line 365) | static JSValue near_account_locked_balance(JSContext *ctx, JSValueConst ...
function JSValue (line 373) | static JSValue near_attached_deposit(JSContext *ctx, JSValueConst this_v...
function JSValue (line 381) | static JSValue near_prepaid_gas(JSContext *ctx, JSValueConst this_val, i...
function JSValue (line 389) | static JSValue near_used_gas(JSContext *ctx, JSValueConst this_val, int ...
function JSValue (line 397) | static JSValue near_random_seed(JSContext *ctx, JSValueConst this_val, i...
function JSValue (line 408) | static JSValue near_sha256(JSContext *ctx, JSValueConst this_val, int ar...
function JSValue (line 426) | static JSValue near_keccak256(JSContext *ctx, JSValueConst this_val, int...
function JSValue (line 443) | static JSValue near_keccak512(JSContext *ctx, JSValueConst this_val, int...
function JSValue (line 461) | static JSValue near_ripemd160(JSContext *ctx, JSValueConst this_val, int...
function JSValue (line 479) | static JSValue near_ecrecover(JSContext *ctx, JSValueConst this_val, int...
function JSValue (line 507) | static JSValue near_value_return(JSContext *ctx, JSValueConst this_val, ...
function JSValue (line 520) | static JSValue near_panic(JSContext *ctx, JSValueConst this_val, int arg...
function JSValue (line 534) | static JSValue near_panic_utf8(JSContext *ctx, JSValueConst this_val, in...
function JSValue (line 548) | static JSValue near_log(JSContext *ctx, JSValueConst this_val, int argc,...
function JSValue (line 559) | static JSValue near_log_utf8(JSContext *ctx, JSValueConst this_val, int ...
function JSValue (line 573) | static JSValue near_log_utf16(JSContext *ctx, JSValueConst this_val, int...
function JSValue (line 587) | static JSValue near_promise_create(JSContext *ctx, JSValueConst this_val...
function JSValue (line 613) | static JSValue near_promise_then(JSContext *ctx, JSValueConst this_val, ...
function JSValue (line 643) | static JSValue near_promise_and(JSContext *ctx, JSValueConst this_val, i...
function JSValue (line 656) | static JSValue near_promise_batch_create(JSContext *ctx, JSValueConst th...
function JSValue (line 667) | static JSValue near_promise_batch_then(JSContext *ctx, JSValueConst this...
function JSValue (line 682) | static JSValue near_promise_batch_action_create_account(JSContext *ctx, ...
function JSValue (line 693) | static JSValue near_promise_batch_action_deploy_contract(JSContext *ctx,...
function JSValue (line 710) | static JSValue near_promise_batch_action_function_call(JSContext *ctx, J...
function JSValue (line 737) | static JSValue near_promise_batch_action_transfer(JSContext *ctx, JSValu...
function JSValue (line 752) | static JSValue near_promise_batch_action_stake(JSContext *ctx, JSValueCo...
function JSValue (line 774) | static JSValue near_promise_batch_action_add_key_with_full_access(JSCont...
function JSValue (line 795) | static JSValue near_promise_batch_action_add_key_with_function_call(JSCo...
function JSValue (line 823) | static JSValue near_promise_batch_action_delete_key(JSContext *ctx, JSVa...
function JSValue (line 840) | static JSValue near_promise_batch_action_function_call_weight(JSContext ...
function JSValue (line 867) | static JSValue near_promise_batch_action_delete_account(JSContext *ctx, ...
function JSValue (line 881) | static JSValue near_promise_results_count(JSContext *ctx, JSValueConst t...
function JSValue (line 889) | static JSValue near_promise_result(JSContext *ctx, JSValueConst this_val...
function JSValue (line 905) | static JSValue near_promise_return(JSContext *ctx, JSValueConst this_val...
function JSValue (line 916) | static JSValue near_storage_write(JSContext *ctx, JSValueConst this_val,...
function JSValue (line 937) | static JSValue near_storage_read(JSContext *ctx, JSValueConst this_val, ...
function JSValue (line 955) | static JSValue near_storage_remove(JSContext *ctx, JSValueConst this_val...
function JSValue (line 973) | static JSValue near_storage_has_key(JSContext *ctx, JSValueConst this_va...
function JSValue (line 987) | static JSValue near_validator_stake(JSContext *ctx, JSValueConst this_va...
function JSValue (line 999) | static JSValue near_validator_total_stake(JSContext *ctx, JSValueConst t...
function JSValue (line 1007) | static JSValue near_utf8_string_to_uint8array(JSContext *ctx, JSValueCon...
function JSValue (line 1019) | static JSValue near_latin1_string_to_uint8array(JSContext *ctx, JSValueC...
function JSValue (line 1031) | static JSValue near_uint8array_to_latin1_string(JSContext *ctx, JSValueC...
function JSValue (line 1044) | static JSValue near_uint8array_to_utf8_string(JSContext *ctx, JSValueCon...
function JSValue (line 1057) | static JSValue near_alt_bn128_g1_multiexp(JSContext *ctx, JSValueConst t...
function JSValue (line 1075) | static JSValue near_alt_bn128_g1_sum(JSContext *ctx, JSValueConst this_v...
function JSValue (line 1093) | static JSValue near_alt_bn128_pairing_check(JSContext *ctx, JSValueConst...
function js_add_near_host_functions (line 1107) | static void js_add_near_host_functions(JSContext* ctx) {
function _start (line 1181) | void _start() {}
FILE: packages/near-sdk-js/lib/api.js
constant U64_MAX (line 3) | const U64_MAX = 2n ** 64n - 1n;
constant EVICTED_REGISTER (line 4) | const EVICTED_REGISTER = U64_MAX - 1n;
function log (line 10) | function log(...params) {
function signerAccountId (line 26) | function signerAccountId() {
function signerAccountPk (line 34) | function signerAccountPk() {
function predecessorAccountId (line 42) | function predecessorAccountId() {
function currentAccountId (line 49) | function currentAccountId() {
function blockIndex (line 56) | function blockIndex() {
function blockHeight (line 62) | function blockHeight() {
function blockTimestamp (line 68) | function blockTimestamp() {
function epochHeight (line 74) | function epochHeight() {
function attachedDeposit (line 81) | function attachedDeposit() {
function prepaidGas (line 87) | function prepaidGas() {
function usedGas (line 93) | function usedGas() {
function accountBalance (line 99) | function accountBalance() {
function accountLockedBalance (line 105) | function accountLockedBalance() {
function storageReadRaw (line 113) | function storageReadRaw(key) {
function storageRead (line 125) | function storageRead(key) {
function storageHasKeyRaw (line 137) | function storageHasKeyRaw(key) {
function storageHasKey (line 145) | function storageHasKey(key) {
function storageGetEvictedRaw (line 151) | function storageGetEvictedRaw() {
function storageGetEvicted (line 157) | function storageGetEvicted() {
function storageUsage (line 163) | function storageUsage() {
function storageWriteRaw (line 172) | function storageWriteRaw(key, value) {
function storageWrite (line 181) | function storageWrite(key, value) {
function storageRemoveRaw (line 189) | function storageRemoveRaw(key) {
function storageRemove (line 197) | function storageRemove(key) {
function storageByteCost (line 203) | function storageByteCost() {
function inputRaw (line 209) | function inputRaw() {
function input (line 216) | function input() {
function valueReturnRaw (line 224) | function valueReturnRaw(value) {
function valueReturn (line 232) | function valueReturn(value) {
function randomSeed (line 238) | function randomSeed() {
function promiseCreateRaw (line 251) | function promiseCreateRaw(accountId, methodName, args, amount, gas) {
function promiseCreate (line 263) | function promiseCreate(accountId, methodName, args, amount, gas) {
function promiseThenRaw (line 276) | function promiseThenRaw(promiseIndex, accountId, methodName, args, amoun...
function promiseThen (line 289) | function promiseThen(promiseIndex, accountId, methodName, args, amount, ...
function promiseAnd (line 297) | function promiseAnd(...promiseIndexes) {
function promiseBatchCreate (line 305) | function promiseBatchCreate(accountId) {
function promiseBatchThen (line 314) | function promiseBatchThen(promiseIndex, accountId) {
function promiseBatchActionCreateAccount (line 322) | function promiseBatchActionCreateAccount(promiseIndex) {
function promiseBatchActionDeployContract (line 331) | function promiseBatchActionDeployContract(promiseIndex, code) {
function promiseBatchActionFunctionCallRaw (line 343) | function promiseBatchActionFunctionCallRaw(promiseIndex, methodName, arg...
function promiseBatchActionFunctionCall (line 355) | function promiseBatchActionFunctionCall(promiseIndex, methodName, args, ...
function promiseBatchActionTransfer (line 364) | function promiseBatchActionTransfer(promiseIndex, amount) {
function promiseBatchActionStake (line 374) | function promiseBatchActionStake(promiseIndex, amount, publicKey) {
function promiseBatchActionAddKeyWithFullAccess (line 384) | function promiseBatchActionAddKeyWithFullAccess(promiseIndex, publicKey,...
function promiseBatchActionAddKeyWithFunctionCall (line 397) | function promiseBatchActionAddKeyWithFunctionCall(promiseIndex, publicKe...
function promiseBatchActionDeleteKey (line 406) | function promiseBatchActionDeleteKey(promiseIndex, publicKey) {
function promiseBatchActionDeleteAccount (line 415) | function promiseBatchActionDeleteAccount(promiseIndex, beneficiaryId) {
function promiseBatchActionFunctionCallWeightRaw (line 428) | function promiseBatchActionFunctionCallWeightRaw(promiseIndex, methodNam...
function promiseBatchActionFunctionCallWeight (line 441) | function promiseBatchActionFunctionCallWeight(promiseIndex, methodName, ...
function promiseResultsCount (line 447) | function promiseResultsCount() {
function promiseResultRaw (line 455) | function promiseResultRaw(promiseIndex) {
function promiseResult (line 469) | function promiseResult(promiseIndex) {
function promiseReturn (line 477) | function promiseReturn(promiseIndex) {
function sha256 (line 485) | function sha256(value) {
function keccak256 (line 494) | function keccak256(value) {
function keccak512 (line 503) | function keccak512(value) {
function ripemd160 (line 512) | function ripemd160(value) {
function ecrecover (line 527) | function ecrecover(hash, sig, v, malleabilityFlag) {
function panicUtf8 (line 539) | function panicUtf8(msg) {
function logUtf8 (line 546) | function logUtf8(msg) {
function logUtf16 (line 553) | function logUtf16(msg) {
function validatorStake (line 561) | function validatorStake(accountId) {
function validatorTotalStake (line 568) | function validatorTotalStake() {
function altBn128G1Multiexp (line 583) | function altBn128G1Multiexp(value) {
function altBn128G1Sum (line 599) | function altBn128G1Sum(value) {
function altBn128PairingCheck (line 618) | function altBn128PairingCheck(value) {
FILE: packages/near-sdk-js/lib/cli/abi.js
function parseMetadata (line 7) | function parseMetadata(packageJsonPath) {
function getProgramFromFiles (line 23) | function getProgramFromFiles(files, jsonCompilerOptions, basePath = "./") {
function validateNearClass (line 33) | function validateNearClass(node) {
function runAbiCompilerPlugin (line 53) | function runAbiCompilerPlugin(tsFile, packageJsonPath, tsConfigJsonPath) {
FILE: packages/near-sdk-js/lib/cli/build-tools/include-bytes.js
method CallExpression (line 8) | CallExpression(path, { opts, file }) {
FILE: packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js
function throwError (line 14) | function throwError(message) {
function readState (line 29) | function readState(classId, methodType) {
function preventDoubleInit (line 50) | function preventDoubleInit(methodType) {
function ensureInitBeforeCall (line 70) | function ensureInitBeforeCall(classId, methodType) {
function initializeContractClass (line 87) | function initializeContractClass(classId) {
function reconstructState (line 104) | function reconstructState(classId, methodType) {
function collectArguments (line 121) | function collectArguments(classId) {
function callContractMethod (line 136) | function callContractMethod(methodName) {
function saveToStorage (line 152) | function saveToStorage(classId, methodType) {
function executePromise (line 175) | function executePromise(classId) {
function createDeclaration (line 187) | function createDeclaration(classId, methodName, methodType) {
method ClassDeclaration (line 225) | ClassDeclaration(path, { opts: { verbose } }) {
FILE: packages/near-sdk-js/lib/cli/cli.js
constant PROJECT_DIR (line 13) | const PROJECT_DIR = process.cwd();
constant NEAR_SDK_JS (line 14) | const NEAR_SDK_JS = "node_modules/near-sdk-js";
constant TSC (line 15) | const TSC = "node_modules/.bin/tsc";
constant QJSC_DIR (line 16) | const QJSC_DIR = `${NEAR_SDK_JS}/lib/cli/deps/quickjs`;
constant QJSC (line 17) | const QJSC = `${NEAR_SDK_JS}/lib/cli/deps/qjsc`;
function getTargetDir (line 57) | function getTargetDir(target) {
function getTargetExt (line 60) | function getTargetExt(target) {
function getTargetFileName (line 63) | function getTargetFileName(target) {
function getRollupTarget (line 66) | function getRollupTarget(target) {
function getQjscTarget (line 69) | function getQjscTarget(target) {
function getContractTarget (line 72) | function getContractTarget(target) {
function getContractAbi (line 75) | function getContractAbi(target) {
function requireTargetExt (line 78) | function requireTargetExt(target) {
function ensureTargetDirExists (line 85) | function ensureTargetDirExists(target) {
function validateCom (line 93) | async function validateCom(source, { verbose = false }) {
function checkTypescriptCom (line 100) | async function checkTypescriptCom(source, { verbose = false }) {
function generateAbi (line 113) | async function generateAbi(source, target, packageJson, tsConfig, { verb...
function createJsFileWithRollupCom (line 125) | async function createJsFileWithRollupCom(source, target, { verbose = fal...
function transpileJsAndBuildWasmCom (line 135) | async function transpileJsAndBuildWasmCom(target, { verbose = false }) {
function buildCom (line 152) | async function buildCom(source, target, packageJson, tsConfig, { verbose...
function checkTsBuildWithTsc (line 165) | async function checkTsBuildWithTsc(sourceFileWithPath, verbose = false) {
function createJsFileWithRullup (line 169) | async function createJsFileWithRullup(sourceFileWithPath, rollupTarget, ...
function createHeaderFileWithQjsc (line 199) | async function createHeaderFileWithQjsc(rollupTarget, qjscTarget, verbos...
function createMethodsHeaderFile (line 202) | async function createMethodsHeaderFile(rollupTarget, verbose = false) {
function createWasmContract (line 216) | async function createWasmContract(qjscTarget, contractTarget, verbose = ...
function wasiStubContract (line 230) | async function wasiStubContract(contractTarget, verbose = false) {
FILE: packages/near-sdk-js/lib/cli/post-install.js
constant DEPS (line 9) | const DEPS = "deps";
constant PLATFORM (line 13) | const PLATFORM = os.platform();
constant ARCH (line 14) | const ARCH = os.arch();
constant SUPPORTED_PLATFORMS (line 16) | const SUPPORTED_PLATFORMS = ["linux", "darwin"];
constant SUPPORTED_ARCH (line 17) | const SUPPORTED_ARCH = ["x64", "arm64"];
constant BINARYEN_VERSION (line 27) | const BINARYEN_VERSION = `0.1.16`;
constant BINARYEN_VERSION_TAG (line 28) | const BINARYEN_VERSION_TAG = `v${BINARYEN_VERSION}`;
constant BINARYEN_SYSTEM_NAME (line 29) | const BINARYEN_SYSTEM_NAME = PLATFORM === "linux"
constant BINARYEN_ARCH_NAME (line 36) | const BINARYEN_ARCH_NAME = (ARCH == 'aarch64') ? 'ARM64' : ARCH.toUpperC...
constant BINARYEN_TAR_NAME (line 37) | const BINARYEN_TAR_NAME = `binaryen-${BINARYEN_SYSTEM_NAME}-${BINARYEN_A...
constant QUICK_JS_VERSION (line 43) | const QUICK_JS_VERSION = `0.1.3`;
constant QUICK_JS_VERSION_TAG (line 44) | const QUICK_JS_VERSION_TAG = `v${QUICK_JS_VERSION}`;
constant QUICK_JS_SYSTEM_NAME (line 45) | const QUICK_JS_SYSTEM_NAME = PLATFORM === "linux"
constant QUICK_JS_ARCH_NAME (line 52) | const QUICK_JS_ARCH_NAME = ARCH === "x64" ? "X64" : ARCH === "arm64" ? "...
constant QUICK_JS_TAR_NAME (line 53) | const QUICK_JS_TAR_NAME = `${QUICK_JS_VERSION_TAG}.tar.gz`;
constant QUICK_JS_DOWNLOADED_FOLDER_NAME (line 54) | const QUICK_JS_DOWNLOADED_FOLDER_NAME = `quickjs-${QUICK_JS_VERSION}`;
constant QUICK_JS_TARGET_FOLDER_NAME (line 55) | const QUICK_JS_TARGET_FOLDER_NAME = "quickjs";
constant QUICK_JS_DOWNLOADED_NAME (line 56) | const QUICK_JS_DOWNLOADED_NAME = `qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_J...
constant QUICK_JS_TARGET_NAME (line 57) | const QUICK_JS_TARGET_NAME = "qjsc";
constant WASI_SDK_MAJOR_VER (line 72) | const WASI_SDK_MAJOR_VER = 11;
constant WASI_SDK_MINOR_VER (line 73) | const WASI_SDK_MINOR_VER = 0;
constant WASI_SDK_DOWNLOADED_FOLDER_NAME (line 74) | const WASI_SDK_DOWNLOADED_FOLDER_NAME = `wasi-sdk-${WASI_SDK_MAJOR_VER}....
constant WASI_SDK_SYSTEM_NAME (line 75) | const WASI_SDK_SYSTEM_NAME = PLATFORM === "linux"
constant WASI_SDK_TAR_NAME (line 82) | const WASI_SDK_TAR_NAME = `${WASI_SDK_DOWNLOADED_FOLDER_NAME}-${WASI_SDK...
FILE: packages/near-sdk-js/lib/cli/utils.js
function executeCommand (line 8) | async function executeCommand(command, verbose = false) {
function download (line 38) | async function download(url, verbose = false) {
constant UNINITIALIZED_PARAMETERS_ERROR (line 41) | const UNINITIALIZED_PARAMETERS_ERROR = "All parameters must be initializ...
function validateContract (line 48) | async function validateContract(contractPath, verbose = false) {
FILE: packages/near-sdk-js/lib/collections/lookup-map.d.ts
class LookupMap (line 6) | class LookupMap<DataType> extends SubType<DataType> {
FILE: packages/near-sdk-js/lib/collections/lookup-map.js
class LookupMap (line 7) | class LookupMap extends SubType {
method constructor (line 11) | constructor(keyPrefix) {
method containsKey (line 20) | containsKey(key) {
method get (line 30) | get(key, options) {
method remove (line 45) | remove(key, options) {
method set (line 60) | set(key, newValue, options) {
method extend (line 75) | extend(keyValuePairs, options) {
method serialize (line 85) | serialize(options) {
method reconstruct (line 93) | static reconstruct(data) {
FILE: packages/near-sdk-js/lib/collections/lookup-set.d.ts
class LookupSet (line 5) | class LookupSet<DataType> {
FILE: packages/near-sdk-js/lib/collections/lookup-set.js
class LookupSet (line 6) | class LookupSet {
method constructor (line 10) | constructor(keyPrefix) {
method contains (line 19) | contains(key, options) {
method remove (line 29) | remove(key, options) {
method set (line 40) | set(key, options) {
method extend (line 50) | extend(keys, options) {
method serialize (line 58) | serialize(options) {
method reconstruct (line 66) | static reconstruct(data) {
FILE: packages/near-sdk-js/lib/collections/subtype.js
class SubType (line 1) | class SubType {
method subtype (line 4) | subtype() { }
method set_reconstructor (line 5) | set_reconstructor(options) {
FILE: packages/near-sdk-js/lib/collections/unordered-map.d.ts
type ValueAndIndex (line 5) | type ValueAndIndex = [value: string, index: number];
class UnorderedMap (line 9) | class UnorderedMap<DataType> extends SubType<DataType> {
class UnorderedMapIterator (line 90) | class UnorderedMapIterator<DataType> {
FILE: packages/near-sdk-js/lib/collections/unordered-map.js
class UnorderedMap (line 8) | class UnorderedMap extends SubType {
method constructor (line 12) | constructor(prefix) {
method length (line 21) | get length() {
method isEmpty (line 27) | isEmpty() {
method get (line 36) | get(key, options) {
method set (line 52) | set(key, value, options) {
method remove (line 71) | remove(key, options) {
method clear (line 91) | clear() {
method createIteratorWithOptions (line 106) | createIteratorWithOptions(options) {
method toArray (line 116) | toArray(options) {
method extend (line 129) | extend(keyValuePairs) {
method serialize (line 139) | serialize(options) {
method reconstruct (line 147) | static reconstruct(data) {
method keys (line 156) | keys({ start, limit }) {
method [Symbol.iterator] (line 98) | [Symbol.iterator]() {
class UnorderedMapIterator (line 173) | class UnorderedMapIterator {
method constructor (line 178) | constructor(unorderedMap, options) {
method subtype (line 186) | subtype() { }
method next (line 187) | next() {
FILE: packages/near-sdk-js/lib/collections/unordered-set.d.ts
class UnorderedSet (line 6) | class UnorderedSet<DataType> {
FILE: packages/near-sdk-js/lib/collections/unordered-set.js
function serializeIndex (line 4) | function serializeIndex(index) {
function deserializeIndex (line 9) | function deserializeIndex(rawIndex) {
class UnorderedSet (line 16) | class UnorderedSet {
method constructor (line 20) | constructor(prefix) {
method length (line 28) | get length() {
method isEmpty (line 34) | isEmpty() {
method contains (line 43) | contains(element, options) {
method set (line 54) | set(element, options) {
method remove (line 71) | remove(element, options) {
method clear (line 104) | clear(options) {
method createIteratorWithOptions (line 119) | createIteratorWithOptions(options) {
method toArray (line 129) | toArray(options) {
method extend (line 142) | extend(elements) {
method serialize (line 152) | serialize(options) {
method reconstruct (line 160) | static reconstruct(data) {
method elements (line 168) | elements({ options, start, limit, }) {
method [Symbol.iterator] (line 111) | [Symbol.iterator]() {
FILE: packages/near-sdk-js/lib/collections/vector.d.ts
class Vector (line 7) | class Vector<DataType> extends SubType<DataType> {
class VectorIterator (line 95) | class VectorIterator<DataType> {
FILE: packages/near-sdk-js/lib/collections/vector.js
function indexToKey (line 4) | function indexToKey(prefix, index) {
class Vector (line 14) | class Vector extends SubType {
method constructor (line 19) | constructor(prefix, length = 0) {
method isEmpty (line 27) | isEmpty() {
method get (line 36) | get(index, options) {
method swapRemove (line 53) | swapRemove(index, options) {
method push (line 71) | push(element, options) {
method pop (line 81) | pop(options) {
method replace (line 99) | replace(index, element, options) {
method extend (line 112) | extend(elements) {
method createIteratorWithOptions (line 125) | createIteratorWithOptions(options) {
method toArray (line 135) | toArray(options) {
method clear (line 146) | clear() {
method serialize (line 158) | serialize(options) {
method reconstruct (line 166) | static reconstruct(data) {
method [Symbol.iterator] (line 117) | [Symbol.iterator]() {
class VectorIterator (line 174) | class VectorIterator {
method constructor (line 179) | constructor(vector, options) {
method next (line 184) | next() {
FILE: packages/near-sdk-js/lib/near-bindgen.d.ts
type EmptyParameterObject (line 1) | type EmptyParameterObject = Record<never, never>;
type DecoratorFunction (line 2) | type DecoratorFunction = <AnyFunction extends (...args: any) => any>(tar...
type Middleware (line 37) | interface Middleware<Arguments extends Array<any>> {
FILE: packages/near-sdk-js/lib/near-bindgen.js
function migrate (line 8) | function migrate(_empty) {
function initialize (line 19) | function initialize(_empty) {
function view (line 30) | function view(_empty) {
function call (line 36) | function call({ privateFunction = false, payableFunction = false, }) {
function middleware (line 60) | function middleware(...middlewares) {
function NearBindgen (line 77) | function NearBindgen({ requireInit = false, serializer = serialize, dese...
FILE: packages/near-sdk-js/lib/promise.d.ts
class CreateAccount (line 20) | class CreateAccount extends PromiseAction {
class DeployContract (line 28) | class DeployContract extends PromiseAction {
class FunctionCall (line 41) | class FunctionCall extends PromiseAction {
class FunctionCallRaw (line 60) | class FunctionCallRaw extends PromiseAction {
class FunctionCallWeight (line 79) | class FunctionCallWeight extends PromiseAction {
class FunctionCallWeightRaw (line 100) | class FunctionCallWeightRaw extends PromiseAction {
class Transfer (line 121) | class Transfer extends PromiseAction {
class Stake (line 134) | class Stake extends PromiseAction {
class AddFullAccessKey (line 149) | class AddFullAccessKey extends PromiseAction {
class AddAccessKey (line 164) | class AddAccessKey extends PromiseAction {
class DeleteKey (line 185) | class DeleteKey extends PromiseAction {
class DeleteAccount (line 198) | class DeleteAccount extends PromiseAction {
class PromiseSingle (line 206) | class PromiseSingle {
class PromiseJoint (line 214) | class PromiseJoint {
type PromiseSubtype (line 221) | type PromiseSubtype = PromiseSingle | PromiseJoint;
class NearPromise (line 225) | class NearPromise {
type PromiseOrValue (line 380) | type PromiseOrValue<T> = NearPromise | T;
FILE: packages/near-sdk-js/lib/promise.js
class PromiseAction (line 6) | class PromiseAction {
class CreateAccount (line 13) | class CreateAccount extends PromiseAction {
method add (line 14) | add(promiseIndex) {
class DeployContract (line 23) | class DeployContract extends PromiseAction {
method constructor (line 27) | constructor(code) {
method add (line 31) | add(promiseIndex) {
class FunctionCall (line 40) | class FunctionCall extends PromiseAction {
method constructor (line 47) | constructor(functionName, args, amount, gas) {
method add (line 54) | add(promiseIndex) {
class FunctionCallRaw (line 63) | class FunctionCallRaw extends PromiseAction {
method constructor (line 70) | constructor(functionName, args, amount, gas) {
method add (line 77) | add(promiseIndex) {
class FunctionCallWeight (line 86) | class FunctionCallWeight extends PromiseAction {
method constructor (line 94) | constructor(functionName, args, amount, gas, weight) {
method add (line 102) | add(promiseIndex) {
class FunctionCallWeightRaw (line 111) | class FunctionCallWeightRaw extends PromiseAction {
method constructor (line 119) | constructor(functionName, args, amount, gas, weight) {
method add (line 127) | add(promiseIndex) {
class Transfer (line 136) | class Transfer extends PromiseAction {
method constructor (line 140) | constructor(amount) {
method add (line 144) | add(promiseIndex) {
class Stake (line 153) | class Stake extends PromiseAction {
method constructor (line 158) | constructor(amount, publicKey) {
method add (line 163) | add(promiseIndex) {
class AddFullAccessKey (line 172) | class AddFullAccessKey extends PromiseAction {
method constructor (line 177) | constructor(publicKey, nonce) {
method add (line 182) | add(promiseIndex) {
class AddAccessKey (line 191) | class AddAccessKey extends PromiseAction {
method constructor (line 199) | constructor(publicKey, allowance, receiverId, functionNames, nonce) {
method add (line 207) | add(promiseIndex) {
class DeleteKey (line 216) | class DeleteKey extends PromiseAction {
method constructor (line 220) | constructor(publicKey) {
method add (line 224) | add(promiseIndex) {
class DeleteAccount (line 233) | class DeleteAccount extends PromiseAction {
method constructor (line 237) | constructor(beneficiaryId) {
method add (line 241) | add(promiseIndex) {
class PromiseSingle (line 245) | class PromiseSingle {
method constructor (line 246) | constructor(accountId, actions, after, promiseIndex) {
method constructRecursively (line 252) | constructRecursively() {
class PromiseJoint (line 264) | class PromiseJoint {
method constructor (line 265) | constructor(promiseA, promiseB, promiseIndex) {
method constructRecursively (line 270) | constructRecursively() {
class NearPromise (line 282) | class NearPromise {
method constructor (line 287) | constructor(subtype, shouldReturn) {
method new (line 296) | static new(accountId) {
method addAction (line 300) | addAction(action) {
method createAccount (line 310) | createAccount() {
method deployContract (line 318) | deployContract(code) {
method functionCall (line 329) | functionCall(functionName, args, amount, gas) {
method functionCallRaw (line 340) | functionCallRaw(functionName, args, amount, gas) {
method functionCallWeight (line 352) | functionCallWeight(functionName, args, amount, gas, weight) {
method functionCallWeightRaw (line 364) | functionCallWeightRaw(functionName, args, amount, gas, weight) {
method transfer (line 372) | transfer(amount) {
method stake (line 381) | stake(amount, publicKey) {
method addFullAccessKey (line 390) | addFullAccessKey(publicKey) {
method addFullAccessKeyWithNonce (line 400) | addFullAccessKeyWithNonce(publicKey, nonce) {
method addAccessKey (line 412) | addAccessKey(publicKey, allowance, receiverId, functionNames) {
method addAccessKeyWithNonce (line 425) | addAccessKeyWithNonce(publicKey, allowance, receiverId, functionNames,...
method deleteKey (line 433) | deleteKey(publicKey) {
method deleteAccount (line 441) | deleteAccount(beneficiaryId) {
method and (line 449) | and(other) {
method then (line 458) | then(other) {
method asReturn (line 467) | asReturn() {
method constructRecursively (line 474) | constructRecursively() {
method onReturn (line 484) | onReturn() {
method build (line 492) | build() {
FILE: packages/near-sdk-js/lib/types/account_id.d.ts
type AccountId (line 4) | type AccountId = string;
FILE: packages/near-sdk-js/lib/types/collections.d.ts
type GetOptions (line 4) | interface GetOptions<DataType> {
FILE: packages/near-sdk-js/lib/types/gas.d.ts
type Gas (line 4) | type Gas = bigint;
FILE: packages/near-sdk-js/lib/types/gas.js
constant ONE_TERA_GAS (line 4) | const ONE_TERA_GAS = 1000000000000n;
FILE: packages/near-sdk-js/lib/types/primitives.d.ts
type StorageUsage (line 4) | type StorageUsage = bigint;
type BlockHeight (line 8) | type BlockHeight = bigint;
type EpochHeight (line 12) | type EpochHeight = bigint;
type Balance (line 16) | type Balance = bigint;
type Nonce (line 20) | type Nonce = bigint;
type GasWeight (line 24) | type GasWeight = bigint;
FILE: packages/near-sdk-js/lib/types/primitives.js
constant ONE_YOCTO (line 4) | const ONE_YOCTO = 1n;
constant ONE_NEAR (line 8) | const ONE_NEAR = 1000000000000000000000000n;
FILE: packages/near-sdk-js/lib/types/public_key.d.ts
type CurveType (line 1) | enum CurveType {
class ParsePublicKeyError (line 6) | class ParsePublicKeyError extends Error {
class InvalidLengthError (line 8) | class InvalidLengthError extends ParsePublicKeyError {
class Base58Error (line 13) | class Base58Error extends ParsePublicKeyError {
class UnknownCurve (line 17) | class UnknownCurve extends ParsePublicKeyError {
class PublicKey (line 25) | class PublicKey {
FILE: packages/near-sdk-js/lib/types/public_key.js
function getCurveType (line 13) | function getCurveType(curveType) {
function dataLength (line 22) | function dataLength(curveType) {
function splitKeyTypeData (line 34) | function splitKeyTypeData(value) {
function curveTypeFromStr (line 46) | function curveTypeFromStr(value) {
class ParsePublicKeyError (line 56) | class ParsePublicKeyError extends Error {
class InvalidLengthError (line 58) | class InvalidLengthError extends ParsePublicKeyError {
method constructor (line 59) | constructor(length, expectedLength) {
class Base58Error (line 65) | class Base58Error extends ParsePublicKeyError {
method constructor (line 66) | constructor(error) {
class UnknownCurve (line 71) | class UnknownCurve extends ParsePublicKeyError {
method constructor (line 72) | constructor() {
class PublicKey (line 81) | class PublicKey {
method constructor (line 85) | constructor(data) {
method curveType (line 96) | curveType() {
method fromString (line 104) | static fromString(publicKeyString) {
FILE: packages/near-sdk-js/lib/types/vm_types.d.ts
type ReceiptIndex (line 4) | type ReceiptIndex = bigint;
type IteratorIndex (line 8) | type IteratorIndex = bigint;
type PromiseResult (line 15) | enum PromiseResult {
type PromiseError (line 23) | enum PromiseError {
FILE: packages/near-sdk-js/lib/utils.d.ts
type Env (line 2) | interface Env {
type PromiseIndex (line 11) | type PromiseIndex = number | bigint;
type NearAmount (line 15) | type NearAmount = number | bigint;
type Register (line 19) | type Register = number | bigint;
type Mutable (line 36) | type Mutable<T> = {
class TextEncoder (line 54) | class TextEncoder {
class TextDecoder (line 60) | class TextDecoder {
type IntoStorageKey (line 92) | interface IntoStorageKey {
FILE: packages/near-sdk-js/lib/utils.js
constant TYPE_KEY (line 2) | const TYPE_KEY = "typeInfo";
constant ERR_INCONSISTENT_STATE (line 8) | const ERR_INCONSISTENT_STATE = "The collection is an inconsistent state....
constant ERR_INDEX_OUT_OF_BOUNDS (line 9) | const ERR_INDEX_OUT_OF_BOUNDS = "Index out of bounds";
constant ACCOUNT_ID_REGEX (line 10) | const ACCOUNT_ID_REGEX = /^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a...
function concat (line 17) | function concat(array1, array2) {
function assert (line 29) | function assert(expression, message) {
function getValueWithOptions (line 34) | function getValueWithOptions(subDatatype, value, options = {}) {
function serializeValueWithOptions (line 99) | function serializeValueWithOptions(value, { serializer } = {
function serialize (line 104) | function serialize(valueToSerialize) {
function deserialize (line 123) | function deserialize(valueToDeserialize) {
function decodeObj2class (line 139) | function decodeObj2class(class_instance, obj) {
function validateAccountId (line 218) | function validateAccountId(accountId) {
class TextEncoder (line 226) | class TextEncoder {
method encode (line 227) | encode(s) {
class TextDecoder (line 234) | class TextDecoder {
method constructor (line 235) | constructor(encoding = "utf-8") {
method decode (line 238) | decode(a) {
function bytes (line 255) | function bytes(s) {
function str (line 263) | function str(a) {
function encode (line 271) | function encode(s) {
function decode (line 279) | function decode(a) {
FILE: packages/near-sdk-js/lib/version.js
constant PACKAGE_JSON (line 3) | const PACKAGE_JSON = JSON.parse(fs.readFileSync(fileURLToPath(new URL("....
constant LIB_VERSION (line 4) | const LIB_VERSION = PACKAGE_JSON["version"];
FILE: packages/near-sdk-js/src/api.ts
constant U64_MAX (line 12) | const U64_MAX = 2n ** 64n - 1n;
constant EVICTED_REGISTER (line 13) | const EVICTED_REGISTER = U64_MAX - 1n;
type Env (line 16) | interface Env {
function log (line 160) | function log(...params: unknown[]): void {
function signerAccountId (line 182) | function signerAccountId(): string {
function signerAccountPk (line 191) | function signerAccountPk(): Uint8Array {
function predecessorAccountId (line 200) | function predecessorAccountId(): string {
function currentAccountId (line 208) | function currentAccountId(): string {
function blockIndex (line 216) | function blockIndex(): bigint {
function blockHeight (line 223) | function blockHeight(): bigint {
function blockTimestamp (line 230) | function blockTimestamp(): bigint {
function epochHeight (line 237) | function epochHeight(): bigint {
function attachedDeposit (line 245) | function attachedDeposit(): bigint {
function prepaidGas (line 252) | function prepaidGas(): bigint {
function usedGas (line 259) | function usedGas(): bigint {
function accountBalance (line 266) | function accountBalance(): bigint {
function accountLockedBalance (line 273) | function accountLockedBalance(): bigint {
function storageReadRaw (line 282) | function storageReadRaw(key: Uint8Array): Uint8Array | null {
function storageRead (line 297) | function storageRead(key: string): string | null {
function storageHasKeyRaw (line 310) | function storageHasKeyRaw(key: Uint8Array): boolean {
function storageHasKey (line 319) | function storageHasKey(key: string): boolean {
function storageGetEvictedRaw (line 326) | function storageGetEvictedRaw(): Uint8Array {
function storageGetEvicted (line 333) | function storageGetEvicted(): string {
function storageUsage (line 340) | function storageUsage(): bigint {
function storageWriteRaw (line 350) | function storageWriteRaw(key: Uint8Array, value: Uint8Array): boolean {
function storageWrite (line 360) | function storageWrite(key: string, value: string): boolean {
function storageRemoveRaw (line 369) | function storageRemoveRaw(key: Uint8Array): boolean {
function storageRemove (line 378) | function storageRemove(key: string): boolean {
function storageByteCost (line 385) | function storageByteCost(): bigint {
function inputRaw (line 392) | function inputRaw(): Uint8Array {
function input (line 400) | function input(): string {
function valueReturnRaw (line 409) | function valueReturnRaw(value: Uint8Array): void {
function valueReturn (line 418) | function valueReturn(value: string): void {
function randomSeed (line 425) | function randomSeed(): Uint8Array {
function promiseCreateRaw (line 439) | function promiseCreateRaw(
function promiseCreate (line 464) | function promiseCreate(
function promiseThenRaw (line 484) | function promiseThenRaw(
function promiseThen (line 512) | function promiseThen(
function promiseAnd (line 535) | function promiseAnd(...promiseIndexes: PromiseIndex[]): PromiseIndex {
function promiseBatchCreate (line 546) | function promiseBatchCreate(accountId: string): PromiseIndex {
function promiseBatchThen (line 556) | function promiseBatchThen(
function promiseBatchActionCreateAccount (line 571) | function promiseBatchActionCreateAccount(
function promiseBatchActionDeployContract (line 583) | function promiseBatchActionDeployContract(
function promiseBatchActionFunctionCallRaw (line 602) | function promiseBatchActionFunctionCallRaw(
function promiseBatchActionFunctionCall (line 627) | function promiseBatchActionFunctionCall(
function promiseBatchActionTransfer (line 649) | function promiseBatchActionTransfer(
function promiseBatchActionStake (line 663) | function promiseBatchActionStake(
function promiseBatchActionAddKeyWithFullAccess (line 682) | function promiseBatchActionAddKeyWithFullAccess(
function promiseBatchActionAddKeyWithFunctionCall (line 704) | function promiseBatchActionAddKeyWithFunctionCall(
function promiseBatchActionDeleteKey (line 728) | function promiseBatchActionDeleteKey(
function promiseBatchActionDeleteAccount (line 744) | function promiseBatchActionDeleteAccount(
function promiseBatchActionFunctionCallWeightRaw (line 764) | function promiseBatchActionFunctionCallWeightRaw(
function promiseBatchActionFunctionCallWeight (line 792) | function promiseBatchActionFunctionCallWeight(
function promiseResultsCount (line 813) | function promiseResultsCount(): bigint {
function promiseResultRaw (line 822) | function promiseResultRaw(promiseIndex: PromiseIndex): Uint8Array {
function promiseResult (line 844) | function promiseResult(promiseIndex: PromiseIndex): string {
function promiseReturn (line 853) | function promiseReturn(promiseIndex: PromiseIndex): void {
function sha256 (line 862) | function sha256(value: Uint8Array): Uint8Array {
function keccak256 (line 872) | function keccak256(value: Uint8Array): Uint8Array {
function keccak512 (line 882) | function keccak512(value: Uint8Array): Uint8Array {
function ripemd160 (line 892) | function ripemd160(value: Uint8Array): Uint8Array {
function ecrecover (line 908) | function ecrecover(
function panicUtf8 (line 929) | function panicUtf8(msg: Uint8Array): never {
function logUtf8 (line 937) | function logUtf8(msg: Uint8Array) {
function logUtf16 (line 945) | function logUtf16(msg: Uint8Array) {
function validatorStake (line 954) | function validatorStake(accountId: string): bigint {
function validatorTotalStake (line 962) | function validatorTotalStake(): bigint {
function altBn128G1Multiexp (line 978) | function altBn128G1Multiexp(value: Uint8Array): Uint8Array {
function altBn128G1Sum (line 995) | function altBn128G1Sum(value: Uint8Array): Uint8Array {
function altBn128PairingCheck (line 1015) | function altBn128PairingCheck(value: Uint8Array): boolean {
FILE: packages/near-sdk-js/src/cli/abi.ts
function parseMetadata (line 9) | function parseMetadata(packageJsonPath: string): abi.AbiMetadata {
function getProgramFromFiles (line 27) | function getProgramFromFiles(
function validateNearClass (line 45) | function validateNearClass(node: ts.Node) {
function runAbiCompilerPlugin (line 70) | function runAbiCompilerPlugin(
FILE: packages/near-sdk-js/src/cli/build-tools/include-bytes.ts
method CallExpression (line 13) | CallExpression(
FILE: packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts
function throwError (line 19) | function throwError(message: string): t.BlockStatement {
function readState (line 37) | function readState(classId: t.Identifier, methodType: string): t.Variabl...
function preventDoubleInit (line 69) | function preventDoubleInit(
function ensureInitBeforeCall (line 96) | function ensureInitBeforeCall(
function initializeContractClass (line 128) | function initializeContractClass(classId: t.Identifier): t.VariableDecla...
function reconstructState (line 149) | function reconstructState(
function collectArguments (line 179) | function collectArguments(classId: t.Identifier): t.VariableDeclaration {
function callContractMethod (line 201) | function callContractMethod(methodName: string): t.VariableDeclaration {
function saveToStorage (line 224) | function saveToStorage(
function executePromise (line 257) | function executePromise(classId: t.Identifier): t.IfStatement {
function createDeclaration (line 315) | function createDeclaration(
method ClassDeclaration (line 364) | ClassDeclaration(
FILE: packages/near-sdk-js/src/cli/cli.ts
constant PROJECT_DIR (line 17) | const PROJECT_DIR = process.cwd();
constant NEAR_SDK_JS (line 18) | const NEAR_SDK_JS = "node_modules/near-sdk-js";
constant TSC (line 19) | const TSC = "node_modules/.bin/tsc";
constant QJSC_DIR (line 20) | const QJSC_DIR = `${NEAR_SDK_JS}/lib/cli/deps/quickjs`;
constant QJSC (line 21) | const QJSC = `${NEAR_SDK_JS}/lib/cli/deps/qjsc`;
function getTargetDir (line 90) | function getTargetDir(target: string): string {
function getTargetExt (line 94) | function getTargetExt(target: string): string {
function getTargetFileName (line 98) | function getTargetFileName(target: string): string {
function getRollupTarget (line 102) | function getRollupTarget(target: string): string {
function getQjscTarget (line 106) | function getQjscTarget(target: string): string {
function getContractTarget (line 110) | function getContractTarget(target: string): string {
function getContractAbi (line 114) | function getContractAbi(target: string): string {
function requireTargetExt (line 118) | function requireTargetExt(target: string): void {
function ensureTargetDirExists (line 131) | function ensureTargetDirExists(target: string): void {
function validateCom (line 141) | async function validateCom(
function checkTypescriptCom (line 154) | async function checkTypescriptCom(
function generateAbi (line 173) | async function generateAbi(
function createJsFileWithRollupCom (line 196) | async function createJsFileWithRollupCom(
function transpileJsAndBuildWasmCom (line 213) | async function transpileJsAndBuildWasmCom(
function buildCom (line 250) | async function buildCom(
function checkTsBuildWithTsc (line 278) | async function checkTsBuildWithTsc(
function createJsFileWithRullup (line 289) | async function createJsFileWithRullup(
function createHeaderFileWithQjsc (line 325) | async function createHeaderFileWithQjsc(
function createMethodsHeaderFile (line 336) | async function createMethodsHeaderFile(rollupTarget: string, verbose = f...
function createWasmContract (line 359) | async function createWasmContract(
function wasiStubContract (line 388) | async function wasiStubContract(contractTarget: string, verbose = false) {
FILE: packages/near-sdk-js/src/cli/post-install.ts
constant DEPS (line 12) | const DEPS = "deps";
constant PLATFORM (line 17) | const PLATFORM = os.platform();
constant ARCH (line 18) | const ARCH = os.arch();
constant SUPPORTED_PLATFORMS (line 21) | const SUPPORTED_PLATFORMS = ["linux", "darwin"];
constant SUPPORTED_ARCH (line 22) | const SUPPORTED_ARCH = ["x64", "arm64"];
constant BINARYEN_VERSION (line 36) | const BINARYEN_VERSION = `0.1.16`;
constant BINARYEN_VERSION_TAG (line 37) | const BINARYEN_VERSION_TAG = `v${BINARYEN_VERSION}`;
constant BINARYEN_SYSTEM_NAME (line 39) | const BINARYEN_SYSTEM_NAME =
constant BINARYEN_ARCH_NAME (line 48) | const BINARYEN_ARCH_NAME = (ARCH == 'aarch64') ? 'ARM64' : ARCH.toUpperC...
constant BINARYEN_TAR_NAME (line 50) | const BINARYEN_TAR_NAME = `binaryen-${BINARYEN_SYSTEM_NAME}-${BINARYEN_A...
constant QUICK_JS_VERSION (line 63) | const QUICK_JS_VERSION = `0.1.3`;
constant QUICK_JS_VERSION_TAG (line 64) | const QUICK_JS_VERSION_TAG = `v${QUICK_JS_VERSION}`;
constant QUICK_JS_SYSTEM_NAME (line 66) | const QUICK_JS_SYSTEM_NAME =
constant QUICK_JS_ARCH_NAME (line 75) | const QUICK_JS_ARCH_NAME =
constant QUICK_JS_TAR_NAME (line 78) | const QUICK_JS_TAR_NAME = `${QUICK_JS_VERSION_TAG}.tar.gz`;
constant QUICK_JS_DOWNLOADED_FOLDER_NAME (line 79) | const QUICK_JS_DOWNLOADED_FOLDER_NAME = `quickjs-${QUICK_JS_VERSION}`;
constant QUICK_JS_TARGET_FOLDER_NAME (line 80) | const QUICK_JS_TARGET_FOLDER_NAME = "quickjs";
constant QUICK_JS_DOWNLOADED_NAME (line 81) | const QUICK_JS_DOWNLOADED_NAME = `qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_J...
constant QUICK_JS_TARGET_NAME (line 82) | const QUICK_JS_TARGET_NAME = "qjsc";
constant WASI_SDK_MAJOR_VER (line 109) | const WASI_SDK_MAJOR_VER = 11;
constant WASI_SDK_MINOR_VER (line 110) | const WASI_SDK_MINOR_VER = 0;
constant WASI_SDK_DOWNLOADED_FOLDER_NAME (line 111) | const WASI_SDK_DOWNLOADED_FOLDER_NAME = `wasi-sdk-${WASI_SDK_MAJOR_VER}....
constant WASI_SDK_SYSTEM_NAME (line 112) | const WASI_SDK_SYSTEM_NAME =
constant WASI_SDK_TAR_NAME (line 120) | const WASI_SDK_TAR_NAME = `${WASI_SDK_DOWNLOADED_FOLDER_NAME}-${WASI_SDK...
FILE: packages/near-sdk-js/src/cli/utils.ts
function executeCommand (line 11) | async function executeCommand(
function download (line 49) | async function download(url: string, verbose = false) {
constant UNINITIALIZED_PARAMETERS_ERROR (line 53) | const UNINITIALIZED_PARAMETERS_ERROR =
function validateContract (line 62) | async function validateContract(
FILE: packages/near-sdk-js/src/collections/lookup-map.ts
class LookupMap (line 13) | class LookupMap<DataType> extends SubType<DataType> {
method constructor (line 17) | constructor(readonly keyPrefix: string) {
method containsKey (line 26) | containsKey(key: string): boolean {
method get (line 37) | get(
method remove (line 57) | remove(
method set (line 79) | set(
method extend (line 102) | extend(
method serialize (line 116) | serialize(options?: Pick<GetOptions<DataType>, "serializer">): Uint8Ar...
method reconstruct (line 125) | static reconstruct<DataType>(data: LookupMap<unknown>): LookupMap<Data...
FILE: packages/near-sdk-js/src/collections/lookup-set.ts
class LookupSet (line 8) | class LookupSet<DataType> {
method constructor (line 12) | constructor(readonly keyPrefix: string) {}
method contains (line 20) | contains(
method remove (line 34) | remove(
method set (line 49) | set(
method extend (line 63) | extend(
method serialize (line 75) | serialize(options?: Pick<GetOptions<DataType>, "serializer">): Uint8Ar...
method reconstruct (line 84) | static reconstruct<DataType>(data: LookupSet<unknown>): LookupSet<Data...
FILE: packages/near-sdk-js/src/collections/subtype.ts
method subtype (line 6) | subtype(): any {}
method set_reconstructor (line 8) | set_reconstructor(
FILE: packages/near-sdk-js/src/collections/unordered-map.ts
type ValueAndIndex (line 15) | type ValueAndIndex = [value: string, index: number];
class UnorderedMap (line 20) | class UnorderedMap<DataType> extends SubType<DataType> {
method constructor (line 27) | constructor(readonly prefix: string) {
method length (line 36) | get length() {
method isEmpty (line 43) | isEmpty(): boolean {
method get (line 53) | get(
method set (line 76) | set(
method remove (line 105) | remove(
method clear (line 136) | clear(): void {
method createIteratorWithOptions (line 154) | private createIteratorWithOptions(options?: GetOptions<DataType>): {
method toArray (line 167) | toArray(options?: GetOptions<DataType>): [string, DataType][] {
method extend (line 184) | extend(keyValuePairs: [string, DataType][]) {
method serialize (line 195) | serialize(options?: Pick<GetOptions<DataType>, "serializer">): Uint8Ar...
method reconstruct (line 204) | static reconstruct<DataType>(
method keys (line 220) | keys({ start, limit }): string[] {
method [Symbol.iterator] (line 145) | [Symbol.iterator](): UnorderedMapIterator<DataType> {
class UnorderedMapIterator (line 238) | class UnorderedMapIterator<DataType> {
method constructor (line 246) | constructor(
method subtype (line 257) | subtype(): any {}
method next (line 259) | next(): { value: [string | null, DataType | null]; done: boolean } {
FILE: packages/near-sdk-js/src/collections/unordered-set.ts
function serializeIndex (line 12) | function serializeIndex(index: number) {
function deserializeIndex (line 19) | function deserializeIndex(rawIndex: Uint8Array): number {
class UnorderedSet (line 28) | class UnorderedSet<DataType> {
method constructor (line 35) | constructor(readonly prefix: string) {
method length (line 43) | get length(): number {
method isEmpty (line 50) | isEmpty(): boolean {
method contains (line 60) | contains(
method set (line 76) | set(
method remove (line 101) | remove(element: DataType, options?: GetOptions<DataType>): boolean {
method clear (line 147) | clear(options?: Pick<GetOptions<DataType>, "serializer">): void {
method createIteratorWithOptions (line 166) | private createIteratorWithOptions(options?: GetOptions<DataType>): {
method toArray (line 179) | toArray(options?: GetOptions<DataType>): DataType[] {
method extend (line 196) | extend(elements: DataType[]): void {
method serialize (line 207) | serialize(options?: Pick<GetOptions<DataType>, "serializer">): Uint8Ar...
method reconstruct (line 216) | static reconstruct<DataType>(
method elements (line 230) | elements({
method [Symbol.iterator] (line 157) | [Symbol.iterator](): VectorIterator<DataType> {
FILE: packages/near-sdk-js/src/collections/vector.ts
function indexToKey (line 14) | function indexToKey(prefix: string, index: number): string {
class Vector (line 26) | class Vector<DataType> extends SubType<DataType> {
method constructor (line 31) | constructor(readonly prefix: string, public length = 0) {
method isEmpty (line 38) | isEmpty(): boolean {
method get (line 48) | get(
method swapRemove (line 70) | swapRemove(index: number, options?: GetOptions<DataType>): DataType | ...
method push (line 100) | push(
method pop (line 118) | pop(options?: Omit<GetOptions<DataType>, "serializer">): DataType | nu...
method replace (line 141) | replace(
method extend (line 168) | extend(elements: DataType[]): void {
method createIteratorWithOptions (line 183) | private createIteratorWithOptions(options?: GetOptions<DataType>): {
method toArray (line 196) | toArray(options?: GetOptions<DataType>): DataType[] {
method clear (line 211) | clear(): void {
method serialize (line 225) | serialize(options?: Pick<GetOptions<DataType>, "serializer">): Uint8Ar...
method reconstruct (line 234) | static reconstruct<DataType>(data: Vector<DataType>): Vector<DataType> {
method [Symbol.iterator] (line 174) | [Symbol.iterator](): VectorIterator<DataType> {
class VectorIterator (line 244) | class VectorIterator<DataType> {
method constructor (line 251) | constructor(
method next (line 256) | next(): {
FILE: packages/near-sdk-js/src/near-bindgen.ts
type EmptyParameterObject (line 10) | type EmptyParameterObject = Record<never, never>;
type AnyObject (line 11) | type AnyObject = Record<string, unknown>;
type DecoratorFunction (line 13) | type DecoratorFunction = <AnyFunction extends (...args: any) => any>(
function migrate (line 24) | function migrate(_empty: EmptyParameterObject): DecoratorFunction {
function initialize (line 39) | function initialize(_empty: EmptyParameterObject): DecoratorFunction {
function view (line 54) | function view(_empty: EmptyParameterObject): DecoratorFunction {
function call (line 77) | function call({
type Middleware (line 117) | interface Middleware<Arguments extends Array<any>> {
function middleware (line 132) | function middleware<Arguments extends Array<any>>(
function NearBindgen (line 173) | function NearBindgen({
FILE: packages/near-sdk-js/src/promise.ts
class CreateAccount (line 23) | class CreateAccount extends PromiseAction {
method add (line 24) | add(promiseIndex: PromiseIndex) {
class DeployContract (line 34) | class DeployContract extends PromiseAction {
method constructor (line 38) | constructor(public code: Uint8Array) {
method add (line 42) | add(promiseIndex: PromiseIndex) {
class FunctionCall (line 52) | class FunctionCall extends PromiseAction {
method constructor (line 59) | constructor(
method add (line 68) | add(promiseIndex: PromiseIndex) {
class FunctionCallRaw (line 84) | class FunctionCallRaw extends PromiseAction {
method constructor (line 91) | constructor(
method add (line 100) | add(promiseIndex: PromiseIndex) {
class FunctionCallWeight (line 116) | class FunctionCallWeight extends PromiseAction {
method constructor (line 124) | constructor(
method add (line 134) | add(promiseIndex: PromiseIndex) {
class FunctionCallWeightRaw (line 151) | class FunctionCallWeightRaw extends PromiseAction {
method constructor (line 159) | constructor(
method add (line 169) | add(promiseIndex: PromiseIndex) {
class Transfer (line 186) | class Transfer extends PromiseAction {
method constructor (line 190) | constructor(public amount: Balance) {
method add (line 194) | add(promiseIndex: PromiseIndex) {
class Stake (line 204) | class Stake extends PromiseAction {
method constructor (line 209) | constructor(public amount: Balance, public publicKey: PublicKey) {
method add (line 213) | add(promiseIndex: PromiseIndex) {
class AddFullAccessKey (line 227) | class AddFullAccessKey extends PromiseAction {
method constructor (line 232) | constructor(public publicKey: PublicKey, public nonce: Nonce) {
method add (line 236) | add(promiseIndex: PromiseIndex) {
class AddAccessKey (line 250) | class AddAccessKey extends PromiseAction {
method constructor (line 258) | constructor(
method add (line 268) | add(promiseIndex: PromiseIndex) {
class DeleteKey (line 285) | class DeleteKey extends PromiseAction {
method constructor (line 289) | constructor(public publicKey: PublicKey) {
method add (line 293) | add(promiseIndex: PromiseIndex) {
class DeleteAccount (line 302) | class DeleteAccount extends PromiseAction {
method constructor (line 306) | constructor(public beneficiaryId: AccountId) {
method add (line 310) | add(promiseIndex: PromiseIndex) {
class PromiseSingle (line 315) | class PromiseSingle {
method constructor (line 316) | constructor(
method constructRecursively (line 323) | constructRecursively(): PromiseIndex {
class PromiseJoint (line 340) | class PromiseJoint {
method constructor (line 341) | constructor(
method constructRecursively (line 347) | constructRecursively(): PromiseIndex {
type PromiseSubtype (line 362) | type PromiseSubtype = PromiseSingle | PromiseJoint;
class NearPromise (line 367) | class NearPromise {
method constructor (line 372) | constructor(private subtype: PromiseSubtype, private shouldReturn: boo...
method new (line 379) | static new(accountId: AccountId): NearPromise {
method addAction (line 384) | private addAction(action: PromiseAction): NearPromise {
method createAccount (line 397) | createAccount(): NearPromise {
method deployContract (line 406) | deployContract(code: Uint8Array): NearPromise {
method functionCall (line 418) | functionCall(
method functionCallRaw (line 435) | functionCallRaw(
method functionCallWeight (line 453) | functionCallWeight(
method functionCallWeightRaw (line 474) | functionCallWeightRaw(
method transfer (line 491) | transfer(amount: Balance): NearPromise {
method stake (line 501) | stake(amount: Balance, publicKey: PublicKey): NearPromise {
method addFullAccessKey (line 511) | addFullAccessKey(publicKey: PublicKey): NearPromise {
method addFullAccessKeyWithNonce (line 522) | addFullAccessKeyWithNonce(publicKey: PublicKey, nonce: Nonce): NearPro...
method addAccessKey (line 535) | addAccessKey(
method addAccessKeyWithNonce (line 560) | addAccessKeyWithNonce(
method deleteKey (line 577) | deleteKey(publicKey: PublicKey): NearPromise {
method deleteAccount (line 586) | deleteAccount(beneficiaryId: AccountId): NearPromise {
method and (line 595) | and(other: NearPromise): NearPromise {
method then (line 605) | then(other: NearPromise): NearPromise {
method asReturn (line 624) | asReturn(): NearPromise {
method constructRecursively (line 632) | constructRecursively(): PromiseIndex {
method onReturn (line 645) | onReturn() {
method build (line 654) | build(): PromiseIndex {
type PromiseOrValue (line 659) | type PromiseOrValue<T> = NearPromise | T;
FILE: packages/near-sdk-js/src/types/account_id.ts
type AccountId (line 4) | type AccountId = string;
FILE: packages/near-sdk-js/src/types/collections.ts
type GetOptions (line 4) | interface GetOptions<DataType> {
FILE: packages/near-sdk-js/src/types/gas.ts
type Gas (line 4) | type Gas = bigint;
constant ONE_TERA_GAS (line 8) | const ONE_TERA_GAS: Gas = 1_000_000_000_000n;
FILE: packages/near-sdk-js/src/types/primitives.ts
type StorageUsage (line 4) | type StorageUsage = bigint;
type BlockHeight (line 8) | type BlockHeight = bigint;
type EpochHeight (line 12) | type EpochHeight = bigint;
type Balance (line 16) | type Balance = bigint;
type Nonce (line 20) | type Nonce = bigint;
type GasWeight (line 24) | type GasWeight = bigint;
constant ONE_YOCTO (line 28) | const ONE_YOCTO: Balance = 1n;
constant ONE_NEAR (line 32) | const ONE_NEAR: Balance = 1_000_000_000_000_000_000_000_000n;
FILE: packages/near-sdk-js/src/types/public_key.ts
type CurveType (line 4) | enum CurveType {
type DataLength (line 9) | enum DataLength {
function getCurveType (line 14) | function getCurveType(curveType: CurveType | number): CurveType {
function dataLength (line 24) | function dataLength(curveType: CurveType | number): DataLength {
function splitKeyTypeData (line 37) | function splitKeyTypeData(value: string): [CurveType, string] {
function curveTypeFromStr (line 49) | function curveTypeFromStr(value: string): CurveType {
class ParsePublicKeyError (line 60) | class ParsePublicKeyError extends Error {}
class InvalidLengthError (line 62) | class InvalidLengthError extends ParsePublicKeyError {
method constructor (line 63) | constructor(public length: number, public expectedLength: number) {
class Base58Error (line 67) | class Base58Error extends ParsePublicKeyError {
method constructor (line 68) | constructor(public error: string) {
class UnknownCurve (line 72) | class UnknownCurve extends ParsePublicKeyError {
method constructor (line 73) | constructor() {
class PublicKey (line 83) | class PublicKey {
method constructor (line 93) | constructor(data: Uint8Array) {
method curveType (line 107) | curveType(): CurveType {
method fromString (line 116) | static fromString(publicKeyString: string) {
FILE: packages/near-sdk-js/src/types/vm_types.ts
type ReceiptIndex (line 4) | type ReceiptIndex = bigint;
type IteratorIndex (line 8) | type IteratorIndex = bigint;
type PromiseResult (line 16) | enum PromiseResult {
type PromiseError (line 25) | enum PromiseError {
FILE: packages/near-sdk-js/src/utils.ts
type Env (line 4) | interface Env {
type PromiseIndex (line 16) | type PromiseIndex = number | bigint;
type NearAmount (line 20) | type NearAmount = number | bigint;
type Register (line 24) | type Register = number | bigint;
constant TYPE_KEY (line 26) | const TYPE_KEY = "typeInfo";
type TypeBrand (line 27) | enum TypeBrand {
constant ERR_INCONSISTENT_STATE (line 32) | const ERR_INCONSISTENT_STATE =
constant ERR_INDEX_OUT_OF_BOUNDS (line 34) | const ERR_INDEX_OUT_OF_BOUNDS = "Index out of bounds";
constant ACCOUNT_ID_REGEX (line 36) | const ACCOUNT_ID_REGEX =
function concat (line 45) | function concat(array1: Uint8Array, array2: Uint8Array): Uint8Array {
function assert (line 58) | function assert(
type Mutable (line 67) | type Mutable<T> = { -readonly [P in keyof T]: T[P] };
function getValueWithOptions (line 69) | function getValueWithOptions<DataType>(
function serializeValueWithOptions (line 150) | function serializeValueWithOptions<DataType>(
function serialize (line 159) | function serialize(valueToSerialize: unknown): Uint8Array {
function deserialize (line 185) | function deserialize(valueToDeserialize: Uint8Array): unknown {
function decodeObj2class (line 205) | function decodeObj2class(class_instance, obj) {
function validateAccountId (line 287) | function validateAccountId(accountId: string): boolean {
class TextEncoder (line 298) | class TextEncoder {
method encode (line 299) | encode(s: string): Uint8Array {
class TextDecoder (line 307) | class TextDecoder {
method constructor (line 308) | constructor(public encoding: string = "utf-8") {}
method decode (line 310) | decode(a: Uint8Array): string {
function bytes (line 326) | function bytes(s: string): Uint8Array {
function str (line 335) | function str(a: Uint8Array): string {
function encode (line 344) | function encode(s: string): Uint8Array {
function decode (line 353) | function decode(a: Uint8Array): string {
type IntoStorageKey (line 360) | interface IntoStorageKey {
FILE: packages/near-sdk-js/src/version.ts
constant PACKAGE_JSON (line 4) | const PACKAGE_JSON = JSON.parse(
constant LIB_VERSION (line 10) | const LIB_VERSION: string = PACKAGE_JSON["version"];
FILE: tests/__tests__/abi/testcases/json_schema.ts
type Pair (line 3) | type Pair = [number, number];
type PairNamed (line 5) | interface PairNamed {
type IpAddrKind (line 10) | enum IpAddrKind {
type IpV4 (line 15) | interface IpV4 {
type IpV6 (line 20) | interface IpV6 {
type IpAddr (line 25) | type IpAddr = IpV4 | IpV6;
class Contract (line 28) | class Contract {
method numeric (line 30) | numeric({ a }: { a: number }) {}
method schema_string (line 33) | schema_string({ a }: { a: string }) {}
method schema_other_primitives (line 36) | schema_other_primitives({ a, b }: { a: boolean; b: null }) {}
method schema_tuples (line 39) | schema_tuples({
method schema_array (line 50) | schema_array({ a }: { a: boolean[] }) {}
method schema_struct (line 53) | schema_struct({ a, b }: { a: Pair; b: PairNamed }) {}
method schema_enum (line 56) | schema_enum({ simple, complex }: { simple: IpAddrKind; complex: IpAddr...
FILE: tests/__tests__/abi/testcases/modifiers.ts
class Contract (line 4) | class Contract {
method add (line 6) | add({ a, b }: { a: number; b: number }): number {
method add2 (line 11) | add2({ a, b }: { a: number; b: number }): number {
method add3 (line 16) | add3({ a, b }: { a: number; b: number }): number {
method add4 (line 21) | add4({ a, b }: { a: number; b: number }): number {
method add5 (line 26) | add5({ a, b }: { a: number; b: number }): number {
FILE: tests/__tests__/abi/testcases/return.ts
class Contract (line 4) | class Contract {
method foo (line 6) | foo() {}
method bar (line 9) | bar(): number {
FILE: tests/__tests__/abi/testcases/simple_function.ts
class Contract (line 4) | class Contract {
method add (line 6) | add({ a, b }: { a: number; b: number }): number {
FILE: tests/__tests__/abi/util.js
function generateAbiSnippet (line 10) | async function generateAbiSnippet(filename) {
FILE: tests/__tests__/bytes.ava.js
function encodeStateKey (line 89) | function encodeStateKey(k) {
FILE: tests/__tests__/constructor_validation.ava.js
constant BUILD_FAILURE_ERROR_CODE (line 4) | const BUILD_FAILURE_ERROR_CODE = 1;
FILE: tests/__tests__/decorators/payable.ava.js
constant DEPOSIT (line 4) | const DEPOSIT = 1_000_000_000;
FILE: tests/src/alt_bn128_api.js
function test_alt_bn128_g1_sum (line 5) | function test_alt_bn128_g1_sum() {
function test_alt_bn128_g1_multiexp (line 16) | function test_alt_bn128_g1_multiexp() {
function test_alt_bn128_pairing_check_valid (line 29) | function test_alt_bn128_pairing_check_valid() {
function test_alt_bn128_pairing_check_invalid (line 60) | function test_alt_bn128_pairing_check_invalid() {
FILE: tests/src/bigint-serialization.ts
class BigIntSerializationTest (line 12) | class BigIntSerializationTest {
method constructor (line 15) | constructor() {
method getBigintField (line 20) | getBigintField(): bigint {
method setBigintField (line 26) | setBigintField(args: { bigintField: bigint }): void {
method increment (line 33) | increment(): void {
FILE: tests/src/bytes.js
function log_expected_input_tests (line 5) | function log_expected_input_tests() {
function log_unexpected_input_tests (line 23) | function log_unexpected_input_tests() {
function log_invalid_utf8_sequence_test (line 30) | function log_invalid_utf8_sequence_test() {
function log_invalid_utf16_sequence_test (line 34) | function log_invalid_utf16_sequence_test() {
function storage_write_bytes (line 38) | function storage_write_bytes() {
function storage_write_utf8 (line 44) | function storage_write_utf8() {
function storage_read_utf8 (line 48) | function storage_read_utf8() {
function storage_read_ascii_bytes (line 52) | function storage_read_ascii_bytes() {
function storage_read_arbitrary_bytes_key_utf8_sequence_bytes_value (line 56) | function storage_read_arbitrary_bytes_key_utf8_sequence_bytes_value() {
function storage_read_utf8_sequence_bytes_key_arbitrary_bytes_value (line 60) | function storage_read_utf8_sequence_bytes_key_arbitrary_bytes_value() {
function panic_test (line 64) | function panic_test() {
function panic_ascii_test (line 68) | function panic_ascii_test() {
function panic_js_number (line 72) | function panic_js_number() {
function panic_js_undefined (line 76) | function panic_js_undefined() {
function panic_js_null (line 80) | function panic_js_null() {
function panic_utf8_test (line 84) | function panic_utf8_test() {
function panicUtf8_valid_utf8_sequence (line 88) | function panicUtf8_valid_utf8_sequence() {
function panicUtf8_invalid_utf8_sequence (line 92) | function panicUtf8_invalid_utf8_sequence() {
function utf8_string_to_uint8array_tests (line 100) | function utf8_string_to_uint8array_tests() {
function uint8array_to_utf8_string_tests (line 126) | function uint8array_to_utf8_string_tests() {
function uint8array_to_latin1_string_tests (line 147) | function uint8array_to_latin1_string_tests() {
FILE: tests/src/constructor-validation/1-parameter-not-set-in-constructor.ts
class ConstructorValidation (line 4) | class ConstructorValidation {
method constructor (line 7) | constructor() {
FILE: tests/src/constructor-validation/all-parameters-set-in-constructor.ts
class ConstructorValidation (line 4) | class ConstructorValidation {
method constructor (line 7) | constructor() {
method get (line 13) | get() {
FILE: tests/src/constructor-validation/no-constructor.ts
class ConstructorValidation (line 4) | class ConstructorValidation {
FILE: tests/src/constructor-validation/no-parameters-set-in-constructor.ts
class ConstructorValidation (line 4) | class ConstructorValidation {
method constructor (line 7) | constructor() {
FILE: tests/src/context_api.js
function get_current_account_id (line 5) | function get_current_account_id() {
function get_signer_account_id (line 9) | function get_signer_account_id() {
function get_predecessor_account_id (line 13) | function get_predecessor_account_id() {
function get_signer_account_pk (line 17) | function get_signer_account_pk() {
function get_input (line 21) | function get_input() {
function get_storage_usage (line 25) | function get_storage_usage() {
function get_block_height (line 29) | function get_block_height() {
function get_block_timestamp (line 33) | function get_block_timestamp() {
function get_epoch_height (line 37) | function get_epoch_height() {
function get_attached_deposit (line 41) | function get_attached_deposit() {
function get_prepaid_gas (line 45) | function get_prepaid_gas() {
function get_used_gas (line 49) | function get_used_gas() {
function get_random_seed (line 53) | function get_random_seed() {
function get_validator_stake (line 57) | function get_validator_stake() {
function get_total_stake (line 61) | function get_total_stake() {
FILE: tests/src/date-serialization.ts
class DateSerializationTest (line 12) | class DateSerializationTest {
method constructor (line 15) | constructor() {
method getDateField (line 20) | getDateField(): Date {
method setDateField (line 26) | setDateField(args: { dateField: Date }): void {
method getDateFieldAsMilliseconds (line 33) | getDateFieldAsMilliseconds(): number {
FILE: tests/src/decorators/payable.ts
class PayableTest (line 17) | class PayableTest {
method constructor (line 20) | constructor() {
method setValueWithPayableFunction (line 25) | setValueWithPayableFunction({ value }: { value: string }): void {
method setValueWithNotPayableFunction (line 31) | setValueWithNotPayableFunction({ value }: { value: string }): void {
method setValueWithNotPayableFunctionByDefault (line 37) | setValueWithNotPayableFunctionByDefault({ value }: { value: string }):...
method getValue (line 43) | getValue(): string {
FILE: tests/src/decorators/private.ts
class PrivateTest (line 17) | class PrivateTest {
method constructor (line 20) | constructor() {
method setValueWithPrivateFunction (line 25) | setValueWithPrivateFunction({ value }: { value: string }): void {
method setValueWithNotPrivateFunction (line 31) | setValueWithNotPrivateFunction({ value }: { value: string }): void {
method setValueWithNotPrivateFunctionByDefault (line 37) | setValueWithNotPrivateFunctionByDefault({ value }: { value: string }):...
method getValue (line 43) | getValue(): string {
FILE: tests/src/decorators/require_init_false.ts
class NBTest (line 14) | class NBTest {
method constructor (line 17) | constructor() {
method init (line 22) | init({ status }: { status: string }): void {
method getStatus (line 28) | getStatus(): string {
method setStatus (line 34) | setStatus({ status }: { status: string }): void {
FILE: tests/src/decorators/require_init_true.ts
class NBTest (line 14) | class NBTest {
method constructor (line 17) | constructor() {
method init (line 22) | init({ status }: { status: string }): void {
method getStatus (line 28) | getStatus(): string {
method setStatus (line 34) | setStatus({ status }: { status: string }): void {
FILE: tests/src/function-params.js
class FunctionParamsTestContract (line 13) | class FunctionParamsTestContract {
method constructor (line 14) | constructor() {
method set_values (line 20) | @call({})
method get_values (line 28) | @view({})
FILE: tests/src/highlevel-promise.js
function callingData (line 4) | function callingData() {
function arrayN (line 13) | function arrayN(n) {
class HighlevelPromiseContract (line 21) | class HighlevelPromiseContract {
method test_promise_batch_stake (line 22) | @call({})
method test_promise_batch_create_transfer (line 32) | @call({})
method test_promise_add_full_access_key (line 40) | @call({})
method test_promise_add_function_call_access_key (line 49) | @call({})
method test_delete_account (line 63) | @call({})
method test_promise_then (line 72) | @call({})
method test_promise_and (line 87) | @call({})
method cross_contract_callback (line 115) | @call({})
method cross_contract_callback_write_state (line 127) | @call({})
method callee_panic (line 135) | @call({})
method before_and_after_callee_panic (line 146) | @call({})
method callee_panic_then (line 159) | @call({})
method callee_panic_and (line 174) | @call({})
method callee_success_then_panic (line 202) | @call({})
method handler (line 218) | @call({})
method handle_error_in_promise_then (line 232) | @call({})
method handle_error_in_promise_then_after_promise_and (line 247) | @call({})
method not_return_not_build (line 270) | @call({})
method build_not_return (line 278) | @call({})
FILE: tests/src/log_panic_api.js
function log_expected_input_tests (line 5) | function log_expected_input_tests() {
function log_invalid_utf8_sequence_test (line 23) | function log_invalid_utf8_sequence_test() {
function log_invalid_utf16_sequence_test (line 27) | function log_invalid_utf16_sequence_test() {
function panic_test (line 31) | function panic_test() {
function panic_ascii_test (line 35) | function panic_ascii_test() {
function panic_js_number (line 39) | function panic_js_number() {
function panic_js_undefined (line 43) | function panic_js_undefined() {
function panic_js_null (line 47) | function panic_js_null() {
function panic_utf8_test (line 51) | function panic_utf8_test() {
function panicUtf8_valid_utf8_sequence (line 55) | function panicUtf8_valid_utf8_sequence() {
function panicUtf8_invalid_utf8_sequence (line 59) | function panicUtf8_invalid_utf8_sequence() {
FILE: tests/src/lookup-map.js
class LookupMapTestContract (line 17) | class LookupMapTestContract {
method constructor (line 18) | constructor() {
method get (line 22) | @view({})
method containsKey (line 27) | @view({})
method set (line 32) | @call({})
method remove_key (line 37) | @call({})
method extend (line 42) | @call({})
method add_house (line 47) | @call({})
method get_house (line 58) | @view({})
FILE: tests/src/lookup-set.js
class LookupSetTestContract (line 16) | class LookupSetTestContract {
method constructor (line 17) | constructor() {
method contains (line 21) | @view({})
method set (line 26) | @call({})
method remove_key (line 31) | @call({})
method extend (line 36) | @call({})
method add_house (line 41) | @call({})
method house_exist (line 50) | @view({})
FILE: tests/src/math_api.js
function test_sha256 (line 5) | function test_sha256() {
function test_keccak256 (line 9) | function test_keccak256() {
function test_keccak512 (line 13) | function test_keccak512() {
function test_ripemd160 (line 17) | function test_ripemd160() {
function test_ecrecover (line 21) | function test_ecrecover() {
FILE: tests/src/middlewares.ts
class Contract (line 16) | class Contract {
method init (line 20) | init({ randomData: _ }: { randomData: string }) {}
method add (line 25) | add({ id: _, text: _t }: { id: string; text: string }) {}
method get (line 29) | get({ id, accountId }: { id: string; accountId: string }): {
method get_two (line 41) | get_two({ id, accountId }: { id: string; accountId: string }): {
method get_private (line 49) | get_private(): { id: string; accountId: string } {
method getFromPrivate (line 54) | getFromPrivate({ id, accountId }: { id: string; accountId: string }): {
FILE: tests/src/migrate.ts
class Counter (line 13) | class Counter {
method increase (line 17) | increase({ n = 1 }: { n: number }) {
method getCount (line 23) | getCount(): number {
method migrFuncValueTo18 (line 28) | migrFuncValueTo18(): void {
FILE: tests/src/model.js
class House (line 8) | class House {
method constructor (line 9) | constructor(name, rooms) {
method describe (line 14) | describe() {
class Room (line 26) | class Room {
method constructor (line 27) | constructor(name, size) {
method describe (line 32) | describe() {
FILE: tests/src/promise_api.js
function arrayN (line 5) | function arrayN(n) {
function just_panic (line 9) | function just_panic() {
function write_some_state (line 13) | function write_some_state() {
function callingData (line 20) | function callingData() {
function cross_contract_callee (line 29) | function cross_contract_callee() {
function cross_contract_call_gas (line 33) | function cross_contract_call_gas() {
function cross_contract_callback (line 37) | function cross_contract_callback() {
function test_promise_create (line 48) | function test_promise_create() {
function test_promise_create_gas_overflow (line 58) | function test_promise_create_gas_overflow() {
function test_promise_then (line 68) | function test_promise_then() {
function test_promise_and (line 86) | function test_promise_and() {
FILE: tests/src/promise_batch_api.js
function test_promise_batch_stake (line 5) | function test_promise_batch_stake() {
function test_transfer_overflow (line 15) | function test_transfer_overflow() {
function test_promise_add_full_access_key (line 22) | function test_promise_add_full_access_key() {
function test_delete_account (line 34) | function test_delete_account() {
function test_promise_add_function_call_access_key (line 42) | function test_promise_add_function_call_access_key() {
function test_promise_batch_create_transfer (line 57) | function test_promise_batch_create_transfer() {
function test_promise_batch_call_weight (line 64) | function test_promise_batch_call_weight() {
function test_promise_batch_deploy_call (line 77) | function test_promise_batch_deploy_call() {
FILE: tests/src/public-key.js
function runtime_validate_public_key (line 7) | function runtime_validate_public_key(prefix, public_key) {
function test_add_signer_key (line 15) | function test_add_signer_key() {
function test_add_ed25519_key_bytes (line 19) | function test_add_ed25519_key_bytes() {
function test_add_ed25519_key_string (line 32) | function test_add_ed25519_key_string() {
function test_add_secp256k1_key_bytes (line 38) | function test_add_secp256k1_key_bytes() {
function test_add_secp256k1_key_string (line 53) | function test_add_secp256k1_key_string() {
function add_invalid_public_key (line 60) | function add_invalid_public_key() {
function curve_type (line 67) | function curve_type() {
function create_invalid_curve_type (line 73) | function create_invalid_curve_type() {
function create_invalid_length (line 77) | function create_invalid_length() {
function create_from_invalid_base58 (line 81) | function create_from_invalid_base58() {
FILE: tests/src/storage_api.js
function test_storage_write (line 5) | function test_storage_write() {
function test_storage_read (line 15) | function test_storage_read() {
function test_storage_remove (line 19) | function test_storage_remove() {
function test_storage_has_key (line 25) | function test_storage_has_key() {
function test_storage_get_evicted (line 31) | function test_storage_get_evicted() {
FILE: tests/src/typescript.ts
class TypeScriptTestContract (line 4) | class TypeScriptTestContract {
method bigint (line 6) | bigint() {
FILE: tests/src/unordered-map.js
class UnorderedMapTestContract (line 21) | class UnorderedMapTestContract {
method constructor (line 22) | constructor() {
method len (line 26) | @view({})
method isEmpty (line 31) | @view({})
method get (line 36) | @view({})
method set (line 41) | @call({})
method remove_key (line 46) | @call({})
method clear (line 51) | @call({})
method toArray (line 56) | @view({})
method extend (line 61) | @call({})
method add_house (line 66) | @call({})
method get_house (line 77) | @view({})
method keys (line 90) | @view({})
FILE: tests/src/unordered-set.js
class UnorderedSetTestContract (line 21) | class UnorderedSetTestContract {
method constructor (line 22) | constructor() {
method len (line 26) | @view({})
method isEmpty (line 31) | @view({})
method contains (line 36) | @view({})
method set (line 41) | @call({})
method remove_key (line 46) | @call({})
method clear (line 51) | @call({})
method toArray (line 56) | @view({})
method elements (line 62) | @view({})
method extend (line 67) | @call({})
method add_house (line 72) | @call({})
method house_exist (line 81) | @view({})
FILE: tests/src/vector.js
class VectorTestContract (line 24) | class VectorTestContract {
method constructor (line 25) | constructor() {
method len (line 29) | @view({})
method isEmpty (line 34) | @view({})
method get (line 39) | @view({})
method push (line 44) | @call({})
method pop (line 49) | @call({})
method clear (line 54) | @call({})
method toArray (line 59) | @view({})
method extend (line 64) | @call({})
method replace (line 69) | @call({})
method swapRemove (line 74) | @call({})
method add_house (line 79) | @call({})
method get_house (line 89) | @view({})
Condensed preview — 348 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,088K chars).
[
{
"path": ".gitattributes",
"chars": 273,
"preview": "pnpm-lock.yaml linguist-generated=true -diff\n/**/lib/**/*.js linguist-generated=true -diff\n/**/lib/**/*.d.ts linguist-ge"
},
{
"path": ".github/ISSUE_TEMPLATE/bug.yml",
"chars": 3146,
"preview": "name: Bug Report\ndescription: Submit a bug report to help us improve\nlabels: [bug, 'status: needs triage']\nbody:\n - typ"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 212,
"preview": "blank_issues_enabled: false\ncontact_links:\n - name: 🚀 Feature request & ❓ Questions\n url: https://github.com/near/ne"
},
{
"path": ".github/ISSUE_TEMPLATE/feature.yml",
"chars": 2640,
"preview": "name: Feature design / RFC\ndescription: Submit a detailed feature request with a concrete proposal, including an exhaust"
},
{
"path": ".github/pull_request_template.md",
"chars": 1357,
"preview": "<!--\nThank you for sending the PR! We appreciate you spending the time to work on these changes.\nYou can learn more abou"
},
{
"path": ".github/workflows/add-to-devtools.yml",
"chars": 473,
"preview": "name: 'Add to DevTools Project'\n\non:\n issues:\n types:\n - opened\n - reopened\n pull_request_target:\n typ"
},
{
"path": ".github/workflows/tests.yml",
"chars": 1021,
"preview": "name: Test\non:\n pull_request:\n push:\n branches:\n - master\n - develop\njobs:\n tests:\n strategy:\n m"
},
{
"path": ".github/workflows/typedoc-generate-gitbook-docs.yml",
"chars": 1377,
"preview": "name: Deploy TypeDoc to GitBook\n\non:\n push:\n branches:\n - develop\n \nenv:\n NODE_VERSION: 18.x\n ENTRY_FILE: \"p"
},
{
"path": ".github/workflows/typedoc-generator.yml",
"chars": 984,
"preview": "name: Deploy TypeDoc on GitHub pages\n\non:\n push:\n branches:\n develop \n\nenv:\n NODE_VERSION: 18.x\n ENTRY"
},
{
"path": ".gitignore",
"chars": 65,
"preview": "node_modules\nvendor\n.idea\ndeps\n.turbo\nyarn.lock\npackage-lock.json"
},
{
"path": ".npmrc",
"chars": 15,
"preview": "save-exact=true"
},
{
"path": "AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md",
"chars": 7381,
"preview": "# JSON Schemas for Automatic Decoding of the State\n\nA limitation that we early detected in the `near-sdk-js` is that Cla"
},
{
"path": "CODEOWNERS",
"chars": 20,
"preview": "* @ailisp @volovyks\n"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 3358,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
},
{
"path": "CONTRIBUTING.md",
"chars": 8131,
"preview": "# Contributing to Near JavaScript SDK\n\nFirst off, thanks for taking the time to contribute! We look forward to to your c"
},
{
"path": "LICENSE",
"chars": 1023,
"preview": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentati"
},
{
"path": "LICENSE-APACHE",
"chars": 9723,
"preview": " Apache License\n Version 2.0, January 2004\n http"
},
{
"path": "README.md",
"chars": 3416,
"preview": "# NEAR JavaScript SDK\n\n<p>\n <a href=\"https://docs.near.org/tools/sdk\" target=\"_blank\">\n <img alt=\"Documentation\" src"
},
{
"path": "RELEASE.md",
"chars": 1889,
"preview": "# Release\n\nThis document describes step to do a new pre-release or formal release.\n\n## Release Requirement\n- A formal re"
},
{
"path": "RUNTIME_INVESTIGATE.md",
"chars": 786,
"preview": "# Runtime Investigate\nInvestigate how to compile js/ts to wasm by any tools, and the output wasm file can be executed on"
},
{
"path": "SECURITY.md",
"chars": 161,
"preview": "# Security Policy\n\n## Reporting a Vulnerability\n\nTo report security issues in this project please send an email to [secu"
},
{
"path": "TOOLING.md",
"chars": 1044,
"preview": "# Tooling\n\nThis document describes at a high level some the key tools used across `near-js`.\n\n## Package Manager - [PNPM"
},
{
"path": "benchmark/.gitignore",
"chars": 5,
"preview": "build"
},
{
"path": "benchmark/README.md",
"chars": 20615,
"preview": "# Gas and size benchmark compare to NEAR-SDK-RS\n\n## Summary\n\nNEAR-SDK-JS bundles a bytecode VM with the contract bytecod"
},
{
"path": "benchmark/__tests__/test-collections-performance.ava.js",
"chars": 5642,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logTotalGas, randomInt } from \"./util.js\";\n\nc"
},
{
"path": "benchmark/__tests__/test-deploy-contract.ava.js",
"chars": 4772,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport {\n formatGas,\n gasBreakdown,\n logGasBreakdow"
},
{
"path": "benchmark/__tests__/test-expensive-calc.ava.js",
"chars": 2624,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before"
},
{
"path": "benchmark/__tests__/test-highlevel-collection.ava.js",
"chars": 1950,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before"
},
{
"path": "benchmark/__tests__/test-highlevel-minimal.ava.js",
"chars": 1377,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before"
},
{
"path": "benchmark/__tests__/test-lowlevel-api.ava.js",
"chars": 1650,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before"
},
{
"path": "benchmark/__tests__/test-lowlevel-minimal.ava.js",
"chars": 1351,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before"
},
{
"path": "benchmark/__tests__/util.js",
"chars": 1845,
"preview": "// Functions consumed by the benchmark contracts tests\n\nexport function formatGas(gas) {\n if (gas < 10 ** 12) {\n let"
},
{
"path": "benchmark/ava.config.cjs",
"chars": 207,
"preview": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n timeout: \"30000"
},
{
"path": "benchmark/example-outcome.json",
"chars": 3322,
"preview": "{\n \"result\": {\n \"receipts_outcome\": [\n {\n \"block_hash\": \"B5zQjLFz1zu36xoUd37Bghzeanw8YfbkLk9amcVdPX4H\",\n"
},
{
"path": "benchmark/jsconfig.json",
"chars": 97,
"preview": "{\n \"compilerOptions\": {\n \"experimentalDecorators\": true\n },\n \"exclude\": [\"node_modules\"]\n}\n"
},
{
"path": "benchmark/package.json",
"chars": 2030,
"preview": "{\n \"name\": \"bench\",\n \"version\": \"1.0.0\",\n \"description\": \"near-sdk-js benchmark\",\n \"main\": \"index.js\",\n \"type\": \"mo"
},
{
"path": "benchmark/src/deploy-contract.js",
"chars": 682,
"preview": "import { near } from \"near-sdk-js\";\n\n/**\n * Used for contract deployment. More information for that\n * can be found in t"
},
{
"path": "benchmark/src/expensive-calc.js",
"chars": 457,
"preview": "import { NearBindgen, call, near } from \"near-sdk-js\";\n\n/**\n * ExpensiveCalc is connected to the expensive contract. Mor"
},
{
"path": "benchmark/src/highlevel-collection.js",
"chars": 360,
"preview": "import { NearBindgen, call, UnorderedMap } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the REA"
},
{
"path": "benchmark/src/highlevel-minimal.js",
"chars": 249,
"preview": "import { NearBindgen, call } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the README.md\n * - A "
},
{
"path": "benchmark/src/lookup-map.js",
"chars": 458,
"preview": "import { NearBindgen, call, LookupMap, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class LookupMapContract {\n "
},
{
"path": "benchmark/src/lookup-set.js",
"chars": 466,
"preview": "import { NearBindgen, call, LookupSet, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class LookupSetContract {\n "
},
{
"path": "benchmark/src/lowlevel-api.js",
"chars": 897,
"preview": "import { near } from \"near-sdk-js\";\n\n/**\n * Helper method for the low level api. More information for that can be found "
},
{
"path": "benchmark/src/lowlevel-minimal.js",
"chars": 155,
"preview": "import { near } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the README.md\n * - A minimal contr"
},
{
"path": "benchmark/src/unordered-map.js",
"chars": 652,
"preview": "import { NearBindgen, call, UnorderedMap, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class UnorderedMapContract"
},
{
"path": "benchmark/src/unordered-set.js",
"chars": 665,
"preview": "import { NearBindgen, call, UnorderedSet, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class UnorderedSetContract"
},
{
"path": "benchmark/src/vector.js",
"chars": 600,
"preview": "import { NearBindgen, call, Vector, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class VectorContract {\n const"
},
{
"path": "benchmark/tsconfig.json",
"chars": 173,
"preview": "{\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"experimentalDecorators\": true,\n \"target\": \"es2020\",\n "
},
{
"path": "examples/.gitignore",
"chars": 18,
"preview": "build\nnode_modules"
},
{
"path": "examples/README.md",
"chars": 3454,
"preview": "# Example Smart Contracts\n\nThis directory contains example smart contracts that demonstrate various functionalities usin"
},
{
"path": "examples/__tests__/standard-ft/ft-tests.ava.js",
"chars": 10941,
"preview": "import { NEAR, Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nconst INITIAL_BALANCE = NEAR.parse(\"10000 N\").t"
},
{
"path": "examples/__tests__/standard-nft/test_approval.ava.js",
"chars": 7703,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/standard-nft/test_core.ava.js",
"chars": 6618,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nconst MAX_GAS = 300_000_000_000_000n;\n\ntest.beforeEac"
},
{
"path": "examples/__tests__/standard-nft/test_enumeration.ava.js",
"chars": 4572,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nasync function helper_mint(nft, nftOwner, id, title, "
},
{
"path": "examples/__tests__/test-basic-updates.ava.js",
"chars": 1594,
"preview": "import {NEAR, Worker} from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker ="
},
{
"path": "examples/__tests__/test-clean-state.ava.js",
"chars": 1104,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-counter.ava.js",
"chars": 1992,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-cross-contract-call-loop.ava.js",
"chars": 1579,
"preview": "import { Worker, NEAR } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker ="
},
{
"path": "examples/__tests__/test-cross-contract-call-ts.ava.js",
"chars": 2294,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-cross-contract-call.ava.js",
"chars": 2300,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-fungible-token-lockable.ava.js",
"chars": 6475,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-fungible-token.ava.js",
"chars": 6705,
"preview": "import { Worker, NEAR } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker ="
},
{
"path": "examples/__tests__/test-nested-collections.ava.js",
"chars": 2987,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and s"
},
{
"path": "examples/__tests__/test-non-fungible-token.ava.js",
"chars": 3760,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-parking-lot.ava.js",
"chars": 1060,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker = await"
},
{
"path": "examples/__tests__/test-programmatic-update.ava.js",
"chars": 1487,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport * as fs from \"fs\";\nimport * as path from \"path\""
},
{
"path": "examples/__tests__/test-state-message-migration-add-filed.ava.js",
"chars": 1243,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker = awa"
},
{
"path": "examples/__tests__/test-state-migration.ava.js",
"chars": 1387,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n const worker = awa"
},
{
"path": "examples/__tests__/test-status-deserialize-class.ava.js",
"chars": 5305,
"preview": "import {Worker} from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and sta"
},
{
"path": "examples/__tests__/test-status-message-borsh.ava.js",
"chars": 1966,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and"
},
{
"path": "examples/__tests__/test-status-message-collections.ava.js",
"chars": 2663,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n // Init the worker a"
},
{
"path": "examples/__tests__/test-status-message-deserialize-err.ava.js",
"chars": 1594,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and"
},
{
"path": "examples/__tests__/test-status-message-serialize-err.ava.js",
"chars": 1498,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and"
},
{
"path": "examples/__tests__/test-status-message.ava.js",
"chars": 1872,
"preview": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n // Init the worker and s"
},
{
"path": "examples/ava.config.cjs",
"chars": 207,
"preview": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n timeout: \"30000"
},
{
"path": "examples/jsconfig.json",
"chars": 128,
"preview": "{\n \"compilerOptions\": {\n \"experimentalDecorators\": true\n },\n \"exclude\": [\"node_modules\"],\n \"files\": [\"src/counter"
},
{
"path": "examples/package.json",
"chars": 6686,
"preview": "{\n \"name\": \"examples\",\n \"version\": \"1.0.0\",\n \"description\": \"Status message example with near-sdk-js\",\n \"main\": \"ind"
},
{
"path": "examples/src/basic-updates/basic-updates-base.js",
"chars": 1217,
"preview": "import {\n NearBindgen,\n call,\n view,\n near,\n Vector,\n ONE_NEAR\n} from \"near-sdk-js\";\n\nconst POINT_ONE "
},
{
"path": "examples/src/basic-updates/basic-updates-update.js",
"chars": 2216,
"preview": "import {NearBindgen, call, view, near, migrate, Vector, assert, ONE_NEAR} from \"near-sdk-js\";\n\nconst POINT_ONE = ONE_NEA"
},
{
"path": "examples/src/clean-state.js",
"chars": 339,
"preview": "import { NearBindgen, call, view, near } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class CleanState {\n @call({})\n c"
},
{
"path": "examples/src/counter/counter-lowlevel.js",
"chars": 1213,
"preview": "// This contract implements exact same functionality as counter.js, but only use low level APIs\nimport { near } from \"ne"
},
{
"path": "examples/src/counter/counter.js",
"chars": 648,
"preview": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\nimport { isUndefined } from \"lodash-es\";\n\n@NearBindgen({})\n"
},
{
"path": "examples/src/counter/counter.ts",
"chars": 735,
"preview": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\nimport { isUndefined } from \"lodash-es\";\nimport { log } fro"
},
{
"path": "examples/src/counter/log.ts",
"chars": 92,
"preview": "import { near } from \"near-sdk-js\";\n\nexport function log(msg: unknown) {\n near.log(msg);\n}\n"
},
{
"path": "examples/src/cross-contract-calls/cross-contract-call-loop.js",
"chars": 1358,
"preview": "import { call, near, NearBindgen, NearPromise, view } from \"near-sdk-js\";\n\nconst CONTRACTS = [\n \"first-contract.test.ne"
},
{
"path": "examples/src/cross-contract-calls/cross-contract-call.js",
"chars": 1493,
"preview": "import { NearBindgen, call, view, initialize, near } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport cla"
},
{
"path": "examples/src/cross-contract-calls/cross-contract-call.ts",
"chars": 1432,
"preview": "import { NearBindgen, call, view, initialize, near } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport cla"
},
{
"path": "examples/src/fungible-token/fungible-token-helper.ts",
"chars": 504,
"preview": "import { NearBindgen, call, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nclass _FungibleTokenHelper {\n data = \"\";\n\n @c"
},
{
"path": "examples/src/fungible-token/fungible-token-lockable.js",
"chars": 6933,
"preview": "import {\n NearBindgen,\n call,\n view,\n initialize,\n near,\n LookupMap,\n} from \"near-sdk-js\";\n\nclass Account {\n cons"
},
{
"path": "examples/src/fungible-token/fungible-token.ts",
"chars": 7220,
"preview": "import {\n NearBindgen,\n call,\n view,\n initialize,\n near,\n LookupMap,\n assert,\n validateAccountId,\n} from \"near-s"
},
{
"path": "examples/src/fungible-token/my-ft.ts",
"chars": 4233,
"preview": "import {\n StorageBalance,\n StorageBalanceBounds,\n StorageManagement,\n FungibleTokenCore,\n FungibleTokenRe"
},
{
"path": "examples/src/nested-collections.ts",
"chars": 2005,
"preview": "import { NearBindgen, near, call, view, UnorderedMap } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class Contract {\n o"
},
{
"path": "examples/src/non-fungible-token/my-nft.ts",
"chars": 5851,
"preview": "import { NonFungibleToken } from \"near-contract-standards/lib\";\nimport {\n assert,\n call,\n initialize,\n near,\n NearB"
},
{
"path": "examples/src/non-fungible-token/non-fungible-token-receiver.js",
"chars": 971,
"preview": "import { NearBindgen, call, near, assert, initialize } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport c"
},
{
"path": "examples/src/non-fungible-token/non-fungible-token.js",
"chars": 3659,
"preview": "import {\n NearBindgen,\n call,\n view,\n initialize,\n near,\n LookupMap,\n assert,\n} from \"near-sdk-js\";\n\nclass Token "
},
{
"path": "examples/src/non-fungible-token/test-approval-receiver.ts",
"chars": 1994,
"preview": "import {\n initialize,\n near,\n NearBindgen,\n NearPromise,\n PromiseOrValue,\n assert,\n call,\n serialize,\n} from \"ne"
},
{
"path": "examples/src/non-fungible-token/test-token-receiver.ts",
"chars": 2507,
"preview": "import { NonFungibleTokenReceiver } from \"near-contract-standards/lib/non_fungible_token/core/receiver\";\nimport {\n asse"
},
{
"path": "examples/src/parking-lot.ts",
"chars": 1910,
"preview": "import { NearBindgen, near, call, view, LookupMap } from \"near-sdk-js\";\n\nclass CarSpecs {\n id: number;\n color: string;"
},
{
"path": "examples/src/programmatic-updates/programmatic-update-after.ts",
"chars": 879,
"preview": "import { NearBindgen, near, initialize, assert, view } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport c"
},
{
"path": "examples/src/programmatic-updates/programmatic-update-before.ts",
"chars": 885,
"preview": "import { NearBindgen, near, initialize, assert, view } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport c"
},
{
"path": "examples/src/state-migration/state-migration-new.ts",
"chars": 2282,
"preview": "import { NearBindgen, view, near, migrate, call, Vector, assert } from 'near-sdk-js'\nimport { AccountId } from 'near-sdk"
},
{
"path": "examples/src/state-migration/state-migration-original.ts",
"chars": 699,
"preview": "import { NearBindgen, view, near, call, Vector } from 'near-sdk-js'\nimport { AccountId } from 'near-sdk-js/lib/types'\n\nt"
},
{
"path": "examples/src/status-deserialize-class.js",
"chars": 9613,
"preview": "import {\n NearBindgen,\n call,\n view,\n near,\n UnorderedMap,\n LookupMap,\n Vector,\n UnorderedSet,\n}"
},
{
"path": "examples/src/status-message/status-message-borsh.js",
"chars": 841,
"preview": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\nimport * as borsh from 'borsh';\n\nconst schema = {\n struct:"
},
{
"path": "examples/src/status-message/status-message-collections.js",
"chars": 870,
"preview": "import {\n NearBindgen,\n call,\n view,\n near,\n LookupSet,\n UnorderedMap,\n} from \"near-sdk-js\";\n\n@NearBindgen({})\nexp"
},
{
"path": "examples/src/status-message/status-message-deserialize-err.js",
"chars": 623,
"preview": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\n\n@NearBindgen({\n deserializer(_value) {\n throw new "
},
{
"path": "examples/src/status-message/status-message-migrate-add-field.js",
"chars": 1340,
"preview": "import {NearBindgen, call, view, near, migrate, assert} from \"near-sdk-js\";\n\nclass OldStatusMessage {\n constructor() {\n"
},
{
"path": "examples/src/status-message/status-message-serialize-err.js",
"chars": 619,
"preview": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\n\n@NearBindgen({\n serializer(_value) {\n throw new Er"
},
{
"path": "examples/src/status-message/status-message.js",
"chars": 501,
"preview": "import { NearBindgen, call, view, near } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class StatusMessage {\n constructo"
},
{
"path": "examples/tsconfig.json",
"chars": 173,
"preview": "{\n \"compilerOptions\": {\n \"experimentalDecorators\": true,\n \"target\": \"es2020\",\n \"moduleResolution\": \"node\",\n "
},
{
"path": "generate-docs-markdown.js",
"chars": 813,
"preview": "const { readFileSync, writeFileSync, unlinkSync } = require(\"fs\");\nconst { execSync } = require(\"child_process\");\n\n// Lo"
},
{
"path": "near-sdk-js@2.0.0-diff-1.0.0.md",
"chars": 6304,
"preview": "# Breaking features diff from SDK 2.0.0 to 1.0.0\n## borsh data de/serializer for contract state\n* using for: new contrac"
},
{
"path": "package.json",
"chars": 523,
"preview": "{\n \"private\": true,\n \"engines\": {\n \"node\": \">=14 <16.6.0 || >16.6.0\",\n \"pnpm\": \">=7\"\n },\n \"scripts\": {\n \"pr"
},
{
"path": "packages/near-contract-standards/.gitignore",
"chars": 18,
"preview": "build\nnode_modules"
},
{
"path": "packages/near-contract-standards/README.md",
"chars": 158,
"preview": "# Package for NEAR JS contract standards\n\nThis package provides a set of interfaces and implementations for NEAR's contr"
},
{
"path": "packages/near-contract-standards/ava.config.cjs",
"chars": 207,
"preview": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n timeout: \"30000"
},
{
"path": "packages/near-contract-standards/lib/event.d.ts",
"chars": 281,
"preview": "export declare abstract class NearEvent {\n private internal_to_json_string;\n private internal_to_json_event_string"
},
{
"path": "packages/near-contract-standards/lib/event.js",
"chars": 460,
"preview": "import { near } from \"near-sdk-js\";\nexport class NearEvent {\n internal_to_json_string() {\n return JSON.stringi"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/core.d.ts",
"chars": 5023,
"preview": "import { AccountId, PromiseOrValue, Balance } from \"near-sdk-js\";\nimport { Option } from \"../non_fungible_token/utils\";\n"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/core.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/core_impl.d.ts",
"chars": 4296,
"preview": "import { StorageBalance, StorageBalanceBounds, StorageManagement } from \"../storage_management\";\nimport { FungibleTokenC"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/core_impl.js",
"chars": 12333,
"preview": "import { StorageBalance, StorageBalanceBounds } from \"../storage_management\";\nimport { FtBurn, FtTransfer } from \"./even"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/events.d.ts",
"chars": 2965,
"preview": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <htt"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/events.js",
"chars": 3203,
"preview": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <htt"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/index.d.ts",
"chars": 163,
"preview": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/index.js",
"chars": 163,
"preview": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/metadata.d.ts",
"chars": 630,
"preview": "import { Option } from \"../non_fungible_token/utils\";\n/**\n * Return metadata for the token, up to contract to implement."
},
{
"path": "packages/near-contract-standards/lib/fungible_token/metadata.js",
"chars": 1010,
"preview": "import { assert, } from \"near-sdk-js\";\nconst FT_METADATA_SPEC = \"ft-1.0.0\";\n/**\n * Return metadata for the token, up to "
},
{
"path": "packages/near-contract-standards/lib/fungible_token/receiver.d.ts",
"chars": 2327,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n/**\n * Provides token transfer resolve functionality.\n *\n * # E"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/receiver.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/resolver.d.ts",
"chars": 1751,
"preview": "import { AccountId, Balance } from \"near-sdk-js\";\n/**\n * Provides token transfer resolve functionality.\n *\n * # Examples"
},
{
"path": "packages/near-contract-standards/lib/fungible_token/resolver.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/index.d.ts",
"chars": 313,
"preview": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \""
},
{
"path": "packages/near-contract-standards/lib/index.js",
"chars": 313,
"preview": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \""
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/approval/approval_receiver.d.ts",
"chars": 1209,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Approval receiver is th"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/approval/approval_receiver.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/approval/index.d.ts",
"chars": 4084,
"preview": "import { AccountId, NearPromise } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\nimport { Option } from \"../uti"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/approval/index.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts",
"chars": 5704,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { Token, TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n/"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/index.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts",
"chars": 2282,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Used when an NFT is tra"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/receiver.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts",
"chars": 2978,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Used when an NFT is transferred using `"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/core/resolver.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/enumeration/index.d.ts",
"chars": 1495,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { Token } from \"../token\";\n/** Offers methods helpful in determining acc"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/enumeration/index.js",
"chars": 11,
"preview": "export {};\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/events.d.ts",
"chars": 3584,
"preview": "/** Standard for nep171 (Non-Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <ht"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/events.js",
"chars": 3248,
"preview": "import { NearEvent } from \"../event\";\nimport { toSnakeCase } from \"../util\";\nexport class Nep171Event extends NearEvent "
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/impl.d.ts",
"chars": 4883,
"preview": "import { AccountId, UnorderedMap, LookupMap, UnorderedSet, NearPromise, IntoStorageKey } from \"near-sdk-js\";\nimport { To"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/impl.js",
"chars": 20750,
"preview": "import { UnorderedMap, LookupMap, near, UnorderedSet, assert, NearPromise, bytes, serialize, str, } from \"near-sdk-js\";\n"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/index.d.ts",
"chars": 1042,
"preview": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. "
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/index.js",
"chars": 1042,
"preview": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. "
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/metadata.d.ts",
"chars": 2440,
"preview": "import { Option } from \"./utils\";\n/** This spec can be treated like a version of the standard. */\nexport declare const N"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/metadata.js",
"chars": 3540,
"preview": "import { assert } from \"near-sdk-js\";\n/** This spec can be treated like a version of the standard. */\nexport const NFT_M"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/token.d.ts",
"chars": 994,
"preview": "import { TokenMetadata } from \"./metadata\";\nimport { AccountId } from \"near-sdk-js\";\n/** Note that token IDs for NFTs ar"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/token.js",
"chars": 426,
"preview": "/** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, "
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/utils.d.ts",
"chars": 700,
"preview": "import { AccountId } from \"near-sdk-js\";\nexport declare function refund_storage_deposit(account_id: AccountId, storage_r"
},
{
"path": "packages/near-contract-standards/lib/non_fungible_token/utils.js",
"chars": 1505,
"preview": "import { near, assert, bytes } from \"near-sdk-js\";\nexport function refund_storage_deposit(account_id, storage_released) "
},
{
"path": "packages/near-contract-standards/lib/storage_management/index.d.ts",
"chars": 2481,
"preview": "import { AccountId, Balance } from \"near-sdk-js\";\nimport { Option } from \"../non_fungible_token/utils\";\nexport declare c"
},
{
"path": "packages/near-contract-standards/lib/storage_management/index.js",
"chars": 258,
"preview": "export class StorageBalance {\n constructor(total, available) {\n this.total = total;\n this.available = a"
},
{
"path": "packages/near-contract-standards/lib/util.d.ts",
"chars": 59,
"preview": "export declare const toSnakeCase: (str: string) => string;\n"
},
{
"path": "packages/near-contract-standards/lib/util.js",
"chars": 170,
"preview": "export const toSnakeCase = (str) => {\n return str.replace(/[A-Z]/g, (letter, index) => { return index == 0 ? letter.t"
},
{
"path": "packages/near-contract-standards/package.json",
"chars": 463,
"preview": "{\n \"name\": \"near-contract-standards\",\n \"version\": \"2.0.0\",\n \"description\": \"Compatible near-contract-standards implem"
},
{
"path": "packages/near-contract-standards/src/event.ts",
"chars": 479,
"preview": "import { near } from \"near-sdk-js\";\n\nexport abstract class NearEvent {\n\n private internal_to_json_string(): string {\n "
},
{
"path": "packages/near-contract-standards/src/fungible_token/core.ts",
"chars": 5093,
"preview": "import { AccountId, PromiseOrValue, Balance } from \"near-sdk-js\"\nimport { Option } from \"../non_fungible_token/utils\"\n\n/"
},
{
"path": "packages/near-contract-standards/src/fungible_token/core_impl.ts",
"chars": 14604,
"preview": "import { StorageBalance, StorageBalanceBounds, StorageManagement } from \"../storage_management\";\nimport { FungibleTokenC"
},
{
"path": "packages/near-contract-standards/src/fungible_token/events.ts",
"chars": 3927,
"preview": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <htt"
},
{
"path": "packages/near-contract-standards/src/fungible_token/index.ts",
"chars": 162,
"preview": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from"
},
{
"path": "packages/near-contract-standards/src/fungible_token/metadata.ts",
"chars": 1516,
"preview": "import {\n assert,\n} from \"near-sdk-js\";\n\nimport { Option } from \"../non_fungible_token/utils\";\n\nconst FT_METADATA_SPE"
},
{
"path": "packages/near-contract-standards/src/fungible_token/receiver.ts",
"chars": 2361,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n\n/**\n * Provides token transfer resolve functionality.\n * \n * #"
},
{
"path": "packages/near-contract-standards/src/fungible_token/resolver.ts",
"chars": 1771,
"preview": "import { AccountId, Balance } from \"near-sdk-js\";\n\n/**\n * Provides token transfer resolve functionality.\n *\n * # Example"
},
{
"path": "packages/near-contract-standards/src/index.ts",
"chars": 313,
"preview": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \""
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/approval/approval_receiver.ts",
"chars": 1185,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Approval receiver is t"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/approval/index.ts",
"chars": 3951,
"preview": "import { AccountId, NearPromise } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\nimport { Option } from \"../uti"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/core/index.ts",
"chars": 5563,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { Token, TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n\n"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/core/receiver.ts",
"chars": 1263,
"preview": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Used when an NFT is tr"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/core/resolver.ts",
"chars": 2906,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Used when an NFT is transferred using "
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/enumeration/index.ts",
"chars": 1576,
"preview": "import { AccountId } from \"near-sdk-js\";\nimport { Token } from \"../token\";\n\n/** Offers methods helpful in determining ac"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/events.ts",
"chars": 4018,
"preview": "/** Standard for nep171 (Non-Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <ht"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/impl.ts",
"chars": 22555,
"preview": "import {\n AccountId,\n UnorderedMap,\n LookupMap,\n near,\n UnorderedSet,\n assert,\n NearPromise,\n bytes,\n serialize"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/index.ts",
"chars": 1048,
"preview": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. "
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/metadata.ts",
"chars": 4368,
"preview": "import { assert } from \"near-sdk-js\";\nimport { Option } from \"./utils\";\n\n/** This spec can be treated like a version of "
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/token.ts",
"chars": 862,
"preview": "import { TokenMetadata } from \"./metadata\";\nimport { AccountId } from \"near-sdk-js\";\n\n/** Note that token IDs for NFTs a"
},
{
"path": "packages/near-contract-standards/src/non_fungible_token/utils.ts",
"chars": 1680,
"preview": "import { near, assert, AccountId, bytes } from \"near-sdk-js\";\n\nexport function refund_storage_deposit(\n account_id: Acc"
},
{
"path": "packages/near-contract-standards/src/storage_management/index.ts",
"chars": 2618,
"preview": "import { AccountId, Balance } from \"near-sdk-js\"\nimport { Option } from \"../non_fungible_token/utils\";\n\nexport class Sto"
},
{
"path": "packages/near-contract-standards/src/util.ts",
"chars": 172,
"preview": "export const toSnakeCase = (str: string) => {\n return str.replace(/[A-Z]/g, (letter, index) => { return index == 0 ? le"
},
{
"path": "packages/near-contract-standards/tsconfig.json",
"chars": 693,
"preview": "{\n \"compilerOptions\": {\n \"esModuleInterop\": true,\n \"lib\": [\"es2015\", \"esnext\", \"dom\"],\n \"module\": \"esnext\",\n "
},
{
"path": "packages/near-sdk-js/.eslintrc.cjs",
"chars": 1058,
"preview": "/** @type {import('eslint').Linter.Config} */\nmodule.exports = {\n root: true,\n env: {\n es2021: true,\n node: true"
},
{
"path": "packages/near-sdk-js/.prettierignore",
"chars": 48,
"preview": "deps\nbuild\nnode_modules\nlib\ncli\npnpm-lock.yaml\n\n"
},
{
"path": "packages/near-sdk-js/README.md",
"chars": 25373,
"preview": "# NEAR JavaScript SDK\n\n## Quick Start\n\nUse [`create-near-app`](https://github.com/near/create-near-app) to quickly get s"
},
{
"path": "packages/near-sdk-js/builder/builder.c",
"chars": 47799,
"preview": "#include <string.h>\r\n#include \"../node_modules/near-sdk-js/lib/cli/deps/quickjs/quickjs-libc-min.h\"\r\n#include \"../node_m"
},
{
"path": "packages/near-sdk-js/lib/api.d.ts",
"chars": 18767,
"preview": "import { NearAmount, PromiseIndex } from \"./utils\";\nimport { GasWeight } from \"./types\";\n/**\n * Logs parameters in the N"
},
{
"path": "packages/near-sdk-js/lib/api.js",
"chars": 21455,
"preview": "import { assert, str, encode, decode, } from \"./utils\";\nimport { PromiseResult } from \"./types\";\nconst U64_MAX = 2n ** 6"
},
{
"path": "packages/near-sdk-js/lib/cli/abi.d.ts",
"chars": 159,
"preview": "import * as abi from \"near-abi\";\nexport declare function runAbiCompilerPlugin(tsFile: string, packageJsonPath: string, t"
},
{
"path": "packages/near-sdk-js/lib/cli/abi.js",
"chars": 11154,
"preview": "import ts from \"typescript\";\nimport JSON5 from 'json5';\nimport * as abi from \"near-abi\";\nimport * as TJS from \"near-type"
},
{
"path": "packages/near-sdk-js/lib/cli/build-tools/include-bytes.d.ts",
"chars": 98,
"preview": "import { Visitor } from \"@babel/traverse\";\nexport default function (): {\n visitor: Visitor;\n};\n"
},
{
"path": "packages/near-sdk-js/lib/cli/build-tools/include-bytes.js",
"chars": 2205,
"preview": "import * as t from \"@babel/types\";\nimport { readFileSync } from \"fs\";\nimport { join, dirname } from \"path\";\nconst assert"
},
{
"path": "packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.d.ts",
"chars": 98,
"preview": "import { Visitor } from \"@babel/traverse\";\nexport default function (): {\n visitor: Visitor;\n};\n"
},
{
"path": "packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js",
"chars": 11117,
"preview": "import * as t from \"@babel/types\";\nimport signal from \"signale\";\nconst { Signale } = signal;\n/**\n * A list of supported "
},
{
"path": "packages/near-sdk-js/lib/cli/cli.d.ts",
"chars": 866,
"preview": "#!/usr/bin/env node\nexport declare function validateCom(source: string, { verbose }: {\n verbose: boolean;\n}): Promise"
}
]
// ... and 148 more files (download for full content)
About this extraction
This page contains the full source code of the near/near-sdk-js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 348 files (997.0 KB), approximately 264.5k tokens, and a symbol index with 1714 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.