[
  {
    "path": ".gitattributes",
    "content": "pnpm-lock.yaml linguist-generated=true -diff\n/**/lib/**/*.js linguist-generated=true -diff\n/**/lib/**/*.d.ts linguist-generated=true -diff\nnear-contract-standards/lib/**/*.js linguist-generated=true -diff\nnear-contract-standards/lib/**/*.d.ts linguist-generated=true -diff\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug.yml",
    "content": "name: Bug Report\ndescription: Submit a bug report to help us improve\nlabels: [bug, 'status: needs triage']\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Before filing your issue, ask yourself:\n        - Is this clearly a NEAR JavaScript SDK defect?\n        - Do I have basic ideas about where it goes wrong? (For example, if there are stack traces, are they pointing to one file?)\n\n        **Please don't use issues for just questions**. For support please use [GitHub discussions](https://github.com/near/near-sdk-js/discussions).\n        \n        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.\n\n  - type: checkboxes\n    attributes:\n      label: Prerequisites\n      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.\n      options:\n        - label: I'm using the latest version of `near-sdk-js`.\n          required: true\n        - label: I have tried to start with a fresh project and reproduce the defect with minimal code changes.\n        - label: I have read the console error messages carefully (if applicable).\n\n  - type: textarea\n    attributes:\n      label: Description\n      description: A clear and concise description of what the bug is.\n    validations:\n      required: true\n\n  - type: input\n    attributes:\n      label: Reproducible demo\n      description: |\n        (Optional) Paste the link to an example repo.\n\n  - type: textarea\n    attributes:\n      label: Steps to reproduce\n      description: Write down the steps to reproduce the bug.\n      placeholder: |\n        1. Step 1...\n        2. Step 2...\n        3. Step 3...\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Expected behavior\n      description: |\n        How did you expect your project to behave? If you’re unsure, write down what you thought would happen.\n      placeholder: Write what you thought would happen.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Actual behavior\n      description: |\n        Did something go wrong? Is something broken, or not behaving as you expected?\n        Describe this section in detail. Please submit complete log messages with the stack traces.\n      placeholder: Write what happened with any error messages.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Your environment\n      description: Include as many relevant details about the environment you experienced the bug in.\n      value: |\n        - NEAR JavaScript SDK version used:\n        - Relevant dependencies (if applicable):\n\n  - type: checkboxes\n    attributes:\n      label: Self-service\n      description: |\n        If you feel like you could contribute to this issue, please check the box below.\n        If you do check this box, please send a pull request within 7 days so we can still delegate this to someone else.\n      options:\n        - label: I'd be willing to fix this bug myself.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: 🚀 Feature request & ❓ Questions\n    url: https://github.com/near/near-sdk-js/discussions\n    about: Use GitHub discussions for feature requests and questions.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature.yml",
    "content": "name: Feature design / RFC\ndescription: Submit a detailed feature request with a concrete proposal, including an exhaustive API design\nlabels: [ feature, 'status: needs triage' ]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Important things:\n\n        - This is for feature request including a real API design, not just a basic idea.\n        - The design does not have to be perfect, we'll discuss it if needed.\n        - For a more \"casual\" feature request, consider using GitHub Discussions instead: https://github.com/near/near-sdk-js/discussions/categories/ideas\n\n\n  - type: checkboxes\n    attributes:\n      label: Have you read the Contributing Guidelines?\n      options:\n        - label: I have read the [Contributing Guidelines on issues](https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md).\n          required: true\n\n  - type: textarea\n    attributes:\n      label: Description\n      description: A clear and concise description of what the feature is.\n    validations:\n      required: true\n\n  - type: input\n    attributes:\n      label: Has this been requested on GitHub Discussions?\n      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.\n\n  - type: textarea\n    attributes:\n      label: Motivation\n      description: Please outline the motivation for the proposal and why it should be implemented.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: API design\n      description: |\n        Please describe how users will use this feature.\n        \n        Please explain in an exhaustive way what are the config options and their respective effects.\n        \n        > **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\n\n\n  - type: checkboxes\n    attributes:\n      label: Self-service\n      description: |\n        If you feel like you could contribute to this issue, please check the box below.\n        If you do check this box, please send a pull request within 7 days so we can still delegate this to someone else.\n        \n        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.\n      options:\n        - label: I'd be willing to contribute and develop this feature myself.\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "<!--\nThank you for sending the PR! We appreciate you spending the time to work on these changes.\nYou can learn more about contributing to NEAR JavaScript SDK here: https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md\nHappy contributing!\n-->\n\n## Pre-flight checklist\n\n- [ ] I have read the [Contributing Guidelines on pull requests](https://github.com/near/near-sdk-js/blob/master/CONTRIBUTING.md).\n- [ ] Commit messages follow the [conventional commits](https://www.conventionalcommits.org/) spec\n- [ ] **If this is a code change**: I have written unit tests.\n- [ ] **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.\n\n## Motivation\n\n<!-- Help us understand your motivation by explaining why you decided to make this change. Does this fix a bug? Does it close an issue? -->\n\n## Test Plan\n\n<!-- Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. -->\n\n## Related issues/PRs\n\n<!-- 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. -->\n"
  },
  {
    "path": ".github/workflows/add-to-devtools.yml",
    "content": "name: 'Add to DevTools Project'\n\non:\n  issues:\n    types:\n      - opened\n      - reopened\n  pull_request_target:\n    types:\n      - opened\n      - reopened\n\njobs:\n  add-to-project:\n    name: Add issue/PR to project\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/add-to-project@v1.0.0\n        with:\n          # add to DevTools Project #156\n          project-url: https://github.com/orgs/near/projects/156\n          github-token: ${{ secrets.PROJECT_GH_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/tests.yml",
    "content": "name: Test\non:\n  pull_request:\n  push:\n    branches:\n      - master\n      - develop\njobs:\n  tests:\n    strategy:\n      matrix:\n        platform: [ubuntu-latest, macos-latest]\n    runs-on: ${{ matrix.platform }}\n    steps:\n      - uses: actions/checkout@v3\n      - name: Setup pnpm\n        uses: pnpm/action-setup@v4\n        with:\n          version: 9\n      - name: Setup Node\n        uses: actions/setup-node@v3\n        with:\n          node-version: 18.x\n          cache: pnpm\n      - name: Install dependencies\n        run: pnpm install\n      - name: Lint code\n        run: pnpm lint\n      - name: Format code\n        run: pnpm format\n      - name: Run git status\n        run: git status\n      - name: Check that lints where commited\n        run: test -z \"$(git status --porcelain)\"\n      - name: Build\n        run: pnpm build\n      - name: Check that all build artifacts where commited\n        run: test -z \"$(git status --porcelain)\"\n      - name: Run tests\n        run: export NEAR_WORKSPACES_DEBUG=true && pnpm test\n"
  },
  {
    "path": ".github/workflows/typedoc-generate-gitbook-docs.yml",
    "content": "name: Deploy TypeDoc to GitBook\n\non:\n  push:\n    branches:\n      - develop\n  \nenv:\n  NODE_VERSION: 18.x\n  ENTRY_FILE: \"packages\"\n  CONFIG_PATH: \"tsconfig.base.json\"\n  USES_PNPM: \"true\"\n  \njobs:\n  deploy:\n    concurrency: ci-${{ github.ref }}\n    runs-on: ubuntu-latest\n    if: \"!contains(github.event.head_commit.message, '[skip ci]')\"\n    permissions:\n      contents: write\n    steps:\n      - uses: actions/checkout@v4\n  \n      - uses: actions/setup-node@v3\n        with:\n          node-version: ${{ env.NODE_VERSION }}\n  \n      - name: Setup pnpm\n        uses: pnpm/action-setup@v4\n        with:\n          version: 9\n  \n      - name: Install dependencies\n        run: pnpm install --no-frozen-lockfile\n    \n      - name: Build project\n        run: pnpm build\n    \n      - name: Build documentation\n        run: pnpm docs:generate-markdown\n    \n      - name: Deploy to GitBook\n        run: |\n          git clone --branch=git-book https://frol:${{ secrets.MY_GITHUB_TOKEN }}@github.com/near/near-sdk-js.git book\n          rsync -av --delete --exclude=.git markdown-docs/ book/\n          cd book\n          git config user.name \"GitHub Actions\"\n          git config user.email \"actions@github.com\"\n          git add .\n          git commit -m \"Update documentation [skip ci]\"\n          git push https://frol:${{ secrets.MY_GITHUB_TOKEN }}@github.com/near/near-sdk-js.git git-book\n"
  },
  {
    "path": ".github/workflows/typedoc-generator.yml",
    "content": "name: Deploy TypeDoc on GitHub pages\n\non:\n    push:\n      branches:\n        develop  \n\nenv:\n  NODE_VERSION: 18.x\n  ENTRY_FILE: 'packages'\n  CONFIG_PATH: 'tsconfig.base.json'\n  USES_PNPM: 'true'\n  \njobs:\n  deploy:\n    concurrency: ci-${{ github.ref }}\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    steps:\n      - uses: actions/checkout@v4\n\n      - uses: actions/setup-node@v3\n        with:\n          node-version: ${{ env.NODE_VERSION }}\n\n      - name: Setup pnpm\n        uses: pnpm/action-setup@v4\n        with:\n          version: 7\n\n      - name: Install dependencies\n        run: pnpm install --no-frozen-lockfile\n\n      - name: Build project\n        run:  pnpm build\n\n      - name: Build documentation\n        run:  pnpm docs:generate\n\n      - name: Deploy to GitHub pages\n        uses: JamesIves/github-pages-deploy-action@v4\n        with:\n          token: ${{ secrets.GITHUB_TOKEN }}\n          branch: gh-pages\n          folder: docs\n          clean: true"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\nvendor\n.idea\ndeps\n.turbo\nyarn.lock\npackage-lock.json"
  },
  {
    "path": ".npmrc",
    "content": "save-exact=true"
  },
  {
    "path": "AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md",
    "content": "# JSON Schemas for Automatic Decoding of the State\n\nA 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.\n\nThis doc explains a new solution currently implemented in the SDK and how to use it to simplify hanlding stored Classes and Nested Structures.\n\n## The Problem\nNEAR 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`.\n\nSince 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:\n\n```typescript\nClass Car {\n    name: string;\n    speed: number;\n    \n    run() {\n      // ...\n    }\n}\n```\n\nA particular instance of that Car (e.g. new Car(\"Audi\", 200)) will be stored in the contract as the JSON string:\n\n```json\n{\"name\": \"Audi\", \"speed\": 200}\n```\n\nNext 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:\n\n```js\n// the SDK parses the String into an Object\nthis.car.run() # This will fail!\n```\n\nThis problem is particularly painful when the class is nested in another Class, e.g. a `LookupMap` of `Cars`.\n\n## The (non-elegant) Solution\nBefore, the SDK mitigated this problem by requiring the user to manually reconstruct the JS `Object` to an instance of the original class.\n\n## A More Elegant Solution: JSON Schemas\nTo 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:\n\n```ts\nClass Car {\n    // Schema to (de)serialize\n    static schema = {\n        name: \"string\",\n        speed: \"number\",\n    };\n\n    // Properties\n    name: string;\n    speed: number;\n\n    // methods\n    run() {\n      // ...\n    }\n}\n```\n\nIf 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:\n\n```js\n// the SDK iteratively reconstructs the Car\nthis.car.run() # This now works!\n```\n\n## The schema format\nThe Schema supports multiple types: \n\n* Primitive types: `string`, `number`, `boolean`. We can remove schema format of `Primitive types` since is no need to reconstruct them.\n* Built-in object types: `Date`, `BigInt`.\n* Built-in collections: `array`, `map`\n  * 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.\n  * 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.\n* Custom classes are denoted by their name, e.g. `Car`\n* 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`.\n\nYou can see a complete example in the [status-deserialize-class](./examples/src/status-deserialize-class.js) file, which contains the following Class declaration:\n\n```js\nexport class StatusDeserializeClass {\n  static schema = {\n    truck: Truck,\n    efficient_recordes: UnorderedMap,\n    nested_efficient_recordes: {class: UnorderedMap, value: UnorderedMap},\n    nested_lookup_recordes:  {class: UnorderedMap, value: LookupMap},\n    vector_nested_group: {class: Vector, value: LookupMap},\n    lookup_nest_vec: { class: LookupMap, value: Vector },\n    unordered_set: UnorderedSet,\n    user_car_map: {class: UnorderedMap, value: Car },\n    big_num: 'bigint',\n    date: 'date'\n  };\n\n  constructor() {\n    this.is_inited = false;\n    this.records = {};\n    this.truck = new Truck();\n    this.messages = [];\n    this.efficient_recordes = new UnorderedMap(\"a\");\n    this.nested_efficient_recordes = new UnorderedMap(\"b\");\n    this.nested_lookup_recordes = new UnorderedMap(\"c\");\n    this.vector_nested_group = new Vector(\"d\");\n    this.lookup_nest_vec = new LookupMap(\"e\");\n    this.unordered_set = new UnorderedSet(\"f\");\n    this.user_car_map = new UnorderedMap(\"g\");\n    this.big_num = 1n;\n    this.date = new Date();\n    this.message_without_schema_defined = \"\";\n    this.number_without_schema_defined = 0;\n    this.records_without_schema_defined = {};\n  }\n    // other methods\n}\n```\n\n---\n\n#### What happens with the old `reconstructor`?\nUntil now, users needed to call a `reconstructor` method in order for **Nested Collections** to be properly decoded: \n\n```typescript\n@NearBindgen({})\nexport class Contract {\n    outerMap: UnorderedMap<UnorderedMap<string>>;\n\n    constructor() {\n        this.outerMap = new UnorderedMap(\"o\");\n    }\n\n    @view({})\n    get({id, accountId}: { id: string; accountId: string }) {\n        const innerMap = this.outerMap.get(id, {\n            reconstructor: UnorderedMap.reconstruct,  // we need to announce reconstructor explicit\n        });\n        if (innerMap === null) {\n            return null;\n        }\n        return innerMap.get(accountId);\n    }\n}\n```\n\nWith schemas, this is no longer needed, as the SDK can correctly infer how to decode the Nested Collections:\n\n```typescript\n@NearBindgen({})\nexport class Contract {\n    static schema = {\n      outerMap: {class: UnorderedMap, value: UnorderedMap}\n    };\n    \n    outerMap: UnorderedMap<UnorderedMap<string>>;\n\n    constructor() {\n        this.outerMap = new UnorderedMap(\"o\");\n    }\n\n    @view({})\n    get({id, accountId}: { id: string; accountId: string }) {\n        const innerMap = this.outerMap.get(id);  // reconstructor can be infered from static schema\n        if (innerMap === null) {\n            return null;\n        }\n        return innerMap.get(accountId);\n    }\n}\n```\n\n---\n\n#### How Does the Reconstruction Work?\nThe `_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`:\n\n```typescript\n  static _reconstruct(classObject: object, plainObject: AnyObject): object {\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    if (classObject.constructor.schema === undefined) {\n      for (const item in classObject) {\n        const reconstructor = classObject[item].constructor?.reconstruct;\n  \n        classObject[item] = reconstructor\n                ? reconstructor(plainObject[item])\n                : plainObject[item];\n      }\n  \n      return classObject;\n    }\n  \n    return decodeObj2class(classObject, plainObject);\n  }\n```\n\n"
  },
  {
    "path": "CODEOWNERS",
    "content": "* @ailisp @volovyks\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n- Using welcoming and inclusive language\n- Being respectful of differing viewpoints and experiences\n- Gracefully accepting constructive criticism\n- Focusing on what is best for the community\n- Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n- The use of sexualized language or imagery and unwelcome sexual attention or\n  advances\n- Trolling, insulting/derogatory comments, and personal or political attacks\n- Public or private harassment\n- Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n- Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at social@nearprotocol.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Near JavaScript SDK\n\nFirst off, thanks for taking the time to contribute! We look forward to to your contributions. 🎉\n\nAll 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.\n\nWe 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.\n\n> 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:\n> - Star the project\n> - Tweet about it\n> - Refer this project in your project's readme\n> - Mention the project at local meetups and tell your friends/colleagues\n\n## Table of Contents\n\n- [I Have a Question](#i-have-a-question)\n- [Get Involved](#get-involved)\n- [Our Development Process](#our-development-process)\n- [Development](#development)\n  - [Pull Requests](#pull-requests)\n  - [Tests](#tests)\n  - [What Happens Next?](#what-happens-next)\n\n## I Have a Question\n\nIf you want to ask a question please use the following resources available for you:\n\n- [Docs site](https://docs.near.org/sdk/js/introduction)\n- Post a question on [GitHub Discussions](https://github.com/near/near-sdk-js/discussions)\n- Post a question on [StackOverflow with `[nearprotocol]` tag](https://stackoverflow.com/questions/tagged/nearprotocol)\n\n\n## Get Involved\n\nThere 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:\n\n- 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).\n- Look through the [open issues](https://github.com/near/near-sdk-js/issues). Provide workarounds or ask for clarification.\n- 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.\n- 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.\n\nIf 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.\n\n### Join our Discord Channel\n\nWe 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.\n\n### Join our Telegram User Group\nYou can have near-sdk-js related discussions with other users, contributors and maintainers on [Telegram]( https://t.me/near_sdk_js).\n\n### Triaging Issues and Pull Requests\n\nOne great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.\n\nYou can review code, or ask for more information if you believe the issue does not provide all the details required to solve it.\n\n## Our Development Process\n\nOur 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.\n\n**Branch organization**: This project has one primary branch `develop` and we use feature branches to deliver new features with pull requests.\n\n**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.\n\n**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.\n\n**Security Bugs**: To report security issues in this project please email [security@near.org](mailto:security@near.org)\n\n**New features and enhancements**:\n\nIf 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).\n\nIf 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). \n\n### Claiming issues\n \nWe 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.\n\nApart from the `good first issue`, the following labels are also worth looking at:\n\n- [`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.\n- [`accepting pr`](https://github.com/near/near-sdk-js/labels/status%3A%20accepting%20pr): community contributors can feel free to claim any of these.\n\nIf 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.\n\n## Development\n\n### Online one-click setup for contributing\n\nYou can use Gitpod (a free, online, VSCode-like IDE) for contributing. With a single click, it will launch a workspace and automatically:\n\n- clone the repo.\n- install the dependencies.\n\nSo that you can start contributing straight away.\n\n[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near/near-sdk-js)\n\n## Pull Requests\n\nWe appreciate the time and effort you invested! 🙏 We will do our best to work with you and get the PR looked at.\n\n> Working on your first-ever Pull Request? You can learn how from this free video series:\n> [**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)\n\nPlease make sure the following is done when submitting a pull request:\n\n1. **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.\n2. **Use descriptive titles.** It is recommended to follow semantic commit conventions: https://www.conventionalcommits.org/en/v1.0.0/\n3. **Test your changes.** Include unit tests for any public API you touch.\n\nAll pull requests should be opened against the `develop` branch.\n\n### Tests\n\nPlease include unit tests for any public api you add or touch. We use [AVA](https://github.com/avajs/ava) for tests.\n\n### What Happens Next?\n\nOur team will be monitoring pull requests. Do help us by keeping pull requests consistent by following the guidelines above.\n"
  },
  {
    "path": "LICENSE",
    "content": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "README.md",
    "content": "# NEAR JavaScript SDK\n\n<p>\n  <a href=\"https://docs.near.org/tools/sdk\" target=\"_blank\">\n    <img alt=\"Documentation\" src=\"https://img.shields.io/badge/documentation-JS/TS-brightgreen.svg\" />\n  </a>\n  <a href=\"https://www.npmjs.com/package/near-sdk-js\" target=\"_blank\">\n    <img alt=\"Version\" src=\"https://img.shields.io/npm/v/near-sdk-js.svg\">\n  </a>\n  <img src=\"https://img.shields.io/badge/node-%3E%3D14%20%3C16.6.0%20%7C%7C%20%3E16.6.0-blue.svg\" />\n  <a href=\"https://github.com/near/near-sdk-js/blob/develop/LICENSE\" target=\"_blank\">\n    <img alt=\"License: LICENSE\" src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" />\n  </a>\n  <a href=\"https://github.com/near/near-sdk-js/blob/develop/LICENSE-APACHE\" target=\"_blank\">\n    <img alt=\"License: LICENSE\" src=\"https://img.shields.io/badge/License-Apache-yellow.svg\" />\n  </a>\n</p>\n\nA JavaScript library for writing NEAR smart contracts.\n\n```typescript\nimport { NearBindgen, near, call, view } from 'near-sdk-js';\n\n@NearBindgen({})\nclass HelloNear {\n  greeting: string = 'Hello';\n\n  @view({}) // This method is read-only and can be called for free\n  get_greeting(): string {\n    return this.greeting;\n  }\n\n  @call({}) // This method changes the state, for which it cost gas\n  set_greeting({ greeting }: { greeting: string }): void {\n    near.log(`Saving greeting ${greeting}`);\n    this.greeting = greeting;\n  }\n}\n```\n\nSee more in the [Anatomy of a Contract](https://docs.near.org/build/smart-contracts/anatomy/).\n\n## Documentation\n\n- [Learn how to use](https://github.com/near/create-near-app/tree/master/templates/contracts/ts)\n- [Learn by example with AgorApp](https://agorapp.dev/catalog/all?difficulty=&chains=near)\n- [Learn by example with NEAR Docs](https://docs.near.org/build/smart-contracts/quickstart)\n- Check our [detailed examples and tutorials](https://docs.near.org/tutorials/welcome)\n- Find [source code examples](https://github.com/near/near-sdk-js/tree/develop/examples) with common use cases\n- Lookup available features in [API reference](https://near.github.io/near-sdk-js/)\n- 🏠 Learn more about NEAR on our [Documentation website](https://docs.near.org/)\n- 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)\n\n## Prerequisites\n\n- node >=14 <16.6.0 || >16.6.0\n- pnpm >=7\n\n## Quick Start\n\nUse [`create-near-app`](https://github.com/near/create-near-app) to quickly get started writing smart contracts in JavaScript on NEAR.\n\n    npx create-near-app\n\nThis will scaffold a basic template for you 😎\n\n## Contributing\n\nIf you are interested in contributing, please look at the [contributing guidelines](https://github.com/near/near-sdk-js/tree/develop/CONTRIBUTING.md).\n\n - [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞\n - [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡\n - [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪\n\n## License\n\nThis 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).\nSee [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.\n"
  },
  {
    "path": "RELEASE.md",
    "content": "# Release\n\nThis document describes step to do a new pre-release or formal release.\n\n## Release Requirement\n- A formal release must be directly bump from a tested, DevRel Team approved pre-release, with no commits other than bump the version.\n- 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.\n\n## Steps for pre-release\n1. Create a new branch for the release.\n2. 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.\n3. Run `pnpm publish` in packages/near-sdk-js and in packages/near-contract-standards.\n4. Copy examples folder in this repo to another place, drop `node_modules`, change its package.json from:\n```\n    \"near-contract-standards\": \"workspace:*\",\n    \"near-sdk-js\": \"workspace:*\",\n```\nto the version you just released, e.g. `x.y.z-1`.\n5. Build and run example tests to ensure the packaging is correct.\n6. 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.\n7. Ask the DevRel team to test the pre-release.\n\n## Steps for formal release\n1. Create a new release branch from the candidate pre-release branch\n2. 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`.\n3. Run `pnpm publish` in packages/near-sdk-js and in packages/near-contract-standards.\n4. 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.\n5. Advertise it to the community!"
  },
  {
    "path": "RUNTIME_INVESTIGATE.md",
    "content": "# Runtime Investigate\nInvestigate 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)\n## Table of Contents\n- [quickjs](#quickjs)\n- [hermes](#hermes)\n- [wasmnizer-ts](#wasmnizer-ts)\n### quickjs\n:white_check_mark: Currently our near-sdk-js use [quickjs engine](https://bellard.org/quickjs/) to compile js->C/C++->wasm.\n### hermes\n: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.\n### wasmnizer-ts\n: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."
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Reporting a Vulnerability\n\nTo report security issues in this project please send an email to [security@near.org](mailto:security@near.org)\n"
  },
  {
    "path": "TOOLING.md",
    "content": "# Tooling\n\nThis document describes at a high level some the key tools used across `near-js`.\n\n## Package Manager - [PNPM](https://pnpm.io/)\n\nPNPM 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`.\n\n## Build System - [Turborepo](https://turborepo.org/)\nTurborepo 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.\n\n## Automation - [GitHub Actions](https://github.com/features/actions)\n\nGithub Actions is used to automate various tasks including PR checks (linting, type checks, and tests).\n"
  },
  {
    "path": "benchmark/.gitignore",
    "content": "build"
  },
  {
    "path": "benchmark/README.md",
    "content": "# Gas and size benchmark compare to NEAR-SDK-RS\n\n## Summary\n\nNEAR-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).\n\nThis results in:\n\n- Size of a minimal contract is 500K, which is also the size of the bytecode VM.\n- 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.\n- For contract that bottlenecks at calling the host functions are using similar gas in JS and Rust.\n- For contract that does a lot of computation in JS, the JS bytecode uses significantly more gas.\n- 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.\n- 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.\n\n## Detailed gas benchmark\n\n### A minimal contract\n\n- RS lowlevel minimal contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 2.43T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.00005T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 5.08T\n- JS lowlevel minimal contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 7.07T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11132T\n  -      WASM_INSTRUCTION :  4.53T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 9.72T\n\nIn 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.\n\n### A highlevel minimal contract (using nearbindgen)\n\n- highlevel-minimal.ava › RS highlevel minimal contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 2.63T\n  -      BASE :  0.79G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  35.46G\n  -      READ_CACHED_TRIE_NODE :  4.56G\n  -      READ_MEMORY_BASE :  7.83G\n  -      READ_MEMORY_BYTE :  0.04G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      TOUCHING_TRIE_NODE :  32.2G\n  -      WASM_INSTRUCTION :  0.46G\n  -      WRITE_MEMORY_BASE :  2.8G\n  -      WRITE_MEMORY_BYTE :  0.04G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 5.28T\n- highlevel-minimal.ava › JS highlevel minimal contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 8.39T\n  -      BASE :  1.59G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  112.03G\n  -      READ_CACHED_TRIE_NODE :  6.84G\n  -      READ_MEMORY_BASE :  7.83G\n  -      READ_MEMORY_BYTE :  0.05G\n  -      READ_REGISTER_BASE :  2.52G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      STORAGE_WRITE_VALUE_BYTE :  0.06G\n  -      TOUCHING_TRIE_NODE :  48.31G\n  -      WASM_INSTRUCTION :  5.66T\n  -      WRITE_MEMORY_BASE :  5.61G\n  -      WRITE_MEMORY_BYTE :  0.05G\n  -      WRITE_REGISTER_BASE :  2.87G\n  -      WRITE_REGISTER_BYTE :  0.01G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 11.05T\n\nJS `@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.\n\n### Low level API\n\n- RS lowlevel API contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 2.53T\n  -      BASE :  0.00026T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.00008T\n  -      READ_MEMORY_BASE :  0.00522T\n  -      READ_MEMORY_BYTE :  0.00008T\n  -      STORAGE_WRITE_BASE :  0.0642T\n  -      STORAGE_WRITE_KEY_BYTE :  0.0007T\n  -      STORAGE_WRITE_VALUE_BYTE :  0.00031T\n  -      TOUCHING_TRIE_NODE :  0.0322T\n  -      WASM_INSTRUCTION :  0.00002T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 5.18T\n- JS lowlevel API contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 7.8T\n  -      BASE :  0.00026T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11119T\n  -      READ_MEMORY_BASE :  0.00522T\n  -      READ_MEMORY_BYTE :  0.00008T\n  -      STORAGE_WRITE_BASE :  0.0642T\n  -      STORAGE_WRITE_EVICTED_BYTE :  0.00032T\n  -      STORAGE_WRITE_KEY_BYTE :  0.0007T\n  -      STORAGE_WRITE_VALUE_BYTE :  0.00031T\n  -      TOUCHING_TRIE_NODE :  0.09661T\n  -      WASM_INSTRUCTION :  5.09T\n  -      WRITE_REGISTER_BASE :  0.00287T\n  -      WRITE_REGISTER_BYTE :  0.00004T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 10.45T\n- JS lowlevel API contract, call many\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 8.47T\n  -      BASE :  0.00265T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11119T\n  -      READ_MEMORY_BASE :  0.0522T\n  -      READ_MEMORY_BYTE :  0.00076T\n  -      STORAGE_WRITE_BASE :  0.64197T\n  -      STORAGE_WRITE_EVICTED_BYTE :  0.00289T\n  -      STORAGE_WRITE_KEY_BYTE :  0.00705T\n  -      STORAGE_WRITE_VALUE_BYTE :  0.0031T\n  -      TOUCHING_TRIE_NODE :  0.04831T\n  -      WASM_INSTRUCTION :  5.14T\n  -      WRITE_REGISTER_BASE :  0.02579T\n  -      WRITE_REGISTER_BYTE :  0.00034T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 11.12T\n\nIn 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).\n\n### Highlevel collection\n\n- RS highlevel collection contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 3.32T\n  -      BASE :  3.18G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  70.94G\n  -      READ_CACHED_TRIE_NODE :  95.76G\n  -      READ_MEMORY_BASE :  26.1G\n  -      READ_MEMORY_BYTE :  1.87G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0.03G\n  -      STORAGE_READ_BASE :  112.71G\n  -      STORAGE_READ_KEY_BYTE :  3.44G\n  -      STORAGE_READ_VALUE_BYTE :  0.19G\n  -      STORAGE_WRITE_BASE :  256.79G\n  -      STORAGE_WRITE_EVICTED_BYTE :  1.09G\n  -      STORAGE_WRITE_KEY_BYTE :  9.23G\n  -      STORAGE_WRITE_VALUE_BYTE :  7.75G\n  -      TOUCHING_TRIE_NODE :  257.63G\n  -      WASM_INSTRUCTION :  16.36G\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.74G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  1.1G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 5.97T\n- JS highlevel collection contract\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 10.06T\n  -      BASE :  2.91G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  113.46G\n  -      READ_CACHED_TRIE_NODE :  72.96G\n  -      READ_MEMORY_BASE :  20.88G\n  -      READ_MEMORY_BYTE :  2G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0.03G\n  -      STORAGE_READ_BASE :  112.71G\n  -      STORAGE_READ_KEY_BYTE :  3.31G\n  -      STORAGE_READ_VALUE_BYTE :  0.53G\n  -      STORAGE_WRITE_BASE :  192.59G\n  -      STORAGE_WRITE_EVICTED_BYTE :  3.02G\n  -      STORAGE_WRITE_KEY_BYTE :  7.96G\n  -      STORAGE_WRITE_VALUE_BYTE :  9.49G\n  -      TOUCHING_TRIE_NODE :  209.33G\n  -      WASM_INSTRUCTION :  6.86T\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.9G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  1.55G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 12.71T\n\nJS 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` ).\n\n### Computational expensive contract\n\n- JS expensive contract, iterate 20000 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 123.26T\n  -      BASE :  1.85G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  112.09G\n  -      READ_CACHED_TRIE_NODE :  4.56G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.07G\n  -      READ_REGISTER_BASE :  2.52G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      STORAGE_WRITE_VALUE_BYTE :  0.06G\n  -      TOUCHING_TRIE_NODE :  32.2G\n  -      WASM_INSTRUCTION :  120.54T\n  -      WRITE_MEMORY_BASE :  5.61G\n  -      WRITE_MEMORY_BYTE :  0.07G\n  -      WRITE_REGISTER_BASE :  2.87G\n  -      WRITE_REGISTER_BYTE :  0.04G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 125.91T\n- RS expensive contract. iterate 20000 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 3.01T\n  -      BASE :  1.85G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  67.77G\n  -      READ_CACHED_TRIE_NODE :  6.84G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.06G\n  -      READ_REGISTER_BASE :  2.52G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      TOUCHING_TRIE_NODE :  48.31G\n  -      WASM_INSTRUCTION :  315.17G\n  -      WRITE_MEMORY_BASE :  5.61G\n  -      WRITE_MEMORY_BYTE :  0.07G\n  -      WRITE_REGISTER_BASE :  2.87G\n  -      WRITE_REGISTER_BYTE :  0.04G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 5.66T\n- RS expensive contract. iterate 10000 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 2.9T\n  -      BASE :  2.38G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  67.77G\n  -      READ_CACHED_TRIE_NODE :  13.68G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.06G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      TOUCHING_TRIE_NODE :  80.51G\n  -      WASM_INSTRUCTION :  158.89G\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.07G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  0.04G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 5.56T\n- RS expensive contract. iterate 100 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 2.75T\n  -      BASE :  2.38G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  67.77G\n  -      READ_CACHED_TRIE_NODE :  13.68G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.05G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      TOUCHING_TRIE_NODE :  80.51G\n  -      WASM_INSTRUCTION :  4.02G\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.07G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  0.03G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 5.4T\n- JS expensive contract, iterate 100 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 9.09T\n  -      BASE :  2.38G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  112.09G\n  -      READ_CACHED_TRIE_NODE :  13.68G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.06G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_READ_VALUE_BYTE :  0.01G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_EVICTED_BYTE :  0.06G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      STORAGE_WRITE_VALUE_BYTE :  0.06G\n  -      TOUCHING_TRIE_NODE :  80.51G\n  -      WASM_INSTRUCTION :  6.3T\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.07G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  0.05G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 11.75T\n- JS expensive contract, iterate 10000 times\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 65.94T\n  -      BASE :  2.38G\n  -      CONTRACT_LOADING_BASE :  0.04G\n  -      CONTRACT_LOADING_BYTES :  112.09G\n  -      READ_CACHED_TRIE_NODE :  13.68G\n  -      READ_MEMORY_BASE :  10.44G\n  -      READ_MEMORY_BYTE :  0.06G\n  -      READ_REGISTER_BASE :  5.03G\n  -      READ_REGISTER_BYTE :  0G\n  -      STORAGE_READ_BASE :  56.36G\n  -      STORAGE_READ_KEY_BYTE :  0.15G\n  -      STORAGE_READ_VALUE_BYTE :  0.01G\n  -      STORAGE_WRITE_BASE :  64.2G\n  -      STORAGE_WRITE_EVICTED_BYTE :  0.06G\n  -      STORAGE_WRITE_KEY_BYTE :  0.35G\n  -      STORAGE_WRITE_VALUE_BYTE :  0.06G\n  -      TOUCHING_TRIE_NODE :  80.51G\n  -      WASM_INSTRUCTION :  63.15T\n  -      WRITE_MEMORY_BASE :  8.41G\n  -      WRITE_MEMORY_BYTE :  0.08G\n  -      WRITE_REGISTER_BASE :  8.6G\n  -      WRITE_REGISTER_BYTE :  0.06G\n  - Gas used to refund unused gas: 223.18G\n  - Total gas used: 68.59T\n\nIn 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.\n\n### Deploy and cross contract call\n\n- JS promise batch deploy contract and call\n\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 25.86T\n  -      CREATE_ACCOUNT :  0.09961T\n  -      DEPLOY_CONTRACT :  3.71T\n  -      FUNCTION_CALL :  2.32T\n  -      NEW_RECEIPT :  0.10806T\n  -      TRANSFER :  0.11512T\n  -      BASE :  0.00159T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.22386T\n  -      PROMISE_RETURN :  0.00056T\n  -      READ_MEMORY_BASE :  0.01566T\n  -      READ_MEMORY_BYTE :  1.97T\n  -      UTF8_DECODING_BASE :  0.00311T\n  -      UTF8_DECODING_BYTE :  0.00525T\n  -      WASM_INSTRUCTION :  14.86T\n  - Gas used to execute the cross contract call: 41.9T\n  -      BASE :  0.00344T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11228T\n  -      READ_MEMORY_BASE :  0.00261T\n  -      READ_MEMORY_BYTE :  0.0005T\n  -      READ_REGISTER_BASE :  0.01007T\n  -      READ_REGISTER_BYTE :  0T\n  -      WASM_INSTRUCTION :  5.47T\n  -      WRITE_MEMORY_BASE :  0.01122T\n  -      WRITE_MEMORY_BYTE :  0.00014T\n  -      WRITE_REGISTER_BASE :  0.01146T\n  -      WRITE_REGISTER_BYTE :  0.00019T\n  - Gas used to refund unused gas for cross contract call: 0.22318T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 70.63T\n\n- RS promise batch deploy contract and call\n  - Gas used to convert transaction to receipt: 2.43T\n  - Gas used to execute the receipt (actual contract call): 10.89T\n  -      CREATE_ACCOUNT :  0.09961T\n  -      DEPLOY_CONTRACT :  3.71T\n  -      FUNCTION_CALL :  2.32T\n  -      NEW_RECEIPT :  0.10806T\n  -      TRANSFER :  0.11512T\n  -      BASE :  0.00159T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11283T\n  -      PROMISE_RETURN :  0.00056T\n  -      READ_MEMORY_BASE :  0.01566T\n  -      READ_MEMORY_BYTE :  1.97T\n  -      UTF8_DECODING_BASE :  0.00311T\n  -      UTF8_DECODING_BYTE :  0.00525T\n  -      WASM_INSTRUCTION :  0.00038T\n  - Gas used to execute the cross contract call: 41.9T\n  -      BASE :  0.00344T\n  -      CONTRACT_LOADING_BASE :  0.00004T\n  -      CONTRACT_LOADING_BYTES :  0.11228T\n  -      READ_MEMORY_BASE :  0.00261T\n  -      READ_MEMORY_BYTE :  0.0005T\n  -      READ_REGISTER_BASE :  0.01007T\n  -      READ_REGISTER_BYTE :  0T\n  -      WASM_INSTRUCTION :  5.47T\n  -      WRITE_MEMORY_BASE :  0.01122T\n  -      WRITE_MEMORY_BYTE :  0.00014T\n  -      WRITE_REGISTER_BASE :  0.01146T\n  -      WRITE_REGISTER_BYTE :  0.00019T\n  - Gas used to refund unused gas for cross contract call: 0.22318T\n  - Gas used to refund unused gas: 0.22318T\n  - Total gas used: 55.67T\n\nIn 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.\n\n## Tips to do your own benchmark\n\nIf 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.\n\nYou 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.\n\nTo 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.\n\n## Details of size benchmark\n\n### JS Contract\n\n```\n\n-rwxrwxr-x 1 bo bo 1009K Feb  9 10:49 ./build/deploy-contract.wasm\n-rwxrwxr-x 1 bo bo  506K Feb  8 12:11 ./build/expensive-calc.wasm\n-rwxrwxr-x 1 bo bo  512K Feb  7 15:57 ./build/highlevel-collection.wasm\n-rwxrwxr-x 1 bo bo  505K Feb  7 10:53 ./build/highlevel-minimal.wasm\n-rwxrwxr-x 1 bo bo  502K Feb 10 11:32 ./build/lowlevel-api.wasm\n-rwxrwxr-x 1 bo bo  502K Feb 10 11:47 ./build/lowlevel-minimal.wasm\n```\n\n### Rust Contract\n\n```\n-rwxrwxr-x 1 bo bo  509K Feb 10 10:02 ./res/deploy_contract.wasm\n-rwxrwxr-x 1 bo bo  306K Feb  8 12:18 ./res/expensive_calc.wasm\n-rwxrwxr-x 1 bo bo  320K Feb  8 11:26 ./res/highlevel_collection.wasm\n-rwxrwxr-x 1 bo bo  160K Feb  7 10:51 ./res/highlevel_minimal.wasm\n-rwxrwxr-x 1 bo bo   387 Feb  7 11:56 ./res/lowlevel_api.wasm\n-rwxrwxr-x 1 bo bo   219 Feb  7 10:33 ./res/lowlevel_minimal.wasm\n```\n\n## Appendix\n\n- Source code of the rust benchmark: https://github.com/near/sdk-rs-gas-benchmark\n"
  },
  {
    "path": "benchmark/__tests__/test-collections-performance.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logTotalGas, randomInt } from \"./util.js\";\n\nconst COLLECTION_SIZE = 20;\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contracts.\n  const lookupMapContract = await root.devDeploy(\"build/lookup-map.wasm\");\n  const lookupSetContract = await root.devDeploy(\"build/lookup-set.wasm\");\n  const unorderedMapContract = await root.devDeploy(\"build/unordered-map.wasm\");\n  const unorderedSetContract = await root.devDeploy(\"build/unordered-set.wasm\");\n  const vectorContract = await root.devDeploy(\"build/vector.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    lookupMapContract,\n    lookupSetContract,\n    unorderedMapContract,\n    unorderedSetContract,\n    vectorContract,\n    ali,\n  };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n      console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"JS lookup map contract operations\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n  \n  let rAdd;\n  for (let i = 0; i < COLLECTION_SIZE; i++) {\n    rAdd = await ali.callRaw(lookupMapContract, \"addElement\", { key: i, value: i });\n  }\n  t.is(rAdd.result.status.SuccessValue, \"\");\n  logTotalGas(\"Add element\", rAdd, t);\n\n  const val = randomInt(COLLECTION_SIZE);\n  const rGet = await ali.callRaw(lookupMapContract, \"getElement\", { key: val });\n  t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, \"base64\")), val);\n  logTotalGas(\"Get element\", rGet, t);\n\n  const rRem = await ali.callRaw(lookupMapContract, \"removeElement\", { key: randomInt(COLLECTION_SIZE) });\n  t.is(rRem.result.status.SuccessValue, \"\");\n  logTotalGas(\"Remove element\", rRem, t);\n});\n\ntest(\"JS lookup set contract operations\", async (t) => {\n  const { ali, lookupSetContract } = t.context.accounts;\n\n  let rAdd;\n  for (let i = 0; i < COLLECTION_SIZE; i++) {\n    rAdd = await ali.callRaw(lookupSetContract, \"addElement\", { value: i });\n  }\n  t.is(rAdd.result.status.SuccessValue, \"\");\n  logTotalGas(\"Add element\", rAdd, t);\n\n  const rGet = await ali.callRaw(lookupSetContract, \"containsElement\", { value: randomInt(COLLECTION_SIZE) });\n  t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, \"base64\")), true);\n  logTotalGas(\"Get element\", rGet, t);\n\n  const rRem = await ali.callRaw(lookupSetContract, \"removeElement\", { value: randomInt(COLLECTION_SIZE) });\n  t.is(rRem.result.status.SuccessValue, \"\");\n  logTotalGas(\"Remove element\", rRem, t);\n});\n\ntest(\"JS unordered map contract operations\", async (t) => {\n  const { ali, unorderedMapContract } = t.context.accounts;\n\n  let rAdd;\n  for (let i = 0; i < COLLECTION_SIZE; i++) {\n    rAdd = await ali.callRaw(unorderedMapContract, \"addElement\", { key: i, value: i });\n  }\n  t.is(rAdd.result.status.SuccessValue, \"\");\n  logTotalGas(\"Add element\", rAdd, t);\n\n  const val = randomInt(COLLECTION_SIZE);\n  const rGet = await ali.callRaw(unorderedMapContract, \"getElement\", { key: val });\n  t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, \"base64\")), val);\n  logTotalGas(\"Get element\", rGet, t);\n\n  const rIt = await ali.callRaw(unorderedMapContract, \"iterate\", {});\n  t.is(rIt.result.status.SuccessValue, \"\");\n  logTotalGas(\"Iterate collection\", rIt, t);\n\n  const rRem = await ali.callRaw(unorderedMapContract, \"removeElement\", { key: randomInt(COLLECTION_SIZE) });\n  t.is(rRem.result.status.SuccessValue, \"\");\n  logTotalGas(\"Remove element\", rRem, t);\n});\n\ntest(\"JS unordered set contract operations\", async (t) => {\n  const { ali, unorderedSetContract } = t.context.accounts;\n\n  let rAdd;\n  for (let i = 0; i < COLLECTION_SIZE; i++) {\n    rAdd = await ali.callRaw(unorderedSetContract, \"addElement\", { value: i });\n  }\n  t.is(rAdd.result.status.SuccessValue, \"\");\n  logTotalGas(\"Add element\", rAdd, t);\n\n  const rGet = await ali.callRaw(unorderedSetContract, \"containsElement\", { value: randomInt(COLLECTION_SIZE) });\n  t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, \"base64\")), true);\n  logTotalGas (\"Get element\", rGet, t);\n\n  const rIt = await ali.callRaw(unorderedSetContract, \"iterate\", {});\n  t.is(rIt.result.status.SuccessValue, \"\");\n  logTotalGas(\"Iterate collection\", rIt, t);\n\n  const rRem = await ali.callRaw(unorderedSetContract, \"removeElement\", { value: randomInt(COLLECTION_SIZE) });\n  t.is(rRem.result.status.SuccessValue, \"\");\n  logTotalGas(\"Remove element\", rRem, t);\n});\n\ntest(\"JS vector contract operations\", async (t) => {\n  const { ali, vectorContract } = t.context.accounts;\n\n  let rAdd;\n  for (let i = 0; i < COLLECTION_SIZE; i++) {\n    rAdd = await ali.callRaw(vectorContract, \"addElement\", { value: i });\n  }\n  t.is(rAdd.result.status.SuccessValue, \"\");\n  logTotalGas(\"Add element\", rAdd, t);\n\n  const val = randomInt(COLLECTION_SIZE);\n  const rGet = await ali.callRaw(vectorContract, \"getElement\", { index: val });\n  t.is(JSON.parse(Buffer.from(rGet.result.status.SuccessValue, \"base64\")), val);\n  logTotalGas(\"Get element\", rGet, t);\n\n  const rIt = await ali.callRaw(vectorContract, \"iterate\", {});\n  t.is(rIt.result.status.SuccessValue, \"\");\n  logTotalGas(\"Iterate collection\", rIt, t);\n\n  const rRem = await ali.callRaw(vectorContract, \"removeElement\", { index: randomInt(COLLECTION_SIZE) });\n  t.is(rRem.result.status.SuccessValue, \"\");\n  logTotalGas(\"Remove element\", rRem, t);\n});"
  },
  {
    "path": "benchmark/__tests__/test-deploy-contract.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport {\n  formatGas,\n  gasBreakdown,\n  logGasBreakdown,\n  logGasDetail,\n} from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const callerContract = await root.createSubAccount(\"caller\", {\n    initialBalance: \"1000N\",\n  });\n  await callerContract.deploy(\"build/deploy-contract.wasm\");\n\n  const callerContractRs = await root.createSubAccount(\"callrs\", {\n    initialBalance: \"1000N\",\n  });\n  await callerContractRs.deploy(\"res/deploy_contract.wasm\");\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    callerContract,\n    ali,\n    bob,\n    carl,\n    callerContractRs,\n  };\n});\n\ntest(\"JS promise batch deploy contract and call\", async (t) => {\n  const { bob, callerContract } = t.context.accounts;\n\n  let r = await bob.callRaw(callerContract, \"deploy_contract\", \"\", {\n    gas: \"300 Tgas\",\n  });\n  // console.log(JSON.stringify(r, null, 2));\n  let deployed = callerContract.getSubAccount(\"a\");\n  t.deepEqual(JSON.parse(Buffer.from(r.result.status.SuccessValue, \"base64\")), {\n    currentAccountId: deployed.accountId,\n    signerAccountId: bob.accountId,\n    predecessorAccountId: callerContract.accountId,\n    input: \"abc\",\n  });\n\n  t.log(\n    \"Gas used to convert transaction to receipt: \",\n    formatGas(r.result.transaction_outcome.outcome.gas_burnt)\n  );\n  t.log(\n    \"Gas used to execute the receipt (actual contract call): \",\n    formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)\n  );\n  let map = gasBreakdown(r.result.receipts_outcome[0].outcome);\n  logGasBreakdown(map, t);\n  t.log(\n    \"Gas used to execute the cross contract call: \",\n    formatGas(r.result.receipts_outcome[1].outcome.gas_burnt)\n  );\n  map = gasBreakdown(r.result.receipts_outcome[1].outcome);\n  logGasBreakdown(map, t);\n  t.log(\n    \"Gas used to refund unused gas for cross contract call: \",\n    formatGas(r.result.receipts_outcome[2].outcome.gas_burnt)\n  );\n  t.log(\n    \"Gas used to refund unused gas: \",\n    // TODO: fix after near-workspaces is updated\n    formatGas(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)\n  );\n  t.log(\n    \"Total gas used: \",\n    formatGas(\n      r.result.transaction_outcome.outcome.gas_burnt +\n        r.result.receipts_outcome[0].outcome.gas_burnt +\n        r.result.receipts_outcome[1].outcome.gas_burnt +\n        r.result.receipts_outcome[2].outcome.gas_burnt +\n        // TODO: fix after near-workspaces is updated\n        (r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)\n    )\n  );\n});\n\ntest(\"RS promise batch deploy contract and call\", async (t) => {\n  const { bob, callerContractRs } = t.context.accounts;\n\n  let r = await bob.callRaw(callerContractRs, \"deploy_contract\", \"\", {\n    gas: \"300 Tgas\",\n  });\n  // console.log(JSON.stringify(r, null, 2));\n  let deployed = callerContractRs.getSubAccount(\"a\");\n  t.deepEqual(JSON.parse(Buffer.from(r.result.status.SuccessValue, \"base64\")), {\n    currentAccountId: deployed.accountId,\n    signerAccountId: bob.accountId,\n    predecessorAccountId: callerContractRs.accountId,\n    input: \"abc\",\n  });\n\n  t.log(\n    \"Gas used to convert transaction to receipt: \",\n    formatGas(r.result.transaction_outcome.outcome.gas_burnt)\n  );\n  t.log(\n    \"Gas used to execute the receipt (actual contract call): \",\n    formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)\n  );\n  let map = gasBreakdown(r.result.receipts_outcome[0].outcome);\n  logGasBreakdown(map, t);\n  t.log(\n    \"Gas used to execute the cross contract call: \",\n    formatGas(r.result.receipts_outcome[1].outcome.gas_burnt)\n  );\n  map = gasBreakdown(r.result.receipts_outcome[1].outcome);\n  logGasBreakdown(map, t);\n  t.log(\n    \"Gas used to refund unused gas for cross contract call: \",\n    formatGas(r.result.receipts_outcome[2].outcome.gas_burnt)\n  );\n  t.log(\n    \"Gas used to refund unused gas: \",\n    // TODO: fix after near-workspaces is updated\n    formatGas(r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)\n  );\n  t.log(\n    \"Total gas used: \",\n    formatGas(\n      r.result.transaction_outcome.outcome.gas_burnt +\n        r.result.receipts_outcome[0].outcome.gas_burnt +\n        r.result.receipts_outcome[1].outcome.gas_burnt +\n        r.result.receipts_outcome[2].outcome.gas_burnt +\n        // TODO: fix after near-workspaces is updated\n        (r.result.receipts_outcome[3]?.outcome.gas_burnt || 0)\n    )\n  );\n});\n"
  },
  {
    "path": "benchmark/__tests__/test-expensive-calc.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const expensiveContract = await root.devDeploy(\"build/expensive-calc.wasm\");\n  const expensiveContractRs = await root.devDeploy(\"res/expensive_calc.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    expensiveContract,\n    expensiveContractRs,\n    ali,\n    bob,\n    carl,\n  };\n});\n\ntest(\"JS expensive contract, iterate 100 times\", async (t) => {\n  const { bob, expensiveContract } = t.context.accounts;\n  let r = await bob.callRaw(expensiveContract, \"expensive\", { n: 100 });\n\n  t.is(r.result.status.SuccessValue, \"LTUw\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS expensive contract. iterate 100 times\", async (t) => {\n  const { bob, expensiveContractRs } = t.context.accounts;\n  let r = await bob.callRaw(expensiveContractRs, \"expensive\", { n: 100 });\n  t.is(r.result.status.SuccessValue, \"LTUw\");\n  logGasDetail(r, t);\n});\n\ntest(\"JS expensive contract, iterate 10000 times\", async (t) => {\n  const { bob, expensiveContract } = t.context.accounts;\n  let r = await bob.callRaw(\n    expensiveContract,\n    \"expensive\",\n    { n: 10000 },\n    { gas: BigInt(300 * 10 ** 12) }\n  );\n\n  t.is(r.result.status.SuccessValue, \"LTUwMDA=\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS expensive contract. iterate 10000 times\", async (t) => {\n  const { bob, expensiveContractRs } = t.context.accounts;\n  let r = await bob.callRaw(expensiveContractRs, \"expensive\", { n: 10000 });\n  t.is(r.result.status.SuccessValue, \"LTUwMDA=\");\n  logGasDetail(r, t);\n});\n\ntest(\"JS expensive contract, iterate 20000 times\", async (t) => {\n  const { bob, expensiveContract } = t.context.accounts;\n  let r = await bob.callRaw(\n    expensiveContract,\n    \"expensive\",\n    { n: 20000 },\n    { gas: BigInt(300 * 10 ** 12) }\n  );\n\n  t.is(r.result.status.SuccessValue, \"LTEwMDAw\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS expensive contract. iterate 20000 times\", async (t) => {\n  const { bob, expensiveContractRs } = t.context.accounts;\n  let r = await bob.callRaw(expensiveContractRs, \"expensive\", { n: 20000 });\n  t.is(r.result.status.SuccessValue, \"LTEwMDAw\");\n  logGasDetail(r, t);\n});\n"
  },
  {
    "path": "benchmark/__tests__/test-highlevel-collection.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const highlevelContract = await root.devDeploy(\n    \"build/highlevel-collection.wasm\"\n  );\n  const highlevelContractRs = await root.devDeploy(\n    \"res/highlevel_collection.wasm\"\n  );\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    highlevelContract,\n    highlevelContractRs,\n    ali,\n    bob,\n    carl,\n  };\n});\n\ntest(\"JS highlevel collection contract\", async (t) => {\n  const { bob, highlevelContract } = t.context.accounts;\n  let r = await bob.callRaw(highlevelContract, \"set\", {\n    key: \"a\".repeat(100),\n    value: \"b\".repeat(100),\n  });\n  r = await bob.callRaw(highlevelContract, \"set\", {\n    key: \"b\".repeat(100),\n    value: \"c\".repeat(100),\n  });\n  r = await bob.callRaw(highlevelContract, \"set\", {\n    key: \"c\".repeat(100),\n    value: \"d\".repeat(100),\n  });\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS highlevel collection contract\", async (t) => {\n  const { bob, highlevelContractRs } = t.context.accounts;\n  let r = await bob.callRaw(highlevelContractRs, \"set\", {\n    key: \"a\".repeat(100),\n    value: \"b\".repeat(100),\n  });\n  r = await bob.callRaw(highlevelContractRs, \"set\", {\n    key: \"b\".repeat(100),\n    value: \"c\".repeat(100),\n  });\n  r = await bob.callRaw(highlevelContractRs, \"set\", {\n    key: \"c\".repeat(100),\n    value: \"d\".repeat(100),\n  });\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n"
  },
  {
    "path": "benchmark/__tests__/test-highlevel-minimal.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const highlevelContract = await root.devDeploy(\n    \"build/highlevel-minimal.wasm\"\n  );\n  const highlevelContractRs = await root.devDeploy(\n    \"res/highlevel_minimal.wasm\"\n  );\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    highlevelContract,\n    highlevelContractRs,\n    ali,\n    bob,\n    carl,\n  };\n});\n\ntest(\"JS highlevel minimal contract\", async (t) => {\n  const { bob, highlevelContract } = t.context.accounts;\n  let r = await bob.callRaw(highlevelContract, \"empty\", \"\");\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS highlevel minimal contract\", async (t) => {\n  const { bob, highlevelContractRs } = t.context.accounts;\n  let r = await bob.callRaw(highlevelContractRs, \"empty\", \"\");\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n"
  },
  {
    "path": "benchmark/__tests__/test-lowlevel-api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const lowlevelContract = await root.devDeploy(\"build/lowlevel-api.wasm\");\n  const lowlevelContractRs = await root.devDeploy(\"res/lowlevel_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    lowlevelContract,\n    lowlevelContractRs,\n    ali,\n    bob,\n    carl,\n  };\n});\n\ntest(\"JS lowlevel API contract\", async (t) => {\n  const { bob, lowlevelContract } = t.context.accounts;\n  let r = await bob.callRaw(lowlevelContract, \"lowlevel_storage_write\", \"\");\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS lowlevel API contract\", async (t) => {\n  const { bob, lowlevelContractRs } = t.context.accounts;\n  let r = await bob.callRaw(lowlevelContractRs, \"lowlevel_storage_write\", \"\");\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n\ntest(\"JS lowlevel API contract, call many\", async (t) => {\n  const { bob, lowlevelContract } = t.context.accounts;\n  let r = await bob.callRaw(\n    lowlevelContract,\n    \"lowlevel_storage_write_many\",\n    \"\"\n  );\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n"
  },
  {
    "path": "benchmark/__tests__/test-lowlevel-minimal.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport { logGasDetail } from \"./util.js\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const lowlevelContract = await root.devDeploy(\"build/lowlevel-minimal.wasm\");\n  const lowlevelContractRs = await root.devDeploy(\"res/lowlevel_minimal.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    lowlevelContract,\n    lowlevelContractRs,\n    ali,\n    bob,\n    carl,\n  };\n});\n\ntest(\"JS lowlevel minimal contract\", async (t) => {\n  const { bob, lowlevelContract } = t.context.accounts;\n  let r = await bob.callRaw(lowlevelContract, \"empty\", \"\");\n\n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n\ntest(\"RS lowlevel minimal contract\", async (t) => {\n  const { bob, lowlevelContractRs } = t.context.accounts;\n  let r = await bob.callRaw(lowlevelContractRs, \"empty\", \"\");\n  \n  t.is(r.result.status.SuccessValue, \"\");\n  logGasDetail(r, t);\n});\n"
  },
  {
    "path": "benchmark/__tests__/util.js",
    "content": "// Functions consumed by the benchmark contracts tests\n\nexport function formatGas(gas) {\n  if (gas < 10 ** 12) {\n    let tGas = gas / 10 ** 12;\n    let roundTGas = Math.round(tGas * 100000) / 100000;\n    return roundTGas + \"T\";\n  }\n  let tGas = gas / 10 ** 12;\n  let roundTGas = Math.round(tGas * 100) / 100;\n  return roundTGas + \"T\";\n}\n\nexport function gasBreakdown(outcome) {\n  return new Map(\n    outcome.metadata.gas_profile.map((g) => {\n      return [g.cost, Number(g.gas_used)];\n    })\n  );\n}\n\nexport function logGasBreakdown(map, t) {\n  map.forEach((v, k) => {\n    t.log(\"  \", k, \": \", formatGas(v));\n  });\n}\n\nexport function logGasDetail(r, t) {\n  t.log(\n    \"Gas used to convert transaction to receipt: \",\n    formatGas(r.result.transaction_outcome.outcome.gas_burnt)\n  );\n  t.log(\n    \"Gas used to execute the receipt (actual contract call): \",\n    formatGas(r.result.receipts_outcome[0].outcome.gas_burnt)\n  );\n  let map = gasBreakdown(r.result.receipts_outcome[0].outcome);\n  logGasBreakdown(map, t);\n  t.log(\n    \"Gas used to refund unused gas: \",\n    // TODO: fix after near-workspaces is updated\n    formatGas(r.result.receipts_outcome[1]?.outcome.gas_burnt || 0)\n  );\n  t.log(\n    \"Total gas used: \",\n    formatGas(\n      r.result.transaction_outcome.outcome.gas_burnt +\n        r.result.receipts_outcome[0].outcome.gas_burnt +\n        // TODO: fix after near-workspaces is updated\n        (r.result.receipts_outcome[1]?.outcome.gas_burnt || 0)\n    )\n  );\n}\n\nexport function logTotalGas(prefix = '', r, t) {\n  t.log(\n    prefix + ' - Total gas used: ',\n    formatGas(\n      r.result.transaction_outcome.outcome.gas_burnt +\n      r.result.receipts_outcome[0].outcome.gas_burnt +\n      (r.result.receipts_outcome[1]?.outcome.gas_burnt || 0)\n    )\n  );\n}\n\nexport function randomInt(max) {\n  return Math.floor(Math.random() * max);\n}"
  },
  {
    "path": "benchmark/ava.config.cjs",
    "content": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n  timeout: \"300000\",\n  files: [\"**/*.ava.js\"],\n  failWithoutAssertions: false,\n  extensions: [\"js\"],\n};\n"
  },
  {
    "path": "benchmark/example-outcome.json",
    "content": "{\n  \"result\": {\n    \"receipts_outcome\": [\n      {\n        \"block_hash\": \"B5zQjLFz1zu36xoUd37Bghzeanw8YfbkLk9amcVdPX4H\",\n        \"id\": \"7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi\",\n        \"outcome\": {\n          \"executor_id\": \"dev-14843.test.near\",\n          \"gas_burnt\": 4217783714059,\n          \"logs\": [],\n          \"metadata\": {\n            \"gas_profile\": [\n              {\n                \"cost\": \"CONTRACT_LOADING_BASE\",\n                \"cost_category\": \"WASM_HOST_COST\",\n                \"gas_used\": \"35445963\"\n              },\n              {\n                \"cost\": \"CONTRACT_LOADING_BYTES\",\n                \"cost_category\": \"WASM_HOST_COST\",\n                \"gas_used\": \"108947436750\"\n              },\n              {\n                \"cost\": \"WASM_INSTRUCTION\",\n                \"cost_category\": \"WASM_HOST_COST\",\n                \"gas_used\": \"1680864179808\"\n              }\n            ],\n            \"version\": 1\n          },\n          \"receipt_ids\": [\"8FYdTYgNnz5jnCDFFHfbyrBVq5rp9beStZYjxjrXvQ5F\"],\n          \"status\": {\n            \"SuccessValue\": \"\"\n          },\n          \"tokens_burnt\": \"4217783714059000000000\"\n        },\n        \"proof\": []\n      },\n      {\n        \"block_hash\": \"4oUZamxqDyUuMp47xfGE7FTnRBRC28VdMuPCS3oSCKpw\",\n        \"id\": \"8FYdTYgNnz5jnCDFFHfbyrBVq5rp9beStZYjxjrXvQ5F\",\n        \"outcome\": {\n          \"executor_id\": \"bob.test.near\",\n          \"gas_burnt\": 223182562500,\n          \"logs\": [],\n          \"metadata\": {\n            \"gas_profile\": [],\n            \"version\": 1\n          },\n          \"receipt_ids\": [],\n          \"status\": {\n            \"SuccessValue\": \"\"\n          },\n          \"tokens_burnt\": \"0\"\n        },\n        \"proof\": []\n      }\n    ],\n    \"status\": {\n      \"SuccessValue\": \"\"\n    },\n    \"transaction\": {\n      \"actions\": [\n        {\n          \"FunctionCall\": {\n            \"args\": \"IiI=\",\n            \"deposit\": \"0\",\n            \"gas\": 30000000000000,\n            \"method_name\": \"empty\"\n          }\n        }\n      ],\n      \"hash\": \"9TvjxGooYJ7A1Ju6NHocss2uCqPeUKiEv1EwPoiXUsS2\",\n      \"nonce\": 10000001,\n      \"public_key\": \"ed25519:5iyD5kpiWwBgW3vunXJdmj66ArJAZBhGUxHEud6UKbyr\",\n      \"receiver_id\": \"dev-14843.test.near\",\n      \"signature\": \"ed25519:5jb67kd3VoTnBWxpSgyHENdWerGwLaa5QJHaKVvaxrZosymia2cKf3DNC4ES3PHZ7mXHkky5JTheqnzzjCpop7fx\",\n      \"signer_id\": \"bob.test.near\"\n    },\n    \"transaction_outcome\": {\n      \"block_hash\": \"FQAFEjJVuBJK6Mf64DxfpMPWifP8jyEUJc6zW3yn1rca\",\n      \"id\": \"9TvjxGooYJ7A1Ju6NHocss2uCqPeUKiEv1EwPoiXUsS2\",\n      \"outcome\": {\n        \"executor_id\": \"bob.test.near\",\n        \"gas_burnt\": 2427936651538,\n        \"logs\": [],\n        \"metadata\": {\n          \"gas_profile\": null,\n          \"version\": 1\n        },\n        \"receipt_ids\": [\"7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi\"],\n        \"status\": {\n          \"SuccessReceiptId\": \"7GaMgKm53Mv5hwimyLTQnxEvaacvSABHhhJXbQYFkiXi\"\n        },\n        \"tokens_burnt\": \"2427936651538000000000\"\n      },\n      \"proof\": []\n    }\n  },\n  \"startMs\": 1675654730297,\n  \"endMs\": 1675654732818,\n  \"config\": {\n    \"network\": \"sandbox\",\n    \"rootAccountId\": \"test.near\",\n    \"rpcAddr\": \"http://localhost:6163\",\n    \"initialBalance\": \"100000000000000000000000000\",\n    \"homeDir\": \"/tmp/sandbox/7a047a19-1712-48ba-9704-d5831cf91f2a\",\n    \"port\": 6163,\n    \"rm\": false,\n    \"refDir\": null\n  }\n}\n"
  },
  {
    "path": "benchmark/jsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"experimentalDecorators\": true\n  },\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "benchmark/package.json",
    "content": "{\n  \"name\": \"bench\",\n  \"version\": \"1.0.0\",\n  \"description\": \"near-sdk-js benchmark\",\n  \"main\": \"index.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"run-s build:*\",\n    \"build:lowlevel-minimal\": \"near-sdk-js build src/lowlevel-minimal.js build/lowlevel-minimal.wasm\",\n    \"build:highlevel-minimal\": \"near-sdk-js build src/highlevel-minimal.js build/highlevel-minimal.wasm\",\n    \"build:lowlevel-api\": \"near-sdk-js build src/lowlevel-api.js build/lowlevel-api.wasm\",\n    \"build:highlevel-collection\": \"near-sdk-js build src/highlevel-collection.js build/highlevel-collection.wasm\",\n    \"build:expensive-calc\": \"near-sdk-js build src/expensive-calc.js build/expensive-calc.wasm\",\n    \"build:deploy-contract\": \"near-sdk-js build src/deploy-contract.js build/deploy-contract.wasm\",\n    \"build:lookup-map\": \"near-sdk-js build src/lookup-map.js build/lookup-map.wasm\",\n    \"build:lookup-set\": \"near-sdk-js build src/lookup-set.js build/lookup-set.wasm\",\n    \"build:unordered-map\": \"near-sdk-js build src/unordered-map.js build/unordered-map.wasm\",\n    \"build:unordered-set\": \"near-sdk-js build src/unordered-set.js build/unordered-set.wasm\",\n    \"build:vector\": \"near-sdk-js build src/vector.js build/vector.wasm\",\n    \"test\": \"ava\",\n    \"test:lowlevel-minimal\": \"ava __tests__/test-lowlevel-minimal.ava.js\",\n    \"test:highlevel-minimal\": \"ava __tests__/test-highlevel-minimal.ava.js\",\n    \"test:lowlevel-api\": \"ava __tests__/test-lowlevel-api.ava.js\",\n    \"test:highlevel-collection\": \"ava __tests__/test-highlevel-collection.ava.js\",\n    \"test:expensive-calc\": \"ava __tests__/test-expensive-calc.ava.js\",\n    \"test:deploy-contract\": \"ava __tests__/test-deploy-contract.ava.js\",\n    \"test:collections\": \"ava __tests__/test-collections-performance.ava.js\"\n  },\n  \"author\": \"Near Inc <hello@nearprotocol.com>\",\n  \"license\": \"Apache-2.0\",\n  \"devDependencies\": {\n    \"ava\": \"4.3.3\",\n    \"near-workspaces\": \"4.0.0\",\n    \"npm-run-all\": \"4.1.5\"\n  },\n  \"dependencies\": {\n    \"typescript\": \"4.7.4\",\n    \"near-sdk-js\": \"workspace:*\"\n  }\n}\n"
  },
  {
    "path": "benchmark/src/deploy-contract.js",
    "content": "import { near } from \"near-sdk-js\";\n\n/**\n * Used for contract deployment. More information for that\n * can be found in the README.md\n * - Deploy and cross contract call\n */\nexport function deploy_contract() {\n  let promiseId = near.promiseBatchCreate(\"a.caller.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseBatchActionDeployContract(\n    promiseId,\n    includeBytes(\"../../tests/build/promise_api.wasm\")\n  );\n  near.promiseBatchActionFunctionCall(\n    promiseId,\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n  near.promiseReturn(promiseId);\n}\n"
  },
  {
    "path": "benchmark/src/expensive-calc.js",
    "content": "import { NearBindgen, call, near } from \"near-sdk-js\";\n\n/**\n * ExpensiveCalc is connected to the expensive contract. More information for that\n * can be found in the README.md\n * - Computational expensive contract\n */\n@NearBindgen({})\nexport class ExpensiveCalc {\n  @call({})\n  expensive({ n }) {\n    let ret = 0;\n    let sign = 1;\n    for (let i = 0; i < n; i++) {\n      ret += i * sign;\n      sign *= -1;\n    }\n    near.valueReturn(ret.toString());\n  }\n}\n"
  },
  {
    "path": "benchmark/src/highlevel-collection.js",
    "content": "import { NearBindgen, call, UnorderedMap } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the README.md\n * - Highlevel collection\n */\n@NearBindgen({})\nexport class HighlevelCollection {\n  constructor() {\n    this.unorderedMap = new UnorderedMap(\"a\");\n  }\n\n  @call({})\n  set({ key, value }) {\n    this.unorderedMap.set(key, value);\n  }\n}\n"
  },
  {
    "path": "benchmark/src/highlevel-minimal.js",
    "content": "import { NearBindgen, call } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the README.md\n * - A highlevel minimal contract (using nearbindgen)\n */\n@NearBindgen({})\nexport class HighlevelMinimal {\n  @call({})\n  empty({}) {}\n}\n"
  },
  {
    "path": "benchmark/src/lookup-map.js",
    "content": "import { NearBindgen, call, LookupMap, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class LookupMapContract {\n    constructor() {\n        this.lookupMap = new LookupMap(\"LM\");\n    }\n\n    @call({})\n    addElement({ key, value }) {\n        this.lookupMap.set(key, value);\n    }\n\n    @call({})\n    removeElement({ key }) {\n        this.lookupMap.remove(key);\n    }\n\n    @view({})\n    getElement({ key }) {\n        return this.lookupMap.get(key);\n    }\n}\n"
  },
  {
    "path": "benchmark/src/lookup-set.js",
    "content": "import { NearBindgen, call, LookupSet, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class LookupSetContract {\n    constructor() {\n        this.lookupSet = new LookupSet(\"LS\");\n    }\n\n    @call({})\n    addElement({ value }) {\n        this.lookupSet.set(value);\n    }\n\n    @call({})\n    removeElement({ value }) {\n        this.lookupSet.remove(value);\n    }\n\n    @view({})\n    containsElement({ value }) {\n        return this.lookupSet.contains(value);\n    }\n}\n"
  },
  {
    "path": "benchmark/src/lowlevel-api.js",
    "content": "import { near } from \"near-sdk-js\";\n\n/**\n * Helper method for the low level api. More information for that can be found in the README.md\n * - Low level API\n */\nexport function lowlevel_storage_write() {\n  let data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n  near.storageWriteRaw(data, data);\n}\n\n/**\n * Helper method for the low level api. More information for that can be found in the README.md\n * - Low level API\n */\nexport function lowlevel_storage_write_many() {\n  let data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n  near.storageWriteRaw(data, data);\n}\n"
  },
  {
    "path": "benchmark/src/lowlevel-minimal.js",
    "content": "import { near } from \"near-sdk-js\";\n\n/**\n * More information for that can be found in the README.md\n * - A minimal contract\n */\nexport function empty() {}\n"
  },
  {
    "path": "benchmark/src/unordered-map.js",
    "content": "import { NearBindgen, call, UnorderedMap, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class UnorderedMapContract {\n    constructor() {\n        this.unorderedMap = new UnorderedMap(\"UM\");\n    }\n\n    @call({})\n    addElement({ key, value }) {\n        this.unorderedMap.set(key, value);\n    }\n\n    @call({})\n    removeElement({ key }) {\n        this.unorderedMap.remove(key);\n    }\n\n    @view({})\n    getElement({ key }) {\n        return this.unorderedMap.get(key);\n    }\n\n    @view({})\n    iterate() {\n        const size = this.unorderedMap.length;\n        for (let i = 0; i < size; i++) {\n            this.unorderedMap.get(i);\n        }\n    }\n}\n"
  },
  {
    "path": "benchmark/src/unordered-set.js",
    "content": "import { NearBindgen, call, UnorderedSet, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class UnorderedSetContract {\n    constructor() {\n        this.unorderedSet = new UnorderedSet(\"US\");\n    }\n\n    @call({})\n    addElement({ value }) {\n        this.unorderedSet.set(value);\n    }\n\n    @call({})\n    removeElement({ value }) {\n        this.unorderedSet.remove(value);\n    }\n\n    @view({})\n    containsElement({ value }) {\n        return this.unorderedSet.contains(value);\n    }\n\n    @view({})\n    iterate() {\n        const size = this.unorderedSet.length;\n        for (let i = 0; i < size; i++) {\n            this.unorderedSet.contains(i);\n        }\n    }\n}\n"
  },
  {
    "path": "benchmark/src/vector.js",
    "content": "import { NearBindgen, call, Vector, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class VectorContract {\n    constructor() {\n        this.vector = new Vector(\"V\");\n    }\n\n    @call({})\n    addElement({ value }) {\n        this.vector.push(value);\n    }\n\n    @call({})\n    removeElement({ index }) {\n        this.vector.swapRemove(index);\n    }\n\n    @view({})\n    getElement({ index }) {\n        return this.vector.get(index);\n    }\n\n    @view({})\n    iterate() {\n        const size = this.vector.length;\n        for (let i = 0; i < size; i++) {\n            this.vector.get(i);\n        }\n    }\n}\n"
  },
  {
    "path": "benchmark/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"moduleResolution\": \"node\",\n    \"experimentalDecorators\": true,\n    \"target\": \"es2020\",\n    \"noEmit\": true\n  },\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "examples/.gitignore",
    "content": "build\nnode_modules"
  },
  {
    "path": "examples/README.md",
    "content": "# Example Smart Contracts\n\nThis 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.\n\n## Overview\n\nThe 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.\n\n## Build and Test\n\nTo build and test the smart contracts in this directory, follow the steps below:\n\n### Build\n\nTo build all the smart contracts, run the following command in the root of the project:\n\n```\npnpm build\n```\n\n### Test\n\nTo run the tests for the example smart contracts, use the following command:\n\n```\npnpm test\n```\n\nThis command will execute the test suites associated with each smart contract, ensuring that they function as expected.\n\n## List of Example Smart Contracts\n\nThe following smart contracts demonstrate various capabilities of the NEAR blockchain, using JavaScript/TypeScript.\nEach example highlights specific features and serves as a practical guide for developers.\n\n**[basic-updates](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/basic-updates)**<br />\nA simple smart contract that can make basic state updates.\n\n**[counter](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/counter)**<br />\nA simple smart contract that demonstrates state management by implementing a basic counter with increment and decrement functionalities.\n\n**[cross-contract](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/cross-contract)**<br />\nA smart contract that demonstrates how to perform cross-contract calls on the NEAR blockchain, including querying external contracts to manage on-chain interactions.\n\n**[fungible-token](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/fungible-token)**<br />\nExample 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`.\n\n**[non-fungible-token](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/non-fungible-token)**<br />\nExample 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).\n\n**[programmatic-updates](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/programmatic-updates)**<br />\nContracts showcasing how contracts can evolve while maintaining certain logic from previous versions.\n\n**[state-migration](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/state-migration)**<br />\nA smart contract that demonstrates how to handle state migration in a NEAR smart contract.\n\n**[status-message](https://github.com/near/near-sdk-js/tree/documentation-improvements/examples/src/status-message)**<br />\nSmart contracts that record the status messages of the accounts that call the contracts.\n\n## Contributing\n\nIf you find any issues or have suggestions for improvement, feel free to open an issue or submit a pull request. Contributions are welcome!\n"
  },
  {
    "path": "examples/__tests__/standard-ft/ft-tests.ava.js",
    "content": "import { NEAR, Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nconst INITIAL_BALANCE = NEAR.parse(\"10000 N\").toJSON();\nconst ONE_YOCTO = \"1\";\nconst STOARAGE_BYTE_COST = 10_000_000_000_000_000_000n;\nconst ACCOUNT_STORAGE_BALANCE = String(STOARAGE_BYTE_COST * 138n);\n\ntest.beforeEach(async (t) => {\n    const worker = await Worker.init();\n    const root = worker.rootAccount;\n\n    const ftContract = await root.devDeploy(\"./build/my-ft.wasm\");\n    await ftContract.call(\n        ftContract,\n        \"init_with_default_meta\",\n        {\n            owner_id: ftContract.accountId,\n            total_supply: INITIAL_BALANCE\n        }\n    );\n\n    /**\n     * DEFI contract implemented in https://github.com/near/near-sdk-rs/tree/master/examples/fungible-token/test-contract-defi\n     * Iterface:\n     * pub fn new(fungible_token_account_id: AccountId) -> Self;\n     * fn ft_on_transfer(\n        &mut self,\n        sender_id: AccountId,\n        amount: U128,\n        msg: String,\n    ) -> PromiseOrValue<U128>\n     * 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\n     */\n    const defiContract = await root.devDeploy(\"./res/defi.wasm\");\n\n    await defiContract.call(\n        defiContract,\n        \"new\",\n        {\n            fungible_token_account_id: ftContract.accountId\n        }\n    );\n\n    const alice = await root.createSubAccount(\"alice\", { initialBalance: NEAR.parse(\"10 N\").toJSON() });\n\n    await registerUser(ftContract, alice.accountId);\n\n    t.context.worker = worker;\n    t.context.accounts = {\n        root,\n        ftContract,\n        alice,\n        defiContract,\n    };\n});\n\ntest.afterEach.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed tear down the worker:\", error);\n    });\n});\n\n\nasync function registerUser(contract, account_id) {\n    const deposit = String(ACCOUNT_STORAGE_BALANCE);\n    await contract.call(contract, \"storage_deposit\", { account_id: account_id }, { attachedDeposit: deposit });\n}\n\ntest(\"test_total_supply\", async (t) => {\n    const { ftContract } = t.context.accounts;\n    const res = await ftContract.view(\"ft_total_supply\", {});\n    t.is(BigInt(res), BigInt(INITIAL_BALANCE));\n});\n\ntest(\"test_storage_deposit\", async (t) => {\n    const { ftContract, root } = t.context.accounts;\n    const bob = await root.createSubAccount(\"bob\", { initialBalance: NEAR.parse(\"10 N\").toJSON() });\n    await registerUser(ftContract, bob.accountId);\n    const bobStorageBalance = await ftContract.view(\"storage_balance_of\", { account_id: bob.accountId });\n    t.is(bobStorageBalance.total, String(ACCOUNT_STORAGE_BALANCE));\n});\n\ntest(\"test_simple_transfer\", async (t) => {\n    const TRANSFER_AMOUNT = NEAR.parse(\"1000 N\").toJSON();\n    const EXPECTED_ROOT_BALANCE = NEAR.parse(\"9000 N\").toJSON();\n\n    const { ftContract, alice } = t.context.accounts;\n\n    await ftContract.call(\n        ftContract,\n        \"ft_transfer\",\n        {\n            receiver_id: alice.accountId,\n            amount: TRANSFER_AMOUNT,\n            memo: null\n        },\n        {\n            attachedDeposit: ONE_YOCTO\n        }\n    );\n\n    let root_balance = await ftContract.view(\"ft_balance_of\", { account_id: ftContract.accountId });\n\n    let alice_balance = await ftContract.view(\"ft_balance_of\", { account_id: alice.accountId });\n\n    t.is(EXPECTED_ROOT_BALANCE, root_balance);\n    t.is(TRANSFER_AMOUNT, alice_balance);\n});\n\ntest(\"test_close_account_empty_balance\", async (t) => {\n    const { ftContract, alice } = t.context.accounts;\n\n    let res = await alice.call(ftContract, \"storage_unregister\", {}, { attachedDeposit: ONE_YOCTO });\n    t.is(res, true); // TODO: doublecheck\n});\n\ntest(\"test_close_account_non_empty_balance\", async (t) => {\n    const { ftContract } = t.context.accounts;\n\n    try {\n        await ftContract.call(ftContract, \"storage_unregister\", {}, { attachedDeposit: ONE_YOCTO });\n        throw Error(\"Unreachable string\");\n    } catch (e) {\n        t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes(\"Can't unregister the account with the positive balance without force\"), true);\n    }\n\n    try {\n        await ftContract.call(ftContract, \"storage_unregister\", { force: false }, { attachedDeposit: ONE_YOCTO });\n        throw Error(\"Unreachable string\");\n    } catch (e) {\n        t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes(\"Can't unregister the account with the positive balance without force\"), true);\n    }\n});\n\ntest(\"simulate_close_account_force_non_empty_balance\", async (t) => {\n    const { ftContract } = t.context.accounts;\n\n    await ftContract.call(\n        ftContract,\n        \"storage_unregister\",\n        { force: true },\n        { attachedDeposit: ONE_YOCTO }\n    );\n\n    const res = await ftContract.view(\"ft_total_supply\", {});\n    t.is(res, \"0\");\n});\n\ntest(\"simulate_transfer_call_with_burned_amount\", async (t) => {\n    const TRANSFER_AMOUNT = NEAR.parse(\"100 N\").toJSON();\n\n    const { ftContract, defiContract } = t.context.accounts;\n\n    // defi contract must be registered as a FT account\n    await registerUser(ftContract, defiContract.accountId);\n\n    const result = await ftContract\n        .batch(ftContract)\n        .functionCall(\n            'ft_transfer_call',\n            {\n                receiver_id: defiContract.accountId,\n                amount: TRANSFER_AMOUNT,\n                memo: null,\n                msg: \"10\",\n            },\n            {\n                attachedDeposit: '1',\n                gas: '150 Tgas'\n            },\n        )\n        .functionCall(\n            'storage_unregister',\n            {\n                force: true\n            },\n            {\n                attachedDeposit: '1',\n                gas: '150 Tgas',\n            },\n        )\n        .transact();\n\n    const logs = JSON.stringify(result);\n    let expected = `Account @${ftContract.accountId} burned ${10}`;\n    t.is(logs.includes(\"The account of the sender was deleted\"), true);\n    t.is(logs.includes(expected), true);\n\n    const new_total_supply = await ftContract.view(\"ft_total_supply\", {});\n\n    t.is(BigInt(new_total_supply), BigInt(TRANSFER_AMOUNT) - 10n);\n\n    const defi_balance = await ftContract.view(\"ft_balance_of\", { account_id: defiContract.accountId });\n\n    t.is(BigInt(defi_balance), BigInt(TRANSFER_AMOUNT) - 10n);\n});\n\ntest(\"simulate_transfer_call_with_immediate_return_and_no_refund\", async (t) => {\n    const TRANSFER_AMOUNT = NEAR.parse(\"100 N\").toJSON();\n\n    const { ftContract, defiContract } = t.context.accounts;\n\n    // defi ftContract must be registered as a FT account\n    await registerUser(ftContract, defiContract.accountId);\n\n    // root invests in defi by calling `ft_transfer_call`\n    await ftContract.call(\n        ftContract,\n        \"ft_transfer_call\",\n        {\n            receiver_id: defiContract.accountId,\n            amount: TRANSFER_AMOUNT,\n            memo: null,\n            msg: \"take-my-money\"\n        },\n        {\n            attachedDeposit: ONE_YOCTO,\n            gas: 300000000000000,\n        }\n    );\n\n    let root_balance = await ftContract.view(\"ft_balance_of\", { account_id: ftContract.accountId });\n    let defi_balance = await ftContract.view(\"ft_balance_of\", { account_id: defiContract.accountId });\n\n    t.is(BigInt(INITIAL_BALANCE) - BigInt(TRANSFER_AMOUNT), BigInt(root_balance));\n    t.is(TRANSFER_AMOUNT, defi_balance);\n});\n\ntest(\"simulate_transfer_call_when_called_contract_not_registered_with_ft\", async (t) => {\n    const TRANSFER_AMOUNT = NEAR.parse(\"100 N\").toJSON();\n\n    const { ftContract, defiContract } = t.context.accounts;\n\n    // call fails because DEFI contract is not registered as FT user\n    try {\n        await ftContract.call(\n            ftContract,\n            \"ft_transfer_call\",\n            {\n                receiver_id: defiContract.accountId,\n                amount: TRANSFER_AMOUNT,\n                memo: null,\n                msg: \"take-my-money\"\n            },\n            {\n                attachedDeposit: ONE_YOCTO,\n                gas: 50000000000000n,\n            }\n        );\n        t.is(true, false); // Unreachable\n    } catch (e) {\n        t.is(JSON.stringify(e, Object.getOwnPropertyNames(e)).includes(\"is not registered\"), true);\n    }\n\n    // balances remain unchanged\n    let root_balance = await ftContract.view(\"ft_balance_of\", { account_id: ftContract.accountId });\n    let defi_balance = await ftContract.view(\"ft_balance_of\", { account_id: defiContract.accountId });\n\n    t.is(BigInt(INITIAL_BALANCE), BigInt(root_balance));\n    t.is(\"0\", defi_balance);\n});\n\ntest(\"simulate_transfer_call_with_promise_and_refund\", async (t) => {\n    const REFUND_AMOUNT = NEAR.parse(\"50 N\").toJSON();\n    const TRANSFER_AMOUNT = NEAR.parse(\"100 N\").toJSON();\n    const TRANSFER_CALL_GAS = String(300_000_000_000_000n);\n\n    const { ftContract, defiContract } = t.context.accounts;\n\n    // defi contract must be registered as a FT account\n    await registerUser(ftContract, defiContract.accountId);\n\n    await ftContract.call(ftContract, \"ft_transfer_call\", {\n        receiver_id: defiContract.accountId,\n        amount: TRANSFER_AMOUNT,\n        memo: null,\n        msg: REFUND_AMOUNT,\n    }, {\n        attachedDeposit: ONE_YOCTO,\n        gas: TRANSFER_CALL_GAS,\n    });\n\n    let root_balance = await ftContract.view(\"ft_balance_of\", { account_id: ftContract.accountId });\n    let defi_balance = await ftContract.view(\"ft_balance_of\", { account_id: defiContract.accountId });\n\n    t.is(BigInt(INITIAL_BALANCE) - BigInt(TRANSFER_AMOUNT) + BigInt(REFUND_AMOUNT), BigInt(root_balance));\n    t.is(BigInt(TRANSFER_AMOUNT) - BigInt(REFUND_AMOUNT), BigInt(defi_balance));\n});\n\ntest(\"simulate_transfer_call_promise_panics_for_a_full_refund\", async (t) => {\n    const TRANSFER_AMOUNT = NEAR.parse(\"100 N\").toJSON();\n\n    const { ftContract, defiContract } = t.context.accounts;\n\n    // defi contract must be registered as a FT account\n    await registerUser(ftContract, defiContract.accountId);\n\n    // root invests in defi by calling `ft_transfer_call`\n    const res = await ftContract.callRaw(\n        ftContract,\n        \"ft_transfer_call\",\n        {\n            receiver_id: defiContract.accountId,\n            amount: TRANSFER_AMOUNT,\n            memo: null,\n            msg: \"no parsey as integer big panic oh no\",\n        },\n        {\n            attachedDeposit: ONE_YOCTO,\n            gas: 50000000000000n,\n        }\n    );\n\n    t.is(JSON.stringify(res).includes(\"ParseIntError\"), true);\n\n    // balances remain unchanged\n    let root_balance = await ftContract.view(\"ft_balance_of\", { account_id: ftContract.accountId });\n    let defi_balance = await ftContract.view(\"ft_balance_of\", { account_id: defiContract.accountId });\n\n    t.is(INITIAL_BALANCE, root_balance);\n    t.is(\"0\", defi_balance);\n});\n"
  },
  {
    "path": "examples/__tests__/standard-nft/test_approval.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy status-message the contract.\n  const nft = await root.devDeploy(\"./build/my-nft.wasm\");\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"alice\");\n  const bob = await root.createSubAccount(\"bob\");\n  const nftOwner = await root.createSubAccount(\"owner\");\n  const nftReceiver = await root.devDeploy(\"./build/nft-receiver.wasm\");\n  const approvalReceiver = await root.devDeploy(\n    \"./build/nft-approval-receiver.wasm\"\n  );\n\n  await nft.call(nft, \"init\", {\n    owner_id: nftOwner.accountId,\n    metadata: { spec: \"nft-1.0.0\", name: \"My NFT\", symbol: \"NFT\" },\n  });\n\n  await nftReceiver.call(nftReceiver, \"init\", {\n    non_fungible_token_account_id: nft.accountId,\n  });\n  await approvalReceiver.call(approvalReceiver, \"init\", {\n    non_fungible_token_account_id: nft.accountId,\n  });\n\n  let token_metadata = {\n    title: \"Olympus Mons\",\n    description: \"The tallest mountain in the charted solar system\",\n    media: null,\n    media_hash: null,\n    copies: 1,\n    issued_at: null,\n    expires_at: null,\n    starts_at: null,\n    updated_at: null,\n    extra: null,\n    reference: null,\n    reference_hash: null,\n  };\n  await nftOwner.call(\n    nft,\n    \"nft_mint\",\n    {\n      token_id: \"0\",\n      token_owner_id: nftOwner.accountId,\n      token_metadata,\n    },\n    { attachedDeposit: \"10 mN\" }\n  );\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    nft,\n    ali,\n    bob,\n    nftOwner,\n    nftReceiver,\n    approvalReceiver,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Simple approve\", async (t) => {\n  const { ali, bob, nft, nftOwner } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: ali.accountId,\n    },\n    { attachedDeposit: \"510000000000000000000\" }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  let alice_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n  });\n  t.assert(alice_approved);\n\n  let alice_approval_id_is_1 = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n    approval_id: \"1\",\n  });\n  t.assert(alice_approval_id_is_1);\n\n  let alice_approval_id_is_2 = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n    approval_id: \"2\",\n  });\n  t.assert(!alice_approval_id_is_2);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: ali.accountId,\n    },\n    {\n      attachedDeposit: \"1\",\n    }\n  );\n  t.assert(res.result.status.SuccessValue);\n  alice_approval_id_is_2 = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n    approval_id: \"2\",\n  });\n  t.assert(alice_approval_id_is_2);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: bob.accountId,\n    },\n    {\n      attachedDeposit: \"550000000000000000000\",\n    }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  let bob_approval_id_is_3 = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: bob.accountId,\n    approval_id: \"3\",\n  });\n  t.assert(bob_approval_id_is_3);\n});\n\ntest(\"Approve call\", async (t) => {\n  const { nft, nftOwner, approvalReceiver } = t.context.accounts;\n\n  let res = await nftOwner.call(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: approvalReceiver.accountId,\n      msg: \"return-now\",\n    },\n    { attachedDeposit: \"610000000000000000000\", gas: \"300 Tgas\" }\n  );\n  t.is(res, \"cool\");\n\n  res = await nftOwner.call(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: approvalReceiver.accountId,\n      msg: \"hahaha\",\n    },\n    { attachedDeposit: \"1\", gas: \"300 Tgas\" }\n  );\n  t.is(res, \"hahaha\");\n});\n\ntest(\"Approved account transfers token\", async (t) => {\n  const { ali, nft, nftOwner } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: ali.accountId,\n    },\n    { attachedDeposit: \"510000000000000000000\" }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n\n  res = await ali.callRaw(\n    nft,\n    \"nft_transfer\",\n    {\n      receiver_id: ali.accountId,\n      token_id: \"0\",\n      memo: \"gotcha! bahahaha\",\n    },\n    { attachedDeposit: \"1\" }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, ali.accountId);\n});\n\ntest(\"revoke\", async (t) => {\n  const { ali, bob, nft, nftOwner } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: ali.accountId,\n    },\n    { attachedDeposit: \"510000000000000000000\" }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      account_id: bob.accountId,\n    },\n    {\n      attachedDeposit: \"510000000000000000000\",\n    }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_revoke\",\n    {\n      token_id: \"0\",\n      account_id: ali.accountId,\n    },\n    {\n      attachedDeposit: \"1\",\n    }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  let alice_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n  });\n  t.assert(!alice_approved);\n\n  let bob_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: bob.accountId,\n  });\n  t.assert(bob_approved);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_revoke\",\n    {\n      token_id: \"0\",\n      account_id: bob.accountId,\n    },\n    {\n      attachedDeposit: \"1\",\n    }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  alice_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n  });\n  t.assert(!alice_approved);\n\n  bob_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: bob.accountId,\n  });\n  t.assert(!bob_approved);\n});\n\ntest(\"revoke all\", async (t) => {\n  const { ali, bob, nft, nftOwner } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      accountId: ali.accountId,\n    },\n    { attachedDeposit: \"510000000000000000000\" }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_approve\",\n    {\n      token_id: \"0\",\n      accountId: bob.accountId,\n    },\n    {\n      attachedDeposit: \"510000000000000000000\",\n    }\n  );\n  t.assert(res.result.status.SuccessValue);\n\n  res = await nftOwner.callRaw(\n    nft,\n    \"nft_revoke_all\",\n    { token_id: \"0\" },\n    {\n      attachedDeposit: \"1\",\n    }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  let alice_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: ali.accountId,\n  });\n  t.assert(!alice_approved);\n\n  let bob_approved = await nft.view(\"nft_is_approved\", {\n    token_id: \"0\",\n    approved_account_id: bob.accountId,\n  });\n  t.assert(!bob_approved);\n});\n"
  },
  {
    "path": "examples/__tests__/standard-nft/test_core.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nconst MAX_GAS = 300_000_000_000_000n;\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy status-message the contract.\n  const nft = await root.devDeploy(\"./build/my-nft.wasm\");\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const nftOwner = await root.createSubAccount(\"owner\");\n  const nftReceiver = await root.devDeploy(\"./build/nft-receiver.wasm\");\n\n  await nft.call(nft, \"init\", {\n    owner_id: nftOwner.accountId,\n    metadata: { spec: \"nft-1.0.0\", name: \"My NFT\", symbol: \"NFT\" },\n  });\n\n  await nftReceiver.call(nftReceiver, \"init\", {\n    non_fungible_token_account_id: nft.accountId,\n  });\n\n  let token_metadata = {\n    title: \"Olympus Mons\",\n    description: \"The tallest mountain in the charted solar system\",\n    media: null,\n    media_hash: null,\n    copies: 1,\n    issued_at: null,\n    expires_at: null,\n    starts_at: null,\n    updated_at: null,\n    extra: null,\n    reference: null,\n    reference_hash: null,\n  };\n  await nftOwner.call(\n    nft,\n    \"nft_mint\",\n    {\n      token_id: \"0\",\n      token_owner_id: nftOwner.accountId,\n      token_metadata,\n    },\n    { attachedDeposit: \"10 mN\" }\n  );\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    nft,\n    ali,\n    bob,\n    nftOwner,\n    nftReceiver,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Simple transfer\", async (t) => {\n  const { ali, nft, nftOwner } = t.context.accounts;\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer\",\n    {\n      receiver_id: ali.accountId,\n      token_id: \"0\",\n      memo: \"simple transfer\",\n    },\n    { attachedDeposit: \"1\" }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  t.is(res.logs.length, 1);\n\n  token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, ali.accountId);\n});\n\ntest(\"Transfer call fast return to sender\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"return-it-now\",\n    },\n    { attachedDeposit: \"1\", gas: MAX_GAS }\n  );\n  t.is(\n    Buffer.from(res.result.status.SuccessValue, \"base64\").toString(),\n    \"false\"\n  );\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n});\n\ntest(\"Transfer call slow return to sender\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"return-it-later\",\n    },\n    { attachedDeposit: \"1\", gas: MAX_GAS }\n  );\n  t.is(\n    Buffer.from(res.result.status.SuccessValue, \"base64\").toString(),\n    \"false\"\n  );\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n});\n\ntest(\"Transfer call fast keep with sender\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"keep-it-now\",\n    },\n    { attachedDeposit: \"1\", gas: MAX_GAS }\n  );\n  t.is(\n    Buffer.from(res.result.status.SuccessValue, \"base64\").toString(),\n    \"true\"\n  );\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftReceiver.accountId);\n});\n\ntest(\"Transfer call slow keep with sender\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"keep-it-later\",\n    },\n    { attachedDeposit: \"1\", gas: MAX_GAS }\n  );\n  t.is(\n    Buffer.from(res.result.status.SuccessValue, \"base64\").toString(),\n    \"true\"\n  );\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftReceiver.accountId);\n});\n\ntest(\"Transfer call receiver panics\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"incorrect message\",\n    },\n    { attachedDeposit: \"1\", gas: MAX_GAS }\n  );\n  t.is(\n    Buffer.from(res.result.status.SuccessValue, \"base64\").toString(),\n    \"false\"\n  );\n\n  t.is(res.logs.length, 3);\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n});\n\ntest(\"Transfer call receiver panics and nft_resolve_transfer produces no log if not enough gas\", async (t) => {\n  const { nft, nftOwner, nftReceiver } = t.context.accounts;\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer_call\",\n    {\n      receiver_id: nftReceiver.accountId,\n      token_id: \"0\",\n      memo: \"transfer & call\",\n      msg: \"incorrect message\",\n    },\n    { attachedDeposit: \"1\", gas: 30_000_000_000_000n }\n  );\n  t.assert(res.result.status.Failure !== undefined);\n\n  t.is(res.logs.length, 0);\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n});\n\ntest(\"Simple transfer no logs on failure\", async (t) => {\n  const { nft, nftOwner } = t.context.accounts;\n\n  let token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n\n  // transfer to the current owner should fail and not print log\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer\",\n    {\n      receiver_id: nftOwner.accountId,\n      token_id: \"0\",\n      memo: \"simple transfer\",\n    },\n    { attachedDeposit: \"1\" }\n  );\n  t.assert(res.result.status.Failure !== undefined);\n\n  t.is(res.logs.length, 0);\n\n  token = await nft.view(\"nft_token\", { token_id: \"0\" });\n  t.is(token.owner_id, nftOwner.accountId);\n});\n"
  },
  {
    "path": "examples/__tests__/standard-nft/test_enumeration.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nasync function helper_mint(nft, nftOwner, id, title, description) {\n  let token_metadata = {\n    title,\n    description,\n    media: null,\n    media_hash: null,\n    copies: 1,\n    issued_at: null,\n    expires_at: null,\n    starts_at: null,\n    updated_at: null,\n    extra: null,\n    reference: null,\n    reference_hash: null,\n  };\n  await nftOwner.call(\n    nft,\n    \"nft_mint\",\n    {\n      token_id: id,\n      token_owner_id: nftOwner.accountId,\n      token_metadata,\n    },\n    { attachedDeposit: \"10 mN\" }\n  );\n}\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy status-message the contract.\n  const nft = await root.devDeploy(\"./build/my-nft.wasm\");\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const nftOwner = await root.createSubAccount(\"owner\");\n  const nftReceiver = await root.devDeploy(\"./build/nft-receiver.wasm\");\n\n  await nft.call(nft, \"init\", {\n    owner_id: nftOwner.accountId,\n    metadata: { spec: \"nft-1.0.0\", name: \"My NFT\", symbol: \"NFT\" },\n  });\n\n  await nftReceiver.call(nftReceiver, \"init\", {\n    non_fungible_token_account_id: nft.accountId,\n  });\n\n  await helper_mint(\n    nft,\n    nftOwner,\n    \"0\",\n    \"Olympus Mons\",\n    \"The tallest mountain in the charted solar system\"\n  );\n  await helper_mint(nft, nftOwner, \"1\", \"Black as the Night\", \"In charcoal\");\n  await helper_mint(nft, nftOwner, \"2\", \"Hamakua\", \"Vintage recording\");\n  await helper_mint(nft, nftOwner, \"3\", \"Aloha ke akua\", \"Original with piano\");\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    nft,\n    ali,\n    bob,\n    nftOwner,\n    nftReceiver,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Enumerate NFT tokens total supply\", async (t) => {\n  const { nft } = t.context.accounts;\n\n  let totalSupply = await nft.view(\"nft_total_supply\");\n  t.is(totalSupply, 4);\n});\n\ntest(\"Enumerate NFT tokens\", async (t) => {\n  const { nft } = t.context.accounts;\n\n  let nftTokens = await nft.view(\"nft_tokens\", { from_index: 1 });\n  t.is(nftTokens.length, 3);\n  t.is(nftTokens[0].token_id, \"1\");\n  t.is(nftTokens[1].token_id, \"2\");\n  t.is(nftTokens[2].token_id, \"3\");\n\n  nftTokens = await nft.view(\"nft_tokens\", { limit: 2 });\n  t.is(nftTokens.length, 2);\n  t.is(nftTokens[0].token_id, \"0\");\n  t.is(nftTokens[1].token_id, \"1\");\n});\n\ntest(\"Enumerate NFT tokens supply for owner\", async (t) => {\n  const { ali, nft, nftOwner } = t.context.accounts;\n\n  let aliNfts = await nft.view(\"nft_supply_for_owner\", {\n    account_id: ali.accountId,\n  });\n  t.is(aliNfts, 0);\n\n  let ownerNfts = await nft.view(\"nft_supply_for_owner\", {\n    account_id: nftOwner.accountId,\n  });\n  t.is(ownerNfts, 4);\n});\n\ntest(\"Enumerate NFT tokens for owner\", async (t) => {\n  const { ali, nft, nftOwner } = t.context.accounts;\n\n  let nftTokens = await nft.view(\"nft_tokens_for_owner\", {\n    account_id: nftOwner.accountId,\n  });\n  t.is(nftTokens.length, 4);\n  t.is(nftTokens[0].token_id, \"0\");\n  t.is(nftTokens[1].token_id, \"1\");\n  t.is(nftTokens[2].token_id, \"2\");\n  t.is(nftTokens[3].token_id, \"3\");\n\n  nftTokens = await nft.view(\"nft_tokens_for_owner\", {\n    account_id: nftOwner.accountId,\n    from_index: 1,\n  });\n  t.is(nftTokens.length, 3);\n  t.is(nftTokens[0].token_id, \"1\");\n  t.is(nftTokens[1].token_id, \"2\");\n  t.is(nftTokens[2].token_id, \"3\");\n\n  nftTokens = await nft.view(\"nft_tokens_for_owner\", {\n    account_id: nftOwner.accountId,\n    limit: 2,\n  });\n  t.is(nftTokens.length, 2);\n  t.is(nftTokens[0].token_id, \"0\");\n  t.is(nftTokens[1].token_id, \"1\");\n\n  let res = await nftOwner.callRaw(\n    nft,\n    \"nft_transfer\",\n    {\n      receiver_id: ali.accountId,\n      token_id: \"0\",\n      memo: \"simple transfer\",\n    },\n    { attachedDeposit: \"1\" }\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n\n  nftTokens = await nft.view(\"nft_tokens_for_owner\", {\n    account_id: ali.accountId,\n  });\n  t.is(nftTokens.length, 1);\n\n  nftTokens = await nft.view(\"nft_tokens_for_owner\", {\n    account_id: nftOwner.accountId,\n  });\n  t.is(nftTokens.length, 3);\n  t.is(nftTokens[0].token_id, \"3\");\n  t.is(nftTokens[1].token_id, \"1\");\n  t.is(nftTokens[2].token_id, \"2\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-basic-updates.ava.js",
    "content": "import {NEAR, Worker} from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n    const worker = await Worker.init();\n    const root = worker.rootAccount;\n    const contract = await root.devDeploy(\"./build/basic-updates-base.wasm\");\n\n    const ali = await root.createSubAccount(\"ali\");\n\n    t.context.worker = worker;\n    t.context.accounts = { root, contract, ali };\n});\n\ntest.afterEach.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"migration basic updates works\", async (t) => {\n    const { contract, ali } = t.context.accounts;\n\n    await ali.call(contract, \"add_message\", { text: \"hello\" }, { attachedDeposit: NEAR.parse(\"1 N\").toJSON() });\n    let message0 = await contract.view(\"get_message\", { index: 0 });\n    let payment0 = await contract.view(\"get_payment\", { index: 0 });\n    console.log(\"message0= \", message0,\" payment0=\", payment0)\n    t.assert(\n        message0.text === \"hello\" && message0.premium && message0.sender === ali.accountId\n    );\n    t.assert(payment0 == NEAR.parse(\"1 N\"));\n\n    await contract.deploy(\"./build/basic-updates-update.wasm\");\n    await ali.call(contract, \"migrateState\", {});\n\n    let messageUpdated0 = await contract.view(\"get_message\", { index: 0 });\n    console.log(\"messageUpdated0= \", messageUpdated0);\n    t.assert(\n        message0.text === messageUpdated0.text && message0.premium === messageUpdated0.premium && message0.sender === messageUpdated0.sender && payment0 == messageUpdated0.payment\n    );\n});\n"
  },
  {
    "path": "examples/__tests__/test-clean-state.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the clean-state contract.\n  const cleanState = await root.devDeploy(\"./build/clean-state.wasm\");\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    cleanState,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Clean state after storing\", async (t) => {\n  const { root, cleanState } = t.context.accounts;\n  await root.call(cleanState, \"put\", { key: \"1\", value: 1 });\n  const value1 = await cleanState.view(\"get\", { key: \"1\" });\n  t.is(value1, \"1\");\n  await cleanState.call(cleanState, \"clean\", { keys: [\"1\"] });\n  const value2 = await cleanState.view(\"get\", { key: \"1\" });\n  t.is(value2, null);\n});\n"
  },
  {
    "path": "examples/__tests__/test-counter.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etc.\n  const root = worker.rootAccount;\n\n  // Deploy the counter contract.\n  const counter = await root.devDeploy(\n    process.env[\"COUNTER_LOWLEVEL\"]\n      ? \"./build/counter-lowlevel.wasm\"\n      : process.env[\"COUNTER_TS\"]\n      ? \"./build/counter-ts.wasm\"\n      : \"./build/counter.wasm\"\n  );\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, counter, ali, bob };\n});\n\n// If the environment is reused, use test.after to replace test.afterEach\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Initial count is 0\", async (t) => {\n  const { counter } = t.context.accounts;\n  const result = await counter.view(\"getCount\", {});\n  t.is(result, 0);\n});\n\ntest(\"Increase works\", async (t) => {\n  const { counter, ali, bob } = t.context.accounts;\n  await ali.call(counter, \"increase\", {});\n\n  let result = await counter.view(\"getCount\", {});\n  t.is(result, 1);\n\n  await bob.call(counter, \"increase\", { n: 4 });\n  result = await counter.view(\"getCount\", {});\n  t.is(result, 5);\n});\n\ntest(\"Decrease works\", async (t) => {\n  const { counter, ali, bob } = t.context.accounts;\n  await ali.call(counter, \"decrease\", {});\n\n  let result = await counter.view(\"getCount\", {});\n  t.is(result, -1);\n\n  let dec = await bob.callRaw(counter, \"decrease\", { n: 4 });\n  // ensure imported log does work, not silent failure\n  t.is(\n    dec.result.receipts_outcome[0].outcome.logs[0],\n    \"Counter decreased to -5\"\n  );\n  result = await counter.view(\"getCount\", {});\n  t.is(result, -5);\n});\n"
  },
  {
    "path": "examples/__tests__/test-cross-contract-call-loop.ava.js",
    "content": "import { Worker, NEAR } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const xccLoop = await root.createSubAccount(\"xcc-loop\");\n  await xccLoop.deploy(\"./build/cross-contract-call-loop.wasm\");\n\n  const firstContract = await root.createSubAccount(\"first-contract\");\n  const secondContract = await root.createSubAccount(\"second-contract\");\n  const thirdContract = await root.createSubAccount(\"third-contract\");\n  await firstContract.deploy(\"./build/counter.wasm\");\n  await secondContract.deploy(\"./build/counter.wasm\");\n  await thirdContract.deploy(\"./build/counter.wasm\");\n\n  await root.call(firstContract, \"increase\", {});\n  await root.call(secondContract, \"increase\", {});\n  await root.call(thirdContract, \"increase\", {});\n\n  const alice = await root.createSubAccount(\"alice\", {\n    initialBalance: NEAR.parse(\"100 N\").toJSON(),\n  });\n\n  t.context.worker = worker;\n  t.context.accounts = { root, alice, xccLoop };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"should have a count of 3 after calling incrementCount\", async (t) => {\n  const { xccLoop, alice } = t.context.accounts;\n  const expected = 3;\n  const callbackResult = await alice.call(\n    xccLoop,\n    \"incrementCount\",\n    {},\n    { gas: \"300\" + \"0\".repeat(12) }\n  );\n  t.is(callbackResult, 3);\n  const result = await xccLoop.view(\"getCount\");\n  t.deepEqual(result, expected);\n});\n"
  },
  {
    "path": "examples/__tests__/test-cross-contract-call-ts.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy status-message the contract.\n  const statusMessage = await root.devDeploy(\"./build/status-message.wasm\");\n\n  // Deploy the onCall contract.\n  const onCall = await root.devDeploy(\"./build/cross-contract-call-ts.wasm\");\n\n  // Init the contract\n  await onCall.call(onCall, \"init\", {\n    statusMessageContract: statusMessage.accountId,\n  });\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    statusMessage,\n    onCall,\n    ali,\n    bob,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Nobody is on-call in the beginning\", async (t) => {\n  const { onCall } = t.context.accounts;\n  const result = await onCall.view(\"person_on_call\", {});\n  t.is(result, \"\");\n});\n\ntest(\"Person can be set on-call if AVAILABLE\", async (t) => {\n  const { ali, bob, onCall, statusMessage } = t.context.accounts;\n\n  // Ali set her status as AVAILABLE\n  await ali.call(statusMessage, \"set_status\", { message: \"AVAILABLE\" });\n  // Bob sets Ali on-call\n  await bob.call(\n    onCall,\n    \"set_person_on_call\",\n    { accountId: ali.accountId },\n    { gas: 120000000000000 }\n  );\n\n  // Check that Ali is on-call\n  t.is(await onCall.view(\"person_on_call\", {}), ali.accountId);\n});\n\ntest(\"Person can NOT be set on-call if UNAVAILABLE\", async (t) => {\n  const { ali, bob, onCall, statusMessage } = t.context.accounts;\n\n  // Ali set her status as AVAILABLE\n  await ali.call(statusMessage, \"set_status\", { message: \"UNAVAILABLE\" });\n  // Bob tries to sets Ali on-call\n  await bob.call(\n    onCall,\n    \"set_person_on_call\",\n    { accountId: ali.accountId },\n    { gas: 120000000000000 }\n  );\n\n  // Check that Ali is NOT on-call\n  t.not(await onCall.view(\"person_on_call\", {}), ali.accountId);\n});\n"
  },
  {
    "path": "examples/__tests__/test-cross-contract-call.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy status-message the contract.\n  const statusMessage = await root.devDeploy(\"./build/status-message.wasm\");\n\n  // Deploy the onCall contract.\n  const onCall = await root.devDeploy(\"./build/cross-contract-call.wasm\");\n\n  // Init the contract\n  await onCall.call(onCall, \"init\", {\n    statusMessageContract: statusMessage.accountId,\n  });\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    statusMessage,\n    onCall,\n    ali,\n    bob,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Nobody is on-call in the beginning\", async (t) => {\n  const { onCall } = t.context.accounts;\n  const result = await onCall.view(\"person_on_call\", {});\n  t.is(result, \"undefined\");\n});\n\ntest(\"Person can be set on-call if AVAILABLE\", async (t) => {\n  const { ali, bob, onCall, statusMessage } = t.context.accounts;\n\n  // Ali set her status as AVAILABLE\n  await ali.call(statusMessage, \"set_status\", { message: \"AVAILABLE\" });\n  // Bob sets Ali on-call\n  await bob.call(\n    onCall,\n    \"set_person_on_call\",\n    { accountId: ali.accountId },\n    { gas: 120000000000000 }\n  );\n\n  // Check that Ali is on-call\n  t.is(await onCall.view(\"person_on_call\", {}), ali.accountId);\n});\n\ntest(\"Person can NOT be set on-call if UNAVAILABLE\", async (t) => {\n  const { ali, bob, onCall, statusMessage } = t.context.accounts;\n\n  // Ali set her status as AVAILABLE\n  await ali.call(statusMessage, \"set_status\", { message: \"UNAVAILABLE\" });\n  // Bob tries to sets Ali on-call\n  await bob.call(\n    onCall,\n    \"set_person_on_call\",\n    { accountId: ali.accountId },\n    { gas: 120000000000000 }\n  );\n\n  // Check that Ali is NOT on-call\n  t.not(await onCall.view(\"person_on_call\", {}), ali.accountId);\n});\n"
  },
  {
    "path": "examples/__tests__/test-fungible-token-lockable.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the lockable-ft contract.\n  const lockableFt = await root.devDeploy(\n    \"./build/fungible-token-lockable.wasm\"\n  );\n\n  // Init the contract\n  await lockableFt.call(lockableFt, \"init\", {\n    prefix: \"prefix\",\n    totalSupply: 10000,\n  });\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, lockableFt, ali, bob };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Owner initial details\", async (t) => {\n  const { lockableFt } = t.context.accounts;\n  const totalSupply = await lockableFt.view(\"getTotalSupply\", {});\n  t.is(totalSupply, 10000);\n  const totalBalance = await lockableFt.view(\"getTotalBalance\", {\n    ownerId: lockableFt.accountId,\n  });\n  t.is(totalBalance, 10000);\n  const unlockedBalance = await lockableFt.view(\"getUnlockedBalance\", {\n    ownerId: lockableFt.accountId,\n  });\n  t.is(unlockedBalance, 10000);\n  const allowance = await lockableFt.view(\"getAllowance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(allowance, 0);\n  const lockedBalance = await lockableFt.view(\"getLockedBalance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(lockedBalance, 0);\n});\n\ntest(\"Set allowance\", async (t) => {\n  const { lockableFt, ali } = t.context.accounts;\n  await lockableFt.call(lockableFt, \"setAllowance\", {\n    escrowAccountId: ali.accountId,\n    allowance: 100,\n  });\n  const aliAllowance = await lockableFt.view(\"getAllowance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: ali.accountId,\n  });\n  t.is(aliAllowance, 100);\n  const contractAllowance = await lockableFt.view(\"getAllowance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(contractAllowance, 0);\n});\n\ntest(\"Fail to set allowance for oneself\", async (t) => {\n  const { lockableFt } = t.context.accounts;\n  const error = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"setAllowance\", {\n      escrowAccountId: lockableFt.accountId,\n      allowance: 100,\n    })\n  );\n  t.assert(error.message.includes(`Can't set allowance for yourself`));\n});\n\ntest(\"Lock owner\", async (t) => {\n  const { lockableFt } = t.context.accounts;\n  await lockableFt.call(lockableFt, \"lock\", {\n    ownerId: lockableFt.accountId,\n    lockAmount: 100,\n  });\n  const unlockedBalance = await lockableFt.view(\"getUnlockedBalance\", {\n    ownerId: lockableFt.accountId,\n  });\n  t.is(unlockedBalance, 9900);\n  const allowance = await lockableFt.view(\"getAllowance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(allowance, 0);\n  const lockedBalance = await lockableFt.view(\"getLockedBalance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(lockedBalance, 100);\n});\n\ntest(\"Lock failures\", async (t) => {\n  const { lockableFt, ali } = t.context.accounts;\n  const error1 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"lock\", {\n      ownerId: lockableFt.accountId,\n      lockAmount: 0,\n    })\n  );\n  t.assert(error1.message.includes(`Can't lock 0 or less tokens`));\n\n  const error2 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"lock\", {\n      ownerId: lockableFt.accountId,\n      lockAmount: 10001,\n    })\n  );\n  t.assert(error2.message.includes(`Not enough unlocked balance`));\n\n  const error3 = await t.throwsAsync(() =>\n    ali.call(lockableFt, \"lock\", {\n      ownerId: lockableFt.accountId,\n      lockAmount: 10,\n    })\n  );\n  t.assert(error3.message.includes(`Not enough allowance`));\n});\n\ntest(\"Unlock owner\", async (t) => {\n  const { lockableFt } = t.context.accounts;\n  await lockableFt.call(lockableFt, \"lock\", {\n    ownerId: lockableFt.accountId,\n    lockAmount: 100,\n  });\n  await lockableFt.call(lockableFt, \"unlock\", {\n    ownerId: lockableFt.accountId,\n    unlockAmount: 100,\n  });\n  const unlockedBalance = await lockableFt.view(\"getUnlockedBalance\", {\n    ownerId: lockableFt.accountId,\n  });\n  t.is(unlockedBalance, 10000);\n  const allowance = await lockableFt.view(\"getAllowance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(allowance, 0);\n  const lockedBalance = await lockableFt.view(\"getLockedBalance\", {\n    ownerId: lockableFt.accountId,\n    escrowAccountId: lockableFt.accountId,\n  });\n  t.is(lockedBalance, 0);\n});\n\ntest(\"Unlock failures\", async (t) => {\n  const { lockableFt } = t.context.accounts;\n  const error1 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"unlock\", {\n      ownerId: lockableFt.accountId,\n      unlockAmount: 0,\n    })\n  );\n  t.assert(error1.message.includes(`Can't unlock 0 or less tokens`));\n\n  const error2 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"unlock\", {\n      ownerId: lockableFt.accountId,\n      unlockAmount: 1,\n    })\n  );\n  t.assert(error2.message.includes(`Not enough locked tokens`));\n});\n\ntest(\"Simple transfer\", async (t) => {\n  const { lockableFt, ali } = t.context.accounts;\n  await lockableFt.call(lockableFt, \"transfer\", {\n    newOwnerId: ali.accountId,\n    amount: 100,\n  });\n  const ownerUnlockedBalance = await lockableFt.view(\"getUnlockedBalance\", {\n    ownerId: lockableFt.accountId,\n  });\n  t.is(ownerUnlockedBalance, 9900);\n  const aliUnlockedBalance = await lockableFt.view(\"getUnlockedBalance\", {\n    ownerId: ali.accountId,\n  });\n  t.is(aliUnlockedBalance, 100);\n});\n\ntest(\"Transfer failures\", async (t) => {\n  const { lockableFt, ali } = t.context.accounts;\n  const error1 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"transfer\", {\n      newOwnerId: ali.accountId,\n      amount: 0,\n    })\n  );\n  t.assert(error1.message.includes(`Can't transfer 0 or less tokens`));\n\n  const error2 = await t.throwsAsync(() =>\n    lockableFt.call(lockableFt, \"transfer\", {\n      newOwnerId: ali.accountId,\n      amount: 10001,\n    })\n  );\n  t.assert(error2.message.includes(`Not enough unlocked balance`));\n});\n"
  },
  {
    "path": "examples/__tests__/test-fungible-token.ava.js",
    "content": "import { Worker, NEAR } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n\n  const totalSupply = 1000;\n  const yoctoAccountStorage = \"90\";\n\n  const root = worker.rootAccount;\n  const xcc = await root.devDeploy(\"./build/fungible-token-helper.wasm\");\n  const ft = await root.createSubAccount(\"ft\");\n  await ft.deploy(\"./build/fungible-token.wasm\");\n  await root.call(ft, \"init\", {\n    owner_id: root.accountId,\n    total_supply: totalSupply.toString(),\n  });\n  const alice = await root.createSubAccount(\"alice\", {\n    initialBalance: NEAR.parse(\"10 N\").toJSON(),\n  });\n\n  t.context.worker = worker;\n  t.context.accounts = { root, ft, alice, xcc };\n  t.context.variables = { totalSupply, yoctoAccountStorage };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"should register account and pay for storage\", async (t) => {\n  const { ft, alice } = t.context.accounts;\n  const { yoctoAccountStorage } = t.context.variables;\n  const result = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  const aliceAfterBalance = await alice.balance();\n  const expected = {\n    message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,\n  };\n  t.deepEqual(result, expected);\n  t.true(\n    aliceAfterBalance.total > NEAR.parse(\"9 N\").toJSON(),\n    \"alice should have received a refund\"\n  );\n});\n\ntest(\"should return message when account is already registered and not refund when no deposit is attached\", async (t) => {\n  const { ft, alice } = t.context.accounts;\n  const { yoctoAccountStorage } = t.context.variables;\n  const result = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  const expected = {\n    message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,\n  };\n  t.deepEqual(result, expected);\n  const result2 = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"0 N\").toJSON() }\n  );\n  t.is(result2.message, \"Account is already registered\");\n});\n\ntest(\"should return message and refund predecessor caller when trying to pay for storage for an account that is already registered\", async (t) => {\n  const { ft, alice } = t.context.accounts;\n  const { yoctoAccountStorage } = t.context.variables;\n  const result = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  const expected = {\n    message: `Account ${alice.accountId} registered with storage deposit of ${yoctoAccountStorage}`,\n  };\n  t.deepEqual(result, expected);\n  const result2 = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  t.is(\n    result2.message,\n    \"Account is already registered, deposit refunded to predecessor\"\n  );\n  const aliceBalance = await alice.balance();\n  t.is(\n    aliceBalance.total > NEAR.parse(\"9 N\"),\n    true,\n    \"alice should have received a refund\"\n  );\n});\n\ntest(\"should return message when trying to pay for storage with less than the required amount and refund predecessor caller\", async (t) => {\n  const { ft, alice } = t.context.accounts;\n  const { yoctoAccountStorage } = t.context.variables;\n  const result = await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.from(\"40\").toJSON() }\n  );\n  t.is(\n    result.message,\n    `Not enough attached deposit to cover storage cost. Required: ${yoctoAccountStorage}`\n  );\n});\n\ntest(\"should throw when trying to transfer for an unregistered account\", async (t) => {\n  const { ft, alice, root } = t.context.accounts;\n  try {\n    await root.call(\n      ft,\n      \"ft_transfer\",\n      { receiver_id: alice.accountId, amount: \"1\" },\n      { attachedDeposit: NEAR.from(\"1\").toJSON() }\n    );\n  } catch (error) {\n    t.true(\n      error.message.includes(`Account ${alice.accountId} is not registered`)\n    );\n  }\n});\n\ntest(\"Owner has all balance in the beginning\", async (t) => {\n  const { ft, root } = t.context.accounts;\n  const result = await ft.view(\"ft_balance_of\", { account_id: root.accountId });\n  t.is(result, \"1000\");\n});\n\ntest(\"Can transfer if balance is sufficient\", async (t) => {\n  const { alice, ft, root } = t.context.accounts;\n  await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  await root.call(\n    ft,\n    \"ft_transfer\",\n    { receiver_id: alice.accountId, amount: \"100\" },\n    { attachedDeposit: NEAR.from(\"1\").toJSON() }\n  );\n  const aliBalance = await ft.view(\"ft_balance_of\", {\n    account_id: alice.accountId,\n  });\n  t.is(aliBalance, \"100\");\n  const ownerBalance = await ft.view(\"ft_balance_of\", {\n    account_id: root.accountId,\n  });\n  t.is(ownerBalance, \"900\");\n});\n\ntest(\"Cannot transfer if balance is not sufficient\", async (t) => {\n  const { alice, root, ft } = t.context.accounts;\n  await alice.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: alice.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  try {\n    await alice.call(\n      ft,\n      \"ft_transfer\",\n      {\n        receiverId: root.accountId,\n        amount: \"100\",\n      },\n      { attachedDeposit: NEAR.from(\"1\").toJSON() }\n    );\n  } catch (e) {\n    t.assert(\n      e\n        .toString()\n        .indexOf(\n          \"Smart contract panicked: assertion failed: The account doesn't have enough balance\"\n        ) >= 0\n    );\n  }\n});\n\ntest(\"Cross contract transfer\", async (t) => {\n  const { xcc, ft, root } = t.context.accounts;\n  await xcc.call(\n    ft,\n    \"storage_deposit\",\n    { account_id: xcc.accountId },\n    { attachedDeposit: NEAR.parse(\"1 N\").toJSON() }\n  );\n  await root.call(\n    ft,\n    \"ft_transfer_call\",\n    { receiver_id: xcc.accountId, amount: \"900\", memo: null, msg: \"test msg\" },\n    { gas: 200000000000000, attachedDeposit: NEAR.from(\"1\").toJSON() }\n  );\n  const xccBalance = await ft.view(\"ft_balance_of\", {\n    account_id: xcc.accountId,\n  });\n  t.is(xccBalance, \"900\");\n  const aliSubContractData = await xcc.view(\"get_contract_data\");\n  t.is(\n    aliSubContractData,\n    `[900 from ${root.accountId} to ${xcc.accountId}] test msg `\n  );\n  const ownerBalance = await ft.view(\"ft_balance_of\", {\n    account_id: root.accountId,\n  });\n  t.is(ownerBalance, \"100\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-nested-collections.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the contract.\n  const nestedCollections = await root.devDeploy(\n    \"./build/nested-collections.wasm\"\n  );\n\n  // Create test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, nestedCollections, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Ali sets then gets text\", async (t) => {\n  const { ali, nestedCollections } = t.context.accounts;\n  await ali.call(nestedCollections, \"add\", { id: \"1\", text: \"hello\" });\n  await ali.call(nestedCollections, \"add\", { id: \"2\", text: \"world\" });\n\n  t.is(\n    await nestedCollections.view(\"get\", { id: \"1\", accountId: ali.accountId }),\n    \"hello\"\n  );\n\n  t.is(\n    await nestedCollections.view(\"get\", { id: \"2\", accountId: ali.accountId }),\n    \"world\"\n  );\n});\n\ntest(\"Bob and Carl have different statuses\", async (t) => {\n  const { nestedCollections, bob, carl } = t.context.accounts;\n  await bob.call(nestedCollections, \"add\", { id: \"1\", text: \"hello\" });\n  await carl.call(nestedCollections, \"add\", { id: \"1\", text: \"world\" });\n\n  t.is(\n    await nestedCollections.view(\"get\", { id: \"1\", accountId: bob.accountId }),\n    \"hello\"\n  );\n\n  t.is(\n    await nestedCollections.view(\"get\", { id: \"1\", accountId: carl.accountId }),\n    \"world\"\n  );\n});\n\ntest(\"sets then gets nested nested collection\", async (t) => {\n  const { ali, bob, nestedCollections } = t.context.accounts;\n  await ali.call(nestedCollections, \"add_to_group\", {\n    group: \"x\",\n    id: \"1\",\n    text: \"hello\",\n  });\n  await ali.call(nestedCollections, \"add_to_group\", {\n    group: \"x\",\n    id: \"2\",\n    text: \"world\",\n  });\n  await ali.call(nestedCollections, \"add_to_group\", {\n    group: \"y\",\n    id: \"2\",\n    text: \"cat\",\n  });\n  await bob.call(nestedCollections, \"add_to_group\", {\n    group: \"y\",\n    id: \"2\",\n    text: \"dog\",\n  });\n\n  t.is(\n    await nestedCollections.view(\"get_from_group\", {\n      group: \"x\",\n      id: \"1\",\n      accountId: ali.accountId,\n    }),\n    \"hello\"\n  );\n\n  t.is(\n    await nestedCollections.view(\"get_from_group\", {\n      group: \"x\",\n      id: \"2\",\n      accountId: ali.accountId,\n    }),\n    \"world\"\n  );\n\n  t.is(\n    await nestedCollections.view(\"get_from_group\", {\n      group: \"y\",\n      id: \"2\",\n      accountId: ali.accountId,\n    }),\n    \"cat\"\n  );\n\n  t.is(\n    await nestedCollections.view(\"get_from_group\", {\n      group: \"y\",\n      id: \"2\",\n      accountId: bob.accountId,\n    }),\n    \"dog\"\n  );\n});\n"
  },
  {
    "path": "examples/__tests__/test-non-fungible-token.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the nft contract.\n  const nft = await root.devDeploy(\"./build/non-fungible-token.wasm\");\n\n  // Init the contract\n  await nft.call(nft, \"init\", {\n    owner_id: nft.accountId,\n    owner_by_id_prefix: \"a\",\n  });\n\n  // Deploy the tokenReceiver contract.\n  const tokenReceiver = await root.devDeploy(\n    \"./build/non-fungible-token-receiver.wasm\"\n  );\n\n  // Init the contract\n  await tokenReceiver.call(tokenReceiver, \"init\", {\n    nonFungibleTokenAccountId: nft.accountId,\n  });\n\n  // Mint an NFT\n  let tokenId = \"my-cool-nft\";\n  await nft.call(nft, \"nftMint\", {\n    token_id: tokenId,\n    token_owner_id: nft.accountId,\n  });\n\n  // Create test accounts\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs, it is unique for each test\n  t.context.worker = worker;\n  t.context.accounts = { root, nft, tokenReceiver, tokenId, ali, bob };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed tear down the worker:\", error);\n  });\n});\n\ntest(\"Owner has the NFT in the beginning\", async (t) => {\n  const { nft, tokenId } = t.context.accounts;\n  const result = await nft.view(\"nftToken\", { token_id: tokenId });\n  t.deepEqual(result, { owner_id: nft.accountId, token_id: tokenId });\n});\n\ntest(\"Simple transfer\", async (t) => {\n  const { nft, tokenId, ali } = t.context.accounts;\n  await nft.call(nft, \"nftTransfer\", {\n    receiver_id: ali.accountId,\n    token_id: tokenId,\n  });\n  const result = await nft.view(\"nftToken\", { token_id: tokenId });\n  t.deepEqual(result, { owner_id: ali.accountId, token_id: tokenId });\n});\n\ntest(\"Transfer failures\", async (t) => {\n  const { nft, tokenId, ali } = t.context.accounts;\n  const error1 = await t.throwsAsync(() =>\n    ali.call(nft, \"nftTransfer\", {\n      receiver_id: nft.accountId,\n      token_id: \"non-existent-id\",\n    })\n  );\n  t.assert(error1.message.includes(`Token not found`));\n\n  const error2 = await t.throwsAsync(() =>\n    ali.call(nft, \"nftTransfer\", {\n      receiver_id: nft.accountId,\n      token_id: tokenId,\n    })\n  );\n  t.assert(error2.message.includes(`Sender must be the current owner`));\n\n  const error3 = await t.throwsAsync(() =>\n    nft.call(nft, \"nftTransfer\", {\n      receiver_id: nft.accountId,\n      token_id: tokenId,\n    })\n  );\n  t.assert(error3.message.includes(`Current and next owner must differ`));\n});\n\ntest(\"Transfer call where receiver returns the token\", async (t) => {\n  const { nft, tokenReceiver, tokenId } = t.context.accounts;\n  await nft.call(\n    nft,\n    \"nftTransferCall\",\n    {\n      receiver_id: tokenReceiver.accountId,\n      token_id: tokenId,\n      approval_id: null,\n      memo: null,\n      msg: \"return-it-now\",\n    },\n    { gas: \"120000000000000\" }\n  );\n  const result = await nft.view(\"nftToken\", { token_id: tokenId });\n  t.deepEqual(result, { owner_id: nft.accountId, token_id: tokenId });\n});\n\ntest(\"Transfer call where receiver keeps the token\", async (t) => {\n  const { nft, tokenReceiver, tokenId } = t.context.accounts;\n  await nft.call(\n    nft,\n    \"nftTransferCall\",\n    {\n      receiver_id: tokenReceiver.accountId,\n      token_id: tokenId,\n      approval_id: null,\n      memo: null,\n      msg: \"keep-it-now\",\n    },\n    { gas: \"120000000000000\" }\n  );\n  const result = await nft.view(\"nftToken\", { token_id: tokenId });\n  t.deepEqual(result, { owner_id: tokenReceiver.accountId, token_id: tokenId });\n});\n"
  },
  {
    "path": "examples/__tests__/test-parking-lot.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const parkingLot = await root.devDeploy(\"build/parking-lot.wasm\");\n\n  const ali = await root.createSubAccount(\"ali\");\n\n  t.context.worker = worker;\n  t.context.accounts = { root, parkingLot, ali };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"No BMW in the beginning\", async (t) => {\n  const { parkingLot } = t.context.accounts;\n\n  t.is(await parkingLot.view(\"getCarSpecs\", { name: \"BMW\" }), null);\n});\n\ntest(\"Can run the car after adding it\", async (t) => {\n  const { ali, parkingLot } = t.context.accounts;\n\n  const bmwSpecs = {\n    id: 1,\n    color: \"Black\",\n    price: 100500,\n    engineHp: 500,\n  };\n\n  await ali.call(parkingLot, \"addCar\", {\n    name: \"BMW\",\n    ...bmwSpecs,\n  });\n\n  t.is(await parkingLot.view(\"runCar\", { name: \"BMW\" }), \"boom\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-programmatic-update.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const ali = await root.createSubAccount(\"ali\");\n\n  const contract = await root.devDeploy(\n    \"build/programmatic-update-before.wasm\"\n  );\n\n  await contract.call(contract, \"init\", { manager: ali.accountId });\n\n  t.context.worker = worker;\n  t.context.accounts = { root, contract, ali };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"the contract can be programmatically updated\", async (t) => {\n  const { ali, contract } = t.context.accounts;\n\n  // ASSERT BEFORE CODE UPDATE\n  const codeBefore = await contract.viewCodeRaw();\n  const beforeDefaultGreeting = await contract.view(\"get_greeting\", {});\n  t.is(beforeDefaultGreeting, \"Hello\");\n\n  // ACT (UPDATE CODE)\n  const code = fs.readFileSync(\n    path.resolve(\"./build/programmatic-update-after.wasm\")\n  );\n  await ali.call(contract, \"updateContract\", code, {\n    gas: \"300\" + \"0\".repeat(12), // 300 Tgas\n  });\n\n  // ASSERT AFTER CODE UPDATE\n  const codeAfter = await contract.viewCodeRaw();\n  const afterDefaultGreeting = await contract.view(\"view_greeting\", {});\n  t.not(codeBefore, codeAfter, \"code should be different after update\");\n  t.is(afterDefaultGreeting, \"Hi\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-state-message-migration-add-filed.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n    const worker = await Worker.init();\n    const root = worker.rootAccount;\n    const contract = await root.devDeploy(\"./build/status-message.wasm\");\n\n    const ali = await root.createSubAccount(\"ali\");\n\n    t.context.worker = worker;\n    t.context.accounts = { root, contract, ali };\n});\n\ntest.afterEach.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"migration works\", async (t) => {\n    const { contract, ali } = t.context.accounts;\n\n    await ali.call(contract, \"set_status\", { message: \"hello\" });\n    t.is(\n        await contract.view(\"get_status\", { account_id: ali.accountId }),\n        \"hello\"\n    );\n\n    await contract.deploy(\"./build/status-message-migrate-add-field.wasm\");\n    await ali.call(contract, \"migrateState\", {});\n\n    t.is(\n        await contract.view(\"get_status\", { account_id: ali.accountId }),\n        \"hello\"\n    );\n\n    await ali.call(contract, \"set_new_status\", { message: \"hello\" });\n    t.is(\n        await contract.view(\"get_new_status\", { account_id: ali.accountId }),\n        \"hello\"\n    );\n});\n"
  },
  {
    "path": "examples/__tests__/test-state-migration.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n    const worker = await Worker.init();\n    const root = worker.rootAccount;\n    const contract = await root.devDeploy(\"./build/state-migration-original.wasm\");\n\n    const ali = await root.createSubAccount(\"ali\");\n\n    t.context.worker = worker;\n    t.context.accounts = { root, contract, ali };\n});\n\ntest.afterEach.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"migration works\", async (t) => {\n    const { contract, ali } = t.context.accounts;\n\n    await ali.call(contract, \"addMessage\", { message: { sender: \"ali\", header: \"h1\", text: \"hello\" } });\n    await ali.call(contract, \"addMessage\", { message: { sender: \"ali\", header: \"h2\", text: \"world\" } });\n    await ali.call(contract, \"addMessage\", { message: { sender: \"ali\", header: \"h3\", text: \"This message is too log for new standard\" } });\n    await ali.call(contract, \"addMessage\", { message: { sender: \"ali\", header: \"h4\", text: \"!\" } });\n\n    const res1 = await contract.view(\"countMessages\", {});\n    t.is(res1, 4);\n\n    await contract.deploy(\"./build/state-migration-new.wasm\");\n\n    await ali.call(contract, \"migrateState\", {});\n\n    const res2 = await contract.view(\"countMessages\", {});\n    t.is(res2, 3);\n});\n"
  },
  {
    "path": "examples/__tests__/test-status-deserialize-class.ava.js",
    "content": "import {Worker} from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the contract.\n  const statusMessage = await root.devDeploy(\"./build/status-deserialize-class.wasm\");\n\n  await root.call(statusMessage, \"init_contract\", {});\n  const result = await statusMessage.view(\"is_contract_inited\", {});\n  t.is(result, true);\n\n  // Create test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Ali sets then gets status\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_record\", { message: \"hello\" });\n\n  t.is(\n    await statusMessage.view(\"get_record\", { account_id: ali.accountId }),\n    \"hello\"\n  );\n});\n\ntest(\"Ali set_truck_info and get_truck_info\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  let carName = \"Mercedes-Benz\";\n  let speed = 240;\n  await ali.call(statusMessage, \"set_truck_info\", { name: carName, speed: speed });\n\n  await ali.call(statusMessage, \"add_truck_load\", { name: \"alice\", load: \"a box\" });\n  await ali.call(statusMessage, \"add_truck_load\", { name: \"bob\", load: \"a packet\" });\n\n  t.is(\n      await statusMessage.view(\"get_truck_info\", { }),\n      carName + \" run with speed \" + speed + \" with loads length: 2\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_user_car_info\", { account_id: ali.accountId }),\n      carName + \" run with speed \" + speed\n  );\n});\n\ntest(\"Ali push_message and get_messages\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  let message1 = 'Hello';\n  let message2 = 'World';\n  await ali.call(statusMessage, \"push_message\", { message: message1 });\n  await ali.call(statusMessage, \"push_message\", { message: message2 });\n\n  t.is(\n      await statusMessage.view(\"get_messages\", { }),\n      'Hello,World'\n  );\n});\n\ntest(\"Ali set_nested_efficient_recordes then get_nested_efficient_recordes text\", async (t) => {\n  const { ali, bob, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_nested_efficient_recordes\", { id: \"1\", message: \"hello\" }, { gas: 35_000_000_000_000n });\n  await bob.call(statusMessage, \"set_nested_efficient_recordes\", { id: \"1\", message: \"hello\" }, { gas: 35_000_000_000_000n });\n  await bob.call(statusMessage, \"set_nested_efficient_recordes\", { id: \"2\", message: \"world\" }, { gas: 35_000_000_000_000n });\n\n  t.is(\n      await statusMessage.view(\"get_efficient_recordes\", { account_id: ali.accountId }),\n      \"hello\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_nested_efficient_recordes\", { id: \"1\", account_id: bob.accountId }),\n      \"hello\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_nested_efficient_recordes\", { id: \"2\", account_id: bob.accountId }),\n      \"world\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_nested_lookup_recordes\", { id: \"1\", account_id: bob.accountId }),\n      \"hello\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_nested_lookup_recordes\", { id: \"2\", account_id: bob.accountId }),\n      \"world\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_vector_nested_group\", { idx: 0, account_id: bob.accountId }),\n      \"world\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_lookup_nested_vec\", { account_id: bob.accountId, idx: 1 }),\n      \"world\"\n  );\n\n  t.is(\n      await statusMessage.view(\"get_is_contains_user\", { account_id: bob.accountId}),\n      true\n  );\n});\n\ntest(\"Ali set_big_num_and_date then gets\", async (t) => {\n  const { ali, bob, statusMessage } = t.context.accounts;\n  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') });\n\n\n  const afterSetNum = await statusMessage.view(\"get_big_num\", { });\n  t.is(afterSetNum, `${10n}`);\n  const afterSetDate =  await statusMessage.view(\"get_date\", { });\n  t.is(afterSetDate.toString(), '2023-08-19T23:15:30.000Z');\n});\n\ntest(\"Ali set_extra_data without schema defined then gets\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_extra_data\", { message: \"Hello world!\", number: 100 });\n\n  const messageWithoutSchemaDefined = await statusMessage.view(\"get_extra_msg\", { });\n  t.is(messageWithoutSchemaDefined, \"Hello world!\");\n  const numberWithoutSchemaDefined =  await statusMessage.view(\"get_extra_number\", { });\n  t.is(numberWithoutSchemaDefined, 100);\n});\n\ntest(\"Ali set_extra_record without schema defined then gets\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_extra_record\", { message: \"Hello world!\"});\n\n  const recordWithoutSchemaDefined = await statusMessage.view(\"get_extra_record\", { account_id: ali.accountId });\n  t.is(recordWithoutSchemaDefined, \"Hello world!\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-status-message-borsh.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n    // Init the worker and start a Sandbox server\n    const worker = await Worker.init();\n\n    // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n    const root = worker.rootAccount;\n\n    // Deploy the contract.\n    const statusMessage = await root.devDeploy(\"./build/status-message-borsh.wasm\");\n\n    // Create test users\n    const ali = await root.createSubAccount(\"ali\");\n    const bob = await root.createSubAccount(\"bob\");\n    const carl = await root.createSubAccount(\"carl\");\n\n    // Save state for test runs\n    t.context.worker = worker;\n    t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"Root gets null status\", async (t) => {\n    const { statusMessage, root } = t.context.accounts;\n    const result = await statusMessage.view(\"get_status\", {\n        account_id: root.accountId,\n    });\n    t.is(result, null);\n});\n\ntest(\"Ali sets then gets status\", async (t) => {\n    const { ali, statusMessage } = t.context.accounts;\n    await ali.call(statusMessage, \"set_status\", { message: \"hello\" });\n\n    t.is(\n        await statusMessage.view(\"get_status\", { account_id: ali.accountId }),\n        \"hello\"\n    );\n});\n\ntest(\"Bob and Carl have different statuses\", async (t) => {\n    const { statusMessage, bob, carl } = t.context.accounts;\n    await bob.call(statusMessage, \"set_status\", { message: \"hello\" });\n    await carl.call(statusMessage, \"set_status\", { message: \"world\" });\n\n    const bobStatus = await statusMessage.view(\"get_status\", {\n        account_id: bob.accountId,\n    });\n    const carlStatus = await statusMessage.view(\"get_status\", {\n        account_id: carl.accountId,\n    });\n    t.is(bobStatus, \"hello\");\n    t.is(carlStatus, \"world\");\n});\n"
  },
  {
    "path": "examples/__tests__/test-status-message-collections.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the statis-message contract.\n  const statusMessage = await root.devDeploy(\n    \"./build/status-message-collections.wasm\"\n  );\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Root gets null status\", async (t) => {\n  const { root, statusMessage } = t.context.accounts;\n  const result = await statusMessage.view(\"get_status\", {\n    account_id: root.accountId,\n  });\n  t.is(result, null);\n});\n\ntest(\"Ali sets then gets status\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_status\", { message: \"hello\" });\n\n  t.is(\n    await statusMessage.view(\"get_status\", { account_id: ali.accountId }),\n    \"hello\"\n  );\n});\n\ntest(\"Bob and Carl have different statuses\", async (t) => {\n  const { statusMessage, bob, carl } = t.context.accounts;\n  await bob.call(statusMessage, \"set_status\", { message: \"hello\" });\n  await carl.call(statusMessage, \"set_status\", { message: \"world\" });\n\n  const bobStatus = await statusMessage.view(\"get_status\", {\n    account_id: bob.accountId,\n  });\n  const carlStatus = await statusMessage.view(\"get_status\", {\n    account_id: carl.accountId,\n  });\n  t.is(bobStatus, \"hello\");\n  t.is(carlStatus, \"world\");\n});\n\ntest(\"Get statuses from the contract\", async (t) => {\n  const { statusMessage, bob, carl } = t.context.accounts;\n  await bob.call(statusMessage, \"set_status\", { message: \"hello\" });\n  await carl.call(statusMessage, \"set_status\", { message: \"world\" });\n\n  const statuses = await statusMessage.view(\"get_all_statuses\", {});\n  t.deepEqual(statuses, [\n    [bob.accountId, \"hello\"],\n    [carl.accountId, \"world\"],\n  ]);\n});\n\ntest(\"message has stored by someone\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_status\", { message: \"hello\" });\n\n  t.is(await statusMessage.view(\"has_status\", { message: \"hello\" }), true);\n\n  t.is(await statusMessage.view(\"has_status\", { message: \"world\" }), false);\n});\n"
  },
  {
    "path": "examples/__tests__/test-status-message-deserialize-err.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n    // Init the worker and start a Sandbox server\n    const worker = await Worker.init();\n\n    // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n    const root = worker.rootAccount;\n\n    // Deploy the contract.\n    const statusMessage = await root.devDeploy(\"./build/status-message-deserialize-err.wasm\");\n\n    // Create test users\n    const ali = await root.createSubAccount(\"ali\");\n    const bob = await root.createSubAccount(\"bob\");\n    const carl = await root.createSubAccount(\"carl\");\n\n    // Save state for test runs\n    t.context.worker = worker;\n    t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"Root gets null status\", async (t) => {\n    const { statusMessage, root } = t.context.accounts;\n    const result = await statusMessage.view(\"get_status\", {\n        account_id: root.accountId,\n    });\n    t.is(result, null);\n});\n\ntest(\"Ali sets then gets status\", async (t) => {\n    const { ali, statusMessage } = t.context.accounts;\n    await ali.call(statusMessage, \"set_status\", { message: \"hello\" });\n\n    let res = await ali.callRaw(statusMessage, \"get_status\", { account_id: ali.accountId });\n\n    t.assert(\n        res.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n            \"Smart contract panicked: deserialize err\"\n        )\n    );\n});\n\n"
  },
  {
    "path": "examples/__tests__/test-status-message-serialize-err.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n    // Init the worker and start a Sandbox server\n    const worker = await Worker.init();\n\n    // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n    const root = worker.rootAccount;\n\n    // Deploy the contract.\n    const statusMessage = await root.devDeploy(\"./build/status-message-serialize-err.wasm\");\n\n    // Create test users\n    const ali = await root.createSubAccount(\"ali\");\n    const bob = await root.createSubAccount(\"bob\");\n    const carl = await root.createSubAccount(\"carl\");\n\n    // Save state for test runs\n    t.context.worker = worker;\n    t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n    await t.context.worker.tearDown().catch((error) => {\n        console.log(\"Failed to tear down the worker:\", error);\n    });\n});\n\ntest(\"Root gets null status\", async (t) => {\n    const { statusMessage, root } = t.context.accounts;\n    const result = await statusMessage.view(\"get_status\", {\n        account_id: root.accountId,\n    });\n    t.is(result, null);\n});\n\ntest(\"Ali sets status\", async (t) => {\n    const { ali, statusMessage } = t.context.accounts;\n    let res = await ali.callRaw(statusMessage, \"set_status\", { message: \"hello\" });\n\n    t.assert(\n        res.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n            \"Smart contract panicked: serialize err\"\n        )\n    );\n});\n"
  },
  {
    "path": "examples/__tests__/test-status-message.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the contract.\n  const statusMessage = await root.devDeploy(\"./build/status-message.wasm\");\n\n  // Create test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, statusMessage, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Root gets null status\", async (t) => {\n  const { statusMessage, root } = t.context.accounts;\n  const result = await statusMessage.view(\"get_status\", {\n    account_id: root.accountId,\n  });\n  t.is(result, null);\n});\n\ntest(\"Ali sets then gets status\", async (t) => {\n  const { ali, statusMessage } = t.context.accounts;\n  await ali.call(statusMessage, \"set_status\", { message: \"hello\" });\n\n  t.is(\n    await statusMessage.view(\"get_status\", { account_id: ali.accountId }),\n    \"hello\"\n  );\n});\n\ntest(\"Bob and Carl have different statuses\", async (t) => {\n  const { statusMessage, bob, carl } = t.context.accounts;\n  await bob.call(statusMessage, \"set_status\", { message: \"hello\" });\n  await carl.call(statusMessage, \"set_status\", { message: \"world\" });\n\n  const bobStatus = await statusMessage.view(\"get_status\", {\n    account_id: bob.accountId,\n  });\n  const carlStatus = await statusMessage.view(\"get_status\", {\n    account_id: carl.accountId,\n  });\n  t.is(bobStatus, \"hello\");\n  t.is(carlStatus, \"world\");\n});\n"
  },
  {
    "path": "examples/ava.config.cjs",
    "content": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n  timeout: \"300000\",\n  files: [\"**/*.ava.js\"],\n  failWithoutAssertions: false,\n  extensions: [\"js\"],\n};\n"
  },
  {
    "path": "examples/jsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"experimentalDecorators\": true\n  },\n  \"exclude\": [\"node_modules\"],\n  \"files\": [\"src/counter.js\"]\n}\n"
  },
  {
    "path": "examples/package.json",
    "content": "{\n  \"name\": \"examples\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Status message example with near-sdk-js\",\n  \"main\": \"index.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"run-s build:*\",\n    \"build:status-message\": \"near-sdk-js build src/status-message/status-message.js build/status-message.wasm\",\n    \"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\",\n    \"build:status-message-borsh\": \"near-sdk-js build src/status-message/status-message-borsh.js build/status-message-borsh.wasm\",\n    \"build:status-message-serialize-err\": \"near-sdk-js build src/status-message/status-message-serialize-err.js build/status-message-serialize-err.wasm\",\n    \"build:status-message-deserialize-err\": \"near-sdk-js build src/status-message/status-message-deserialize-err.js build/status-message-deserialize-err.wasm\",\n    \"build:clean-state\": \"near-sdk-js build src/clean-state.js build/clean-state.wasm\",\n    \"build:counter\": \"near-sdk-js build src/counter/counter.js build/counter.wasm\",\n    \"build:counter-lowlevel\": \"near-sdk-js build src/counter/counter-lowlevel.js build/counter-lowlevel.wasm\",\n    \"build:counter-ts\": \"near-sdk-js build src/counter/counter.ts build/counter-ts.wasm\",\n    \"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\",\n    \"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\",\n    \"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\",\n    \"build:fungible-token-lockable\": \"near-sdk-js build src/fungible-token/fungible-token-lockable.js build/fungible-token-lockable.wasm\",\n    \"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\",\n    \"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\",\n    \"build:status-message-collections\": \"near-sdk-js build src/status-message/status-message-collections.js build/status-message-collections.wasm\",\n    \"build:parking-lot\": \"near-sdk-js build src/parking-lot.ts build/parking-lot.wasm\",\n    \"build:programmatic-updates\": \"near-sdk-js build src/programmatic-updates/programmatic-update-before.ts build/programmatic-update-before.wasm && near-sdk-js build src/programmatic-updates/programmatic-update-after.ts build/programmatic-update-after.wasm\",\n    \"build:nested-collections\": \"near-sdk-js build src/nested-collections.ts build/nested-collections.wasm\",\n    \"build-nft\": \"run-s build:nft-*\",\n    \"build:nft-contract\": \"near-sdk-js build src/non-fungible-token/my-nft.ts build/my-nft.wasm\",\n    \"build:nft-receiver\": \"near-sdk-js build src/non-fungible-token/test-token-receiver.ts build/nft-receiver.wasm\",\n    \"build:nft-approval-receiver\": \"near-sdk-js build src/non-fungible-token/test-approval-receiver.ts build/nft-approval-receiver.wasm\",\n    \"build:ft\": \"near-sdk-js build src/fungible-token/my-ft.ts build/my-ft.wasm\",\n    \"build:state-migration\": \"run-s build:state-migration:*\",\n    \"build:state-migration:original\": \"near-sdk-js build src/state-migration/state-migration-original.ts build/state-migration-original.wasm\",\n    \"build:state-migration:new\": \"near-sdk-js build src/state-migration/state-migration-new.ts build/state-migration-new.wasm\",\n    \"build:status-deserialize-class\": \"near-sdk-js build src/status-deserialize-class.js build/status-deserialize-class.wasm\",\n    \"build:basic-updates-base\": \"near-sdk-js build src/basic-updates/basic-updates-base.js build/basic-updates-base.wasm\",\n    \"build:basic-updates-update\": \"near-sdk-js build src/basic-updates/basic-updates-update.js build/basic-updates-update.wasm\",\n    \"test\": \"ava && pnpm test:counter-lowlevel && pnpm test:counter-ts\",\n    \"test:nft\": \"ava __tests__/standard-nft/*\",\n    \"test:ft\": \"ava __tests__/standard-ft/*\",\n    \"test:status-message\": \"ava __tests__/test-status-message.ava.js\",\n    \"test:status-message-migrate-add-field\": \"ava __tests__/test-state-message-migration-add-filed.ava.js\",\n    \"test:clean-state\": \"ava __tests__/test-clean-state.ava.js\",\n    \"test:counter\": \"ava __tests__/test-counter.ava.js\",\n    \"test:counter-lowlevel\": \"COUNTER_LOWLEVEL=1 ava __tests__/test-counter.ava.js\",\n    \"test:counter-ts\": \"COUNTER_TS=1 ava __tests__/test-counter.ava.js\",\n    \"test:cross-contract-call\": \"ava __tests__/test-cross-contract-call.ava.js\",\n    \"test:cross-contract-call-ts\": \"ava __tests__/test-cross-contract-call-ts.ava.js\",\n    \"test:cross-contract-call-loop\": \"ava __tests__/test-cross-contract-call-loop.ava.js\",\n    \"test:fungible-token-lockable\": \"ava __tests__/test-fungible-token-lockable.ava.js\",\n    \"test:fungible-token\": \"ava __tests__/test-fungible-token.ava.js\",\n    \"test:non-fungible-token\": \"ava __tests__/test-non-fungible-token.ava.js\",\n    \"test:status-message-collections\": \"ava __tests__/test-status-message-collections.ava.js\",\n    \"test:parking-lot\": \"ava __tests__/test-parking-lot.ava.js\",\n    \"test:programmatic-update\": \"ava __tests__/test-programmatic-update.ava.js\",\n    \"test:state-migration\": \"ava __tests__/test-state-migration.ava.js\",\n    \"test:nested-collections\": \"ava __tests__/test-nested-collections.ava.js\",\n    \"test:status-message-borsh\": \"ava __tests__/test-status-message-borsh.ava.js\",\n    \"test:status-message-serialize-err\": \"ava __tests__/test-status-message-serialize-err.ava.js\",\n    \"test:status-message-deserialize-err\": \"ava __tests__/test-status-message-deserialize-err.ava.js\",\n    \"test:status-deserialize-class\": \"ava __tests__/test-status-deserialize-class.ava.js\",\n    \"test:basic-updates\": \"ava __tests__/test-basic-updates.ava.js\"\n  },\n  \"author\": \"Near Inc <hello@nearprotocol.com>\",\n  \"license\": \"Apache-2.0\",\n  \"dependencies\": {\n    \"lodash-es\": \"4.17.21\",\n    \"near-contract-standards\": \"workspace:*\",\n    \"near-sdk-js\": \"workspace:*\",\n    \"typescript\": \"4.7.4\",\n    \"borsh\": \"1.0.0\"\n  },\n  \"devDependencies\": {\n    \"@types/lodash-es\": \"4.17.12\",\n    \"ava\": \"4.3.3\",\n    \"near-workspaces\": \"4.0.0\",\n    \"npm-run-all\": \"4.1.5\"\n  }\n}\n"
  },
  {
    "path": "examples/src/basic-updates/basic-updates-base.js",
    "content": "import {\n    NearBindgen,\n    call,\n    view,\n    near,\n    Vector,\n    ONE_NEAR\n} from \"near-sdk-js\";\n\nconst POINT_ONE = ONE_NEAR / 10000n;\n\nclass PostedMessage {\n    constructor() {\n        this.premium = false;\n        this.sender = \"\";\n        this.text = \"\";\n    }\n\n    static new(premium, sender, text) {\n        let posted_message = new PostedMessage();\n        posted_message.premium = premium;\n        posted_message.sender = sender;\n        posted_message.text = text;\n        return posted_message;\n    }\n}\n\n@NearBindgen({})\nexport class GuestBook {\n    constructor() {\n        this.messages = new Vector(\"a\");\n        this.payments = new Vector(\"b\");\n    }\n\n    @call({payableFunction: true})\n    add_message({text}) {\n        const payment = near.attachedDeposit();\n        let premium = payment > POINT_ONE;\n        const sender = near.predecessorAccountId();\n        let message = PostedMessage.new(premium, sender, text);\n        this.messages.push(message);\n        this.payments.push(payment);\n    }\n\n    @view({})\n    get_message({ index }) {\n        return this.messages.get(index) || null;\n    }\n\n    @view({})\n    get_payment({ index }) {\n        return this.payments.get(index) || null;\n    }\n}"
  },
  {
    "path": "examples/src/basic-updates/basic-updates-update.js",
    "content": "import {NearBindgen, call, view, near, migrate, Vector, assert, ONE_NEAR} from \"near-sdk-js\";\n\nconst POINT_ONE = ONE_NEAR / 10000n;\n\nclass OldPostedMessage {\n    constructor() {\n        this.premium = false;\n        this.sender = \"\";\n        this.text = \"\";\n    }\n}\n\n@NearBindgen({})\nexport class OldState {\n    constructor() {\n        this.messages = new Vector(\"a\");\n        this.payments = new Vector(\"b\");\n    }\n}\n\nclass PostedMessage {\n    constructor() {\n        this.payment = 0n;\n        this.premium = false;\n        this.sender = \"\";\n        this.text = \"\";\n    }\n\n    static new(payment, premium, sender, text) {\n        let posted_message = new PostedMessage();\n        posted_message.payment = payment;\n        posted_message.premium = premium;\n        posted_message.sender = sender;\n        posted_message.text = text;\n        return posted_message;\n    }\n}\n\n@NearBindgen({})\nexport class GuestBook {\n    constructor() {\n        this.messages = new Vector(\"a\");\n    }\n\n    @migrate({})\n    migrateState() {\n        assert(this.messages !== undefined, \"Contract state should not be deserialized in @migrate\");\n        // retrieve the current state from the contract\n        const _state = OldState._getState();\n        const _contract = OldState._create();\n        if (_state) {\n            OldState._reconstruct(_contract, _state);\n        }\n\n        let new_messages = new Vector(\"p\");\n\n        _contract.messages.toArray().forEach((posted, idx) => {\n            let payment = _contract\n                .payments\n                .get(idx) || 0n;\n            new_messages.push(PostedMessage.new(payment, posted.premium, posted.sender, posted.text));\n        });\n\n        _contract.messages.clear();\n        _contract.payments.clear();\n\n        this.messages = new_messages;\n    }\n\n    @call({payableFunction: true})\n    add_message({text}) {\n        const payment = near.attachedDeposit();\n        let premium = payment > POINT_ONE;\n        const sender = near.predecessorAccountId();\n        let message = PostedMessage.new(payment, premium, sender, text);\n        this.messages.push(message);\n    }\n\n    @view({})\n    get_message({ index }) {\n        return this.messages.get(index) || null;\n    }\n}"
  },
  {
    "path": "examples/src/clean-state.js",
    "content": "import { NearBindgen, call, view, near } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class CleanState {\n  @call({})\n  clean({ keys }) {\n    keys.forEach((key) => near.storageRemove(key));\n  }\n\n  @call({})\n  put({ key, value }) {\n    near.storageWrite(key, value);\n  }\n\n  @view({})\n  get({ key }) {\n    return near.storageRead(key);\n  }\n}\n"
  },
  {
    "path": "examples/src/counter/counter-lowlevel.js",
    "content": "// This contract implements exact same functionality as counter.js, but only use low level APIs\nimport { near } from \"near-sdk-js\";\n\nexport function init() {\n  let argsRaw = near.input();\n  let args = JSON.parse(argsRaw || \"{}\");\n  let initial = args.initial || 0;\n  let count = initial;\n  let state = JSON.stringify({ count });\n  near.storageWrite(\"STATE\", state);\n}\n\nfunction deserialize() {\n  let state = near.storageRead(\"STATE\");\n  if (state) {\n    return JSON.parse(state);\n  } else {\n    return { count: 0 };\n  }\n}\n\nexport function getCount() {\n  let state = deserialize();\n  let count = state.count;\n  near.valueReturn(JSON.stringify(count));\n}\n\nexport function increase() {\n  let argsRaw = near.input();\n  let args = JSON.parse(argsRaw || \"{}\");\n  let n = args.n || 1;\n  let state = deserialize();\n  state.count += n;\n  near.log(`Counter increased to ${state.count}`);\n  near.storageWrite(\"STATE\", JSON.stringify(state));\n}\n\nexport function decrease() {\n  let argsRaw = near.input();\n  let args = JSON.parse(argsRaw || \"{}\");\n  let n = args.n || 1;\n  let state = deserialize();\n  state.count -= n;\n  near.log(`Counter decreased to ${state.count}`);\n  near.storageWrite(\"STATE\", JSON.stringify(state));\n}\n"
  },
  {
    "path": "examples/src/counter/counter.js",
    "content": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\nimport { isUndefined } from \"lodash-es\";\n\n@NearBindgen({})\nexport class Counter {\n  constructor() {\n    this.count = 0;\n  }\n\n  @call({})\n  increase({ n = 1 }) {\n    this.count += n;\n    near.log(`Counter increased to ${this.count}`);\n  }\n\n  @call({})\n  decrease({ n }) {\n    // you can use default argument `n=1` too\n    // this is to illustrate a npm dependency: lodash can be used\n    if (isUndefined(n)) {\n      this.count -= 1;\n    } else {\n      this.count -= n;\n    }\n    near.log(`Counter decreased to ${this.count}`);\n  }\n\n  @view({})\n  getCount() {\n    return this.count;\n  }\n}\n"
  },
  {
    "path": "examples/src/counter/counter.ts",
    "content": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\nimport { isUndefined } from \"lodash-es\";\nimport { log } from \"./log\";\n\n@NearBindgen({})\nexport class Counter {\n  count = 0;\n\n  @call({})\n  increase({ n = 1 }: { n: number }) {\n    this.count += n;\n    near.log(`Counter increased to ${this.count}`);\n  }\n\n  @call({})\n  decrease({ n }: { n: number }) {\n    // you can use default argument `n=1` too\n    // this is to illustrate a npm dependency: lodash can be used\n    if (isUndefined(n)) {\n      this.count -= 1;\n    } else {\n      this.count -= n;\n    }\n    // this is to illustrate import a local ts module\n    log(`Counter decreased to ${this.count}`);\n  }\n\n  @view({})\n  getCount(): number {\n    return this.count;\n  }\n}\n"
  },
  {
    "path": "examples/src/counter/log.ts",
    "content": "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",
    "content": "import { call, near, NearBindgen, NearPromise, view } from \"near-sdk-js\";\n\nconst CONTRACTS = [\n  \"first-contract.test.near\",\n  \"second-contract.test.near\",\n  \"third-contract.test.near\",\n];\nconst NO_ARGS = \"\";\nconst THIRTY_TGAS = BigInt(\"30\" + \"0\".repeat(12));\n\n@NearBindgen({})\nexport class LoopXCC {\n  constructor() {\n    this.count = 0;\n  }\n\n  @call({})\n  incrementCount() {\n    let promise = NearPromise.new(CONTRACTS[0]).functionCall(\n      \"getCount\",\n      NO_ARGS,\n      BigInt(0),\n      THIRTY_TGAS\n    );\n    for (let i = 1; i < CONTRACTS.length; i++) {\n      promise = promise.and(\n        NearPromise.new(CONTRACTS[i]).functionCall(\n          \"getCount\",\n          NO_ARGS,\n          BigInt(0),\n          THIRTY_TGAS\n        )\n      );\n    }\n    promise = promise.then(\n      NearPromise.new(near.currentAccountId()).functionCall(\n        \"_incrementCountCallback\",\n        NO_ARGS,\n        BigInt(0),\n        THIRTY_TGAS\n      )\n    );\n    return promise.asReturn();\n  }\n\n  @call({ privateFunction: true })\n  _incrementCountCallback() {\n    const callCount = near.promiseResultsCount();\n    for (let i = 0; i < callCount; i++) {\n      const promiseResult = near.promiseResult(i);\n      const result = JSON.parse(promiseResult);\n      this.count += result;\n    }\n    return this.count;\n  }\n\n  @view({})\n  getCount() {\n    return this.count;\n  }\n}\n"
  },
  {
    "path": "examples/src/cross-contract-calls/cross-contract-call.js",
    "content": "import { NearBindgen, call, view, initialize, near } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class OnCall {\n  constructor() {\n    this.personOnCall = \"\";\n    this.statusMessageContract = \"\";\n  }\n\n  @initialize({})\n  init({ statusMessageContract }) {\n    this.personOnCall = \"undefined\";\n    this.statusMessageContract = statusMessageContract;\n  }\n\n  @call({})\n  set_person_on_call({ accountId }) {\n    near.log(`Trying to set ${accountId} on-call`);\n    const promise = near.promiseBatchCreate(this.statusMessageContract);\n    near.promiseBatchActionFunctionCall(\n      promise,\n      \"get_status\",\n      JSON.stringify({ account_id: accountId }),\n      0,\n      30000000000000\n    );\n    near.promiseThen(\n      promise,\n      near.currentAccountId(),\n      \"_set_person_on_call_private\",\n      JSON.stringify({ accountId: accountId }),\n      0,\n      30000000000000\n    );\n  }\n\n  @call({ privateFunction: true })\n  _set_person_on_call_private({ accountId }) {\n    near.log(`_set_person_on_call_private called, accountId ${accountId}`);\n    const status = JSON.parse(near.promiseResult(0));\n    near.log(`${accountId} status is ${status}`);\n    if (status === \"AVAILABLE\") {\n      this.personOnCall = accountId;\n      near.log(`${accountId} set on-call`);\n    } else {\n      near.log(`${accountId} can not be set on-call`);\n    }\n  }\n\n  @view({})\n  person_on_call() {\n    near.log(`Returning person on-call: ${this.personOnCall}`);\n    return this.personOnCall;\n  }\n}\n"
  },
  {
    "path": "examples/src/cross-contract-calls/cross-contract-call.ts",
    "content": "import { NearBindgen, call, view, initialize, near } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class OnCall {\n  personOnCall:string =\"\";\n  statusMessageContract:string =\"\";\n\n  @initialize({})\n  init({ statusMessageContract }) {\n    this.statusMessageContract = statusMessageContract;\n  }\n\n  @call({})\n  set_person_on_call({ accountId }) {\n    near.log(`Trying to set ${accountId} on-call`);\n    const promise = near.promiseBatchCreate(this.statusMessageContract);\n    near.promiseBatchActionFunctionCall(\n      promise,\n      \"get_status\",\n      JSON.stringify({ account_id: accountId }),\n      0,\n      30000000000000\n    );\n    near.promiseThen(\n      promise,\n      near.currentAccountId(),\n      \"_set_person_on_call_private\",\n      JSON.stringify({ accountId: accountId }),\n      0,\n      30000000000000\n    );\n  }\n\n  @call({ privateFunction: true })\n  _set_person_on_call_private({ accountId }) {\n    near.log(`_set_person_on_call_private called, accountId ${accountId}`);\n    const status = JSON.parse(near.promiseResult(0));\n    near.log(`${accountId} status is ${status}`);\n    if (status === \"AVAILABLE\") {\n      this.personOnCall = accountId;\n      near.log(`${accountId} set on-call`);\n    } else {\n      near.log(`${accountId} can not be set on-call`);\n    }\n  }\n\n  @view({})\n  person_on_call() {\n    near.log(`Returning person on-call: ${this.personOnCall}`);\n    return this.personOnCall;\n  }\n}\n"
  },
  {
    "path": "examples/src/fungible-token/fungible-token-helper.ts",
    "content": "import { NearBindgen, call, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nclass _FungibleTokenHelper {\n  data = \"\";\n\n  @call({})\n  ft_on_transfer({\n    sender_id,\n    amount,\n    msg,\n    receiver_id,\n  }: {\n    sender_id: string;\n    amount: string;\n    msg: string;\n    receiver_id: string;\n  }) {\n    const concatString = `[${amount} from ${sender_id} to ${receiver_id}] ${msg} `;\n    this.data = this.data.concat(\"\", concatString);\n  }\n\n  @view({})\n  get_contract_data() {\n    return this.data;\n  }\n}\n"
  },
  {
    "path": "examples/src/fungible-token/fungible-token-lockable.js",
    "content": "import {\n  NearBindgen,\n  call,\n  view,\n  initialize,\n  near,\n  LookupMap,\n} from \"near-sdk-js\";\n\nclass Account {\n  constructor(balance, allowances, lockedBalances) {\n    this.balance = balance; // Current unlocked balance\n    this.allowances = allowances; // Allowed account to the allowance amount\n    this.lockedBalances = lockedBalances; // Allowed account to locked balance\n  }\n\n  setAllowance(escrowAccountId, allowance) {\n    if (allowance > 0) {\n      this.allowances[escrowAccountId] = allowance;\n    } else if (allowance === 0) {\n      delete this.allowances[escrowAccountId];\n    } else {\n      throw Error(\"Allowance can't be negative\");\n    }\n  }\n\n  getAllowance(escrowAccountId) {\n    return this.allowances[escrowAccountId] || 0;\n  }\n\n  setLockedBalance(escrowAccountId, lockedBalance) {\n    if (lockedBalance > 0) {\n      this.lockedBalances[escrowAccountId] = lockedBalance;\n    } else if (lockedBalance === 0) {\n      delete this.lockedBalances[escrowAccountId];\n    } else {\n      throw Error(\"Locked balance cannot be negative\");\n    }\n  }\n\n  getLockedBalance(escrowAccountId) {\n    return this.lockedBalances[escrowAccountId] || 0;\n  }\n\n  totalBalance() {\n    let totalLockedBalance = Object.values(this.lockedBalances).reduce(\n      (acc, val) => acc + val,\n      0\n    );\n    return this.balance + totalLockedBalance;\n  }\n}\n\n@NearBindgen({ initRequired: true })\nexport class LockableFungibleToken {\n  constructor() {\n    this.accounts = new LookupMap(\"a\"); // Account ID -> Account mapping\n    this.totalSupply = 0; // Total supply of the all tokens\n  }\n\n  @initialize({})\n  init({ prefix, totalSupply }) {\n    this.accounts = new LookupMap(prefix);\n    this.totalSupply = totalSupply;\n    let ownerId = near.signerAccountId();\n    let ownerAccount = this.getAccount(ownerId);\n    ownerAccount.balance = this.totalSupply;\n    this.setAccount(ownerId, ownerAccount);\n  }\n\n  getAccount(ownerId) {\n    let account = this.accounts.get(ownerId);\n    if (account === null) {\n      return new Account(0, {}, {});\n    }\n    return new Account(\n      account.balance,\n      account.allowances,\n      account.lockedBalances\n    );\n  }\n\n  setAccount(accountId, account) {\n    this.accounts.set(accountId, account);\n  }\n\n  @call({})\n  setAllowance({ escrowAccountId, allowance }) {\n    let ownerId = near.predecessorAccountId();\n    if (escrowAccountId === ownerId) {\n      throw Error(\"Can't set allowance for yourself\");\n    }\n    let account = this.getAccount(ownerId);\n    let lockedBalance = account.getLockedBalance(escrowAccountId);\n    if (lockedBalance > allowance) {\n      throw Error(\n        \"The new allowance can't be less than the amount of locked tokens\"\n      );\n    }\n\n    account.setAllowance(escrowAccountId, allowance - lockedBalance);\n    this.setAccount(ownerId, account);\n  }\n\n  @call({})\n  lock({ ownerId, lockAmount }) {\n    if (lockAmount <= 0) {\n      throw Error(\"Can't lock 0 or less tokens\");\n    }\n    let escrowAccountId = near.predecessorAccountId();\n    let account = this.getAccount(ownerId);\n\n    // Checking and updating unlocked balance\n    if (account.balance < lockAmount) {\n      throw Error(\"Not enough unlocked balance\");\n    }\n    account.balance -= lockAmount;\n\n    // If locking by escrow, need to check and update the allowance.\n    if (escrowAccountId !== ownerId) {\n      let allowance = account.getAllowance(escrowAccountId);\n      if (allowance < lockAmount) {\n        throw Error(\"Not enough allowance\");\n      }\n      account.setAllowance(escrowAccountId, allowance - lockAmount);\n    }\n\n    // Updating total lock balance\n    let lockedBalance = account.getLockedBalance(escrowAccountId);\n    account.setLockedBalance(escrowAccountId, lockedBalance + lockAmount);\n\n    this.setAccount(ownerId, account);\n  }\n\n  @call({})\n  unlock({ ownerId, unlockAmount }) {\n    if (unlockAmount <= 0) {\n      throw Error(\"Can't unlock 0 or less tokens\");\n    }\n    let escrowAccountId = near.predecessorAccountId();\n    let account = this.getAccount(ownerId);\n\n    // Checking and updating locked balance\n    let lockedBalance = account.getLockedBalance(escrowAccountId);\n    if (lockedBalance < unlockAmount) {\n      throw Error(\"Not enough locked tokens\");\n    }\n    account.setLockedBalance(escrowAccountId, lockedBalance - unlockAmount);\n\n    // If unlocking by escrow, need to update allowance.\n    if (escrowAccountId !== ownerId) {\n      let allowance = account.getAllowance(escrowAccountId);\n      account.setAllowance(escrowAccountId, allowance + unlockAmount);\n    }\n\n    // Updating unlocked balance\n    account.balance += unlockAmount;\n\n    this.setAccount(ownerId, account);\n  }\n\n  @call({})\n  transferFrom({ ownerId, newOwnerId, amount }) {\n    if (amount <= 0) {\n      throw Error(\"Can't transfer 0 or less tokens\");\n    }\n    let escrowAccountId = near.predecessorAccountId();\n    let account = this.getAccount(ownerId);\n\n    // Checking and updating locked balance\n    let lockedBalance = account.getLockedBalance(escrowAccountId);\n    var remainingAmount;\n    if (lockedBalance >= amount) {\n      account.setLockedBalance(escrowAccountId, lockedBalance - amount);\n      remainingAmount = 0;\n    } else {\n      account.setLockedBalance(escrowAccountId, 0);\n      remainingAmount = amount - lockedBalance;\n    }\n\n    // If there is remaining balance after the locked balance, we try to use unlocked tokens.\n    if (remainingAmount > 0) {\n      // Checking and updating unlocked balance\n      if (account.balance < remainingAmount) {\n        throw Error(\"Not enough unlocked balance\");\n      }\n      account.balance -= remainingAmount;\n\n      // If transferring by escrow, need to check and update allowance.\n      if (escrowAccountId !== ownerId) {\n        let allowance = account.getAllowance(escrowAccountId);\n        // Checking and updating unlocked balance\n        if (allowance < remainingAmount) {\n          throw Error(\"Not enough allowance\");\n        }\n        account.setAllowance(escrowAccountId, allowance - remainingAmount);\n      }\n    }\n\n    this.setAccount(ownerId, account);\n\n    // Deposit amount to the new owner\n    let newAccount = this.getAccount(newOwnerId);\n    newAccount.balance += amount;\n    this.setAccount(newOwnerId, newAccount);\n  }\n\n  @call({})\n  transfer({ newOwnerId, amount }) {\n    this.transferFrom({\n      ownerId: near.predecessorAccountId(),\n      newOwnerId,\n      amount,\n    });\n  }\n\n  @view({})\n  getTotalSupply() {\n    return this.totalSupply;\n  }\n\n  @view({})\n  getTotalBalance({ ownerId }) {\n    return this.getAccount(ownerId).totalBalance();\n  }\n\n  @view({})\n  getUnlockedBalance({ ownerId }) {\n    return this.getAccount(ownerId).balance;\n  }\n\n  @view({})\n  getAllowance({ ownerId, escrowAccountId }) {\n    return this.getAccount(ownerId).getAllowance(escrowAccountId);\n  }\n\n  @view({})\n  getLockedBalance({ ownerId, escrowAccountId }) {\n    return this.getAccount(ownerId).getLockedBalance(escrowAccountId);\n  }\n}\n"
  },
  {
    "path": "examples/src/fungible-token/fungible-token.ts",
    "content": "import {\n  NearBindgen,\n  call,\n  view,\n  initialize,\n  near,\n  LookupMap,\n  assert,\n  validateAccountId,\n} from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class FungibleToken {\n  accounts: LookupMap<bigint>;\n  accountRegistrants: LookupMap<string>;\n  accountDeposits: LookupMap<bigint>;\n  totalSupply: bigint;\n\n  constructor() {\n    this.accounts = new LookupMap(\"a\");\n    this.accountRegistrants = new LookupMap(\"r\");\n    this.accountDeposits = new LookupMap(\"d\");\n    this.totalSupply = BigInt(\"0\");\n  }\n\n  @initialize({})\n  init({ owner_id, total_supply }: { owner_id: string; total_supply: string }) {\n    Assertions.isLeftGreaterThanRight(total_supply, 0);\n    validateAccountId(owner_id);\n    this.totalSupply = BigInt(total_supply);\n    this.accounts.set(owner_id, this.totalSupply);\n  }\n\n  internalGetAccountStorageUsage(accountLength: number): bigint {\n    const initialStorageUsage = near.storageUsage();\n    const tempAccountId = \"a\".repeat(64);\n    this.accounts.set(tempAccountId, BigInt(\"0\"));\n    const len64StorageUsage = near.storageUsage() - initialStorageUsage;\n    const len1StorageUsage = len64StorageUsage / BigInt(64);\n    const lenAccountStorageUsage = len1StorageUsage * BigInt(accountLength);\n    this.accounts.remove(tempAccountId);\n    return lenAccountStorageUsage * BigInt(3); // we create an entry in 3 maps\n  }\n\n  internalRegisterAccount({\n    registrantAccountId,\n    accountId,\n    amount,\n  }: {\n    registrantAccountId: string;\n    accountId: string;\n    amount: string;\n  }) {\n    assert(\n      !this.accounts.containsKey(accountId),\n      \"Account is already registered\"\n    );\n    this.accounts.set(accountId, BigInt(\"0\"));\n    this.accountRegistrants.set(accountId, registrantAccountId);\n    this.accountDeposits.set(accountId, BigInt(amount));\n  }\n\n  internalSendNEAR(receivingAccountId: string, amount: bigint) {\n    Assertions.isLeftGreaterThanRight(amount, 0);\n    Assertions.isLeftGreaterThanRight(\n      near.accountBalance(),\n      amount,\n      `Not enough balance ${near.accountBalance()} to send ${amount}`\n    );\n    const promise = near.promiseBatchCreate(receivingAccountId);\n    near.promiseBatchActionTransfer(promise, amount);\n    near.promiseReturn(promise);\n  }\n\n  internalGetBalance(accountId: string): string {\n    assert(\n      this.accounts.containsKey(accountId),\n      `Account ${accountId} is not registered`\n    );\n    return this.accounts.get(accountId).toString();\n  }\n\n  internalDeposit(accountId: string, amount: string) {\n    const balance = this.internalGetBalance(accountId);\n    const newBalance = BigInt(balance) + BigInt(amount);\n    this.accounts.set(accountId, newBalance);\n    const newSupply = BigInt(this.totalSupply) + BigInt(amount);\n    this.totalSupply = newSupply;\n  }\n\n  internalWithdraw(accountId: string, amount: string) {\n    const balance = this.internalGetBalance(accountId);\n    const newBalance = BigInt(balance) - BigInt(amount);\n    const newSupply = BigInt(this.totalSupply) - BigInt(amount);\n    Assertions.isLeftGreaterThanRight(\n      newBalance,\n      -1,\n      \"The account doesn't have enough balance\"\n    );\n    Assertions.isLeftGreaterThanRight(newSupply, -1, \"Total supply overflow\");\n    this.accounts.set(accountId, newBalance);\n    this.totalSupply = newSupply;\n  }\n\n  internalTransfer(\n    senderId: string,\n    receiverId: string,\n    amount: string,\n    _memo: string = null\n  ) {\n    assert(senderId != receiverId, \"Sender and receiver should be different\");\n    Assertions.isLeftGreaterThanRight(amount, 0);\n    this.internalWithdraw(senderId, amount);\n    this.internalDeposit(receiverId, amount);\n  }\n\n  @call({ payableFunction: true })\n  storage_deposit({ account_id }: { account_id: string }) {\n    const accountId = account_id || near.predecessorAccountId();\n    validateAccountId(accountId);\n    const attachedDeposit = near.attachedDeposit();\n    if (this.accounts.containsKey(accountId)) {\n      if (attachedDeposit > 0) {\n        this.internalSendNEAR(near.predecessorAccountId(), attachedDeposit);\n        return {\n          message:\n            \"Account is already registered, deposit refunded to predecessor\",\n        };\n      }\n      return { message: \"Account is already registered\" };\n    }\n    const storageCost = this.internalGetAccountStorageUsage(accountId.length);\n    if (attachedDeposit < storageCost) {\n      this.internalSendNEAR(near.predecessorAccountId(), attachedDeposit);\n      return {\n        message: `Not enough attached deposit to cover storage cost. Required: ${storageCost.toString()}`,\n      };\n    }\n    this.internalRegisterAccount({\n      registrantAccountId: near.predecessorAccountId(),\n      accountId: accountId,\n      amount: storageCost.toString(),\n    });\n    const refund = attachedDeposit - storageCost;\n    if (refund > 0) {\n      near.log(\n        \"Storage registration refunding \" +\n          refund +\n          \" yoctoNEAR to \" +\n          near.predecessorAccountId()\n      );\n      this.internalSendNEAR(near.predecessorAccountId(), refund);\n    }\n    return {\n      message: `Account ${accountId} registered with storage deposit of ${storageCost.toString()}`,\n    };\n  }\n\n  @call({ payableFunction: true })\n  ft_transfer({\n    receiver_id,\n    amount,\n    memo,\n  }: {\n    receiver_id: string;\n    amount: string;\n    memo: string;\n  }) {\n    Assertions.hasAtLeastOneAttachedYocto();\n    const senderId = near.predecessorAccountId();\n    near.log(\n      \"Transfer \" + amount + \" token from \" + senderId + \" to \" + receiver_id\n    );\n    this.internalTransfer(senderId, receiver_id, amount, memo);\n  }\n\n  @call({ payableFunction: true })\n  ft_transfer_call({\n    receiver_id,\n    amount,\n    memo,\n    msg,\n  }: {\n    receiver_id: string;\n    amount: string;\n    memo: string;\n    msg: string;\n  }) {\n    Assertions.hasAtLeastOneAttachedYocto();\n    const senderId = near.predecessorAccountId();\n    this.internalTransfer(senderId, receiver_id, amount, memo);\n    const promise = near.promiseBatchCreate(receiver_id);\n    const params = {\n      sender_id: senderId,\n      amount: amount,\n      msg: msg,\n      receiver_id: receiver_id,\n    };\n    near.log(\n      \"Transfer call \" +\n        amount +\n        \" token from \" +\n        senderId +\n        \" to \" +\n        receiver_id +\n        \" with message \" +\n        msg\n    );\n    near.promiseBatchActionFunctionCall(\n      promise,\n      \"ft_on_transfer\",\n      JSON.stringify(params),\n      0,\n      30000000000000\n    );\n    return near.promiseReturn(promise);\n  }\n\n  @view({})\n  ft_total_supply() {\n    return this.totalSupply;\n  }\n\n  @view({})\n  ft_balance_of({ account_id }: { account_id: string }) {\n    validateAccountId(account_id);\n    return this.internalGetBalance(account_id);\n  }\n}\n\nclass Assertions {\n  static hasAtLeastOneAttachedYocto() {\n    assert(\n      near.attachedDeposit() > BigInt(0),\n      \"Requires at least 1 yoctoNEAR to ensure signature\"\n    );\n  }\n\n  static isLeftGreaterThanRight(\n    left: string | bigint | number | boolean,\n    right: string | bigint | number | boolean,\n    message: string = null\n  ) {\n    const msg =\n      message || `Provided amount ${left} should be greater than ${right}`;\n    assert(BigInt(left) > BigInt(right), msg);\n  }\n}\n"
  },
  {
    "path": "examples/src/fungible-token/my-ft.ts",
    "content": "import {\n    StorageBalance,\n    StorageBalanceBounds,\n    StorageManagement,\n    FungibleTokenCore,\n    FungibleTokenResolver,\n    FungibleToken,\n    FungibleTokenMetadata,\n} from \"near-contract-standards/lib\"; //TODO: delete lib\n\nimport {\n    AccountId,\n    Balance,\n    PromiseOrValue,\n    call,\n    view,\n    initialize,\n    NearBindgen,\n    IntoStorageKey,\n    near,\n} from \"near-sdk-js\";\n\nimport {\n    Option,\n} from \"near-contract-standards/lib/non_fungible_token/utils\"; // TODO: fix import\n\nclass FTPrefix implements IntoStorageKey {\n    into_storage_key(): string {\n        return \"A\"; // TODO: What is the best value to put here?\n    }\n}\n\n@NearBindgen({ requireInit: true })\nexport class MyFt implements FungibleTokenCore, StorageManagement, FungibleTokenResolver {\n    token: FungibleToken;\n    metadata: FungibleTokenMetadata;\n\n    constructor() {\n        this.token = new FungibleToken();\n        this.metadata = new FungibleTokenMetadata(\"\", \"\", \"\", \"\", null, null, 0);\n    }\n\n    @initialize({})\n    init({\n        owner_id,\n        total_supply,\n        metadata,\n    }: {\n        owner_id: AccountId;\n        total_supply: Balance;\n        metadata: FungibleTokenMetadata;\n    }) {\n        metadata.assert_valid();\n        this.token = new FungibleToken().init(new FTPrefix());\n        this.metadata = metadata;\n        this.token.internal_register_account(owner_id);\n        this.token.internal_deposit(owner_id, total_supply);\n    }\n\n    @initialize({})\n    init_with_default_meta({\n        owner_id,\n        total_supply\n    }: {\n        owner_id: AccountId;\n        total_supply: Balance;\n    }) {\n        const metadata = new FungibleTokenMetadata(\n            \"ft-1.0.0\",\n            \"Example NEAR fungible token\",\n            \"EXAMPLE\",\n            \"DATA_IMAGE_SVG_NEAR_ICON\",\n            null,\n            null,\n            24,\n        );\n        return this.init({\n            owner_id,\n            total_supply,\n            metadata\n        })\n    }\n\n\n    @call({})\n    measure_account_storage_usage() {\n        return this.token.measure_account_storage_usage();\n    }\n\n    @call({ payableFunction: true })\n    ft_transfer({\n        receiver_id,\n        amount,\n        memo\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo?: String\n    }) {\n        return this.token.ft_transfer({ receiver_id, amount, memo });\n    }\n\n    @call({ payableFunction: true })\n    ft_transfer_call({\n        receiver_id,\n        amount,\n        memo,\n        msg\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo: Option<String>,\n        msg: string\n    }): PromiseOrValue<bigint> {\n        return this.token.ft_transfer_call({ receiver_id, amount, memo, msg });\n    }\n\n    @view({})\n    ft_total_supply(): Balance {\n        return this.token.ft_total_supply();\n    }\n\n    @view({})\n    ft_balance_of({ account_id }: { account_id: AccountId }): Balance {\n        return this.token.ft_balance_of({ account_id });\n    }\n\n    @call({ payableFunction: true })\n    storage_deposit(\n        {\n            account_id,\n            registration_only,\n        }: {\n            account_id?: AccountId,\n            registration_only?: boolean,\n        }\n    ): StorageBalance {\n        return this.token.storage_deposit({ account_id, registration_only });\n    }\n\n    @view({})\n    storage_withdraw({ amount }: { amount?: bigint }): StorageBalance {\n        return this.token.storage_withdraw({ amount });\n    }\n\n    @call({ payableFunction: true })\n    storage_unregister({ force }: { force?: boolean }): boolean {\n        return this.token.storage_unregister({ force });\n    }\n\n    @view({})\n    storage_balance_bounds(): StorageBalanceBounds {\n        return this.token.storage_balance_bounds();\n    }\n\n    @view({})\n    storage_balance_of({ account_id }: { account_id: AccountId }): Option<StorageBalance> {\n        return this.token.storage_balance_of({ account_id });\n    }\n\n    @call({})\n    ft_resolve_transfer({\n        sender_id,\n        receiver_id,\n        amount\n    }: {\n        sender_id: AccountId,\n        receiver_id: AccountId,\n        amount: Balance\n    }): Balance {\n        return this.token.ft_resolve_transfer({ sender_id, receiver_id, amount });\n    }\n}\n"
  },
  {
    "path": "examples/src/nested-collections.ts",
    "content": "import { NearBindgen, near, call, view, UnorderedMap } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class Contract {\n  outerMap: UnorderedMap<UnorderedMap<string>>;\n  groups: UnorderedMap<UnorderedMap<UnorderedMap<string>>>;\n\n  constructor() {\n    this.outerMap = new UnorderedMap(\"o\");\n    this.groups = new UnorderedMap(\"gs\");\n  }\n\n  @call({})\n  add({ id, text }: { id: string; text: string }) {\n    const innerMap = this.outerMap.get(id, {\n      reconstructor: UnorderedMap.reconstruct,\n      defaultValue: new UnorderedMap<string>(\"i_\" + id + \"_\"),\n    });\n    innerMap.set(near.signerAccountId(), text);\n    this.outerMap.set(id, innerMap);\n  }\n\n  @view({})\n  get({ id, accountId }: { id: string; accountId: string }) {\n    const innerMap = this.outerMap.get(id, {\n      reconstructor: UnorderedMap.reconstruct,\n    });\n    if (innerMap === null) {\n      return null;\n    }\n    return innerMap.get(accountId);\n  }\n\n  @call({})\n  add_to_group({\n    group,\n    id,\n    text,\n  }: {\n    group: string;\n    id: string;\n    text: string;\n  }) {\n    const groupMap = this.groups.get(group, {\n      reconstructor: UnorderedMap.reconstruct,\n      defaultValue: new UnorderedMap<UnorderedMap<string>>(\"g_\" + group + \"_\"),\n    });\n    const innerMap = groupMap.get(id, {\n      reconstructor: UnorderedMap.reconstruct,\n      defaultValue: new UnorderedMap<string>(\"gi_\" + group + \"_\" + id + \"_\"),\n    });\n    innerMap.set(near.signerAccountId(), text);\n    groupMap.set(id, innerMap);\n    this.groups.set(group, groupMap);\n  }\n\n  @view({})\n  get_from_group({\n    group,\n    id,\n    accountId,\n  }: {\n    group: string;\n    id: string;\n    accountId: string;\n  }) {\n    const groupMap = this.groups.get(group, {\n      reconstructor: UnorderedMap.reconstruct,\n    });\n    if (groupMap === null) {\n      return null;\n    }\n    const innerMap = groupMap.get(id, {\n      reconstructor: UnorderedMap.reconstruct,\n    });\n    if (innerMap === null) {\n      return null;\n    }\n    return innerMap.get(accountId);\n  }\n}\n"
  },
  {
    "path": "examples/src/non-fungible-token/my-nft.ts",
    "content": "import { NonFungibleToken } from \"near-contract-standards/lib\";\nimport {\n  assert,\n  call,\n  initialize,\n  near,\n  NearBindgen,\n  NearPromise,\n  PromiseOrValue,\n  view,\n  IntoStorageKey\n} from \"near-sdk-js\";\nimport {\n  NFTContractMetadata,\n  NonFungibleTokenMetadataProvider,\n  TokenMetadata,\n} from \"near-contract-standards/lib/non_fungible_token/metadata\";\nimport {\n  Option,\n} from \"near-contract-standards/lib/non_fungible_token/utils\";\nimport { AccountId } from \"near-sdk-js\";\nimport { NonFungibleTokenCore } from \"near-contract-standards/lib/non_fungible_token/core\";\nimport {\n  Token,\n  TokenId,\n} from \"near-contract-standards/lib/non_fungible_token/token\";\nimport { NonFungibleTokenResolver } from \"near-contract-standards/lib/non_fungible_token/core/resolver\";\nimport { NonFungibleTokenApproval } from \"near-contract-standards/lib/non_fungible_token/approval\";\nimport { NonFungibleTokenEnumeration } from \"near-contract-standards/lib/non_fungible_token/enumeration\";\n\nclass StorageKey { }\n\nclass StorageKeyNonFungibleToken extends StorageKey implements IntoStorageKey {\n  into_storage_key(): string {\n    return \"NFT_\";\n  }\n}\n\nclass StorageKeyTokenMetadata extends StorageKey implements IntoStorageKey {\n  into_storage_key(): string {\n    return \"TOKEN_METADATA_\";\n  }\n}\n\nclass StorageKeyTokenEnumeration extends StorageKey implements IntoStorageKey {\n  into_storage_key(): string {\n    return \"TOKEN_ENUMERATION_\";\n  }\n}\n\nclass StorageKeyApproval extends StorageKey implements IntoStorageKey {\n  into_storage_key(): string {\n    return \"APPROVAL1_\";\n  }\n}\n\n@NearBindgen({ requireInit: true })\nexport class MyNFT\n  implements\n  NonFungibleTokenCore,\n  NonFungibleTokenMetadataProvider,\n  NonFungibleTokenResolver,\n  NonFungibleTokenApproval,\n  NonFungibleTokenEnumeration {\n  tokens: NonFungibleToken;\n  metadata: Option<NFTContractMetadata>;\n\n  constructor() {\n    this.tokens = new NonFungibleToken();\n    this.metadata = new NFTContractMetadata();\n  }\n\n  @view({})\n  nft_total_supply(): number {\n    return this.tokens.nft_total_supply();\n  }\n\n  @view({})\n  nft_tokens({\n    from_index,\n    limit,\n  }: {\n    from_index?: number;\n    limit?: number;\n  }): Token[] {\n    return this.tokens.nft_tokens({ from_index, limit });\n  }\n\n  @view({})\n  nft_supply_for_owner({ account_id }: { account_id: string }): number {\n    return this.tokens.nft_supply_for_owner({ account_id });\n  }\n\n  @view({})\n  nft_tokens_for_owner({\n    account_id,\n    from_index,\n    limit,\n  }: {\n    account_id: string;\n    from_index?: number;\n    limit?: number;\n  }): Token[] {\n    return this.tokens.nft_tokens_for_owner({ account_id, from_index, limit });\n  }\n\n  @call({ payableFunction: true })\n  nft_approve({\n    token_id,\n    account_id,\n    msg,\n  }: {\n    token_id: string;\n    account_id: string;\n    msg?: string;\n  }): Option<NearPromise> {\n    return this.tokens.nft_approve({ token_id, account_id, msg });\n  }\n\n  @call({ payableFunction: true })\n  nft_revoke({\n    token_id,\n    account_id,\n  }: {\n    token_id: string;\n    account_id: string;\n  }) {\n    return this.tokens.nft_revoke({ token_id, account_id });\n  }\n\n  @call({ payableFunction: true })\n  nft_revoke_all({ token_id }: { token_id: string }) {\n    return this.tokens.nft_revoke_all({ token_id });\n  }\n\n  @view({})\n  nft_is_approved({\n    token_id,\n    approved_account_id,\n    approval_id,\n  }: {\n    token_id: string;\n    approved_account_id: string;\n    approval_id?: bigint;\n  }): boolean {\n    return this.tokens.nft_is_approved({\n      token_id,\n      approved_account_id,\n      approval_id,\n    });\n  }\n\n  @call({})\n  nft_resolve_transfer({\n    previous_owner_id,\n    receiver_id,\n    token_id,\n    approved_account_ids,\n  }: {\n    previous_owner_id: string;\n    receiver_id: string;\n    token_id: string;\n    approved_account_ids?: { [approval: string]: bigint };\n  }): boolean {\n    return this.tokens.nft_resolve_transfer({\n      previous_owner_id,\n      receiver_id,\n      token_id,\n      approved_account_ids,\n    });\n  }\n\n  @view({})\n  nft_metadata(): NFTContractMetadata {\n    assert(this.metadata !== null, \"Metadata not initialized\");\n    return this.metadata;\n  }\n\n  @call({ payableFunction: true })\n  nft_transfer({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n  }: {\n    receiver_id: string;\n    token_id: string;\n    approval_id?: bigint;\n    memo?: string;\n  }) {\n    this.tokens.nft_transfer({ receiver_id, token_id, approval_id, memo });\n  }\n\n  @call({ payableFunction: true })\n  nft_transfer_call({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n    msg,\n  }: {\n    receiver_id: string;\n    token_id: string;\n    approval_id?: bigint;\n    memo?: string;\n    msg: string;\n  }): PromiseOrValue<boolean> {\n    return this.tokens.nft_transfer_call({\n      receiver_id,\n      token_id,\n      approval_id,\n      memo,\n      msg,\n    });\n  }\n\n  @view({})\n  nft_token({ token_id }: { token_id: string }): Option<Token> {\n    return this.tokens.nft_token({ token_id });\n  }\n\n  @initialize({ requireInit: true })\n  init({\n    owner_id,\n    metadata,\n  }: {\n    owner_id: string;\n    metadata: NFTContractMetadata;\n  }) {\n    this.metadata = Object.assign(new NFTContractMetadata(), metadata);\n    this.metadata.assert_valid();\n    this.tokens = new NonFungibleToken();\n    this.tokens.init(\n      new StorageKeyNonFungibleToken(),\n      owner_id,\n      new StorageKeyTokenMetadata(),\n      new StorageKeyTokenEnumeration(),\n      new StorageKeyApproval()\n    );\n  }\n\n  @call({ payableFunction: true })\n  nft_mint({\n    token_id,\n    token_owner_id,\n    token_metadata,\n  }: {\n    token_id: TokenId;\n    token_owner_id: AccountId;\n    token_metadata: TokenMetadata;\n  }) {\n    assert(\n      near.predecessorAccountId() === this.tokens.owner_id,\n      \"Unauthorized\"\n    );\n    this.tokens.internal_mint(token_id, token_owner_id, token_metadata);\n  }\n}\n"
  },
  {
    "path": "examples/src/non-fungible-token/non-fungible-token-receiver.js",
    "content": "import { NearBindgen, call, near, assert, initialize } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class NftContract {\n  constructor() {\n    this.nonFungibleTokenAccountId = \"\";\n  }\n\n  @initialize({})\n  init({ nonFungibleTokenAccountId }) {\n    this.nonFungibleTokenAccountId = nonFungibleTokenAccountId;\n  }\n\n  @call({})\n  nftOnTransfer({ senderId, previousOwnerId, tokenId, msg }) {\n    near.log(\n      `nftOnTransfer called, params: senderId: ${senderId}, previousOwnerId: ${previousOwnerId}, tokenId: ${tokenId}, msg: ${msg}`\n    );\n    assert(\n      near.predecessorAccountId() === this.nonFungibleTokenAccountId,\n      \"Only supports the one non-fungible token contract\"\n    );\n    if (msg === \"return-it-now\") {\n      near.log(`Returning ${tokenId} to ${senderId}`);\n      return false;\n    } else if (msg === \"keep-it-now\") {\n      near.log(`Keep ${tokenId}`);\n      return true;\n    } else {\n      throw Error(\"unsupported msg\");\n    }\n  }\n}\n"
  },
  {
    "path": "examples/src/non-fungible-token/non-fungible-token.js",
    "content": "import {\n  NearBindgen,\n  call,\n  view,\n  initialize,\n  near,\n  LookupMap,\n  assert,\n} from \"near-sdk-js\";\n\nclass Token {\n  constructor(token_id, owner_id) {\n    this.token_id = token_id;\n    this.owner_id = owner_id;\n  }\n}\n\n@NearBindgen({ requireInit: true })\nexport class NftContract {\n  constructor() {\n    this.owner_id = \"\";\n    this.owner_by_id = new LookupMap(\"a\");\n  }\n\n  @initialize({})\n  init({ owner_id, owner_by_id_prefix }) {\n    this.owner_id = owner_id;\n    this.owner_by_id = new LookupMap(owner_by_id_prefix);\n  }\n\n  internalTransfer({\n    sender_id,\n    receiver_id,\n    token_id,\n    approval_id: _ai,\n    memo: _m,\n  }) {\n    let owner_id = this.owner_by_id.get(token_id);\n\n    assert(owner_id !== null, \"Token not found\");\n    assert(sender_id === owner_id, \"Sender must be the current owner\");\n    assert(owner_id !== receiver_id, \"Current and next owner must differ\");\n\n    this.owner_by_id.set(token_id, receiver_id);\n\n    return owner_id;\n  }\n\n  @call({})\n  nftTransfer({ receiver_id, token_id, approval_id, memo }) {\n    let sender_id = near.predecessorAccountId();\n    this.internalTransfer({\n      sender_id,\n      receiver_id,\n      token_id,\n      approval_id,\n      memo,\n    });\n  }\n\n  @call({})\n  nftTransferCall({ receiver_id, token_id, approval_id, memo, msg }) {\n    near.log(\n      `nftTransferCall called, receiver_id ${receiver_id}, token_id ${token_id}`\n    );\n    let sender_id = near.predecessorAccountId();\n    let old_owner_id = this.internalTransfer({\n      sender_id,\n      receiver_id,\n      token_id,\n      approval_id,\n      memo,\n    });\n\n    const promise = near.promiseBatchCreate(receiver_id);\n    near.promiseBatchActionFunctionCall(\n      promise,\n      \"nftOnTransfer\",\n        JSON.stringify({\n          senderId: sender_id,\n          previousOwnerId: old_owner_id,\n          tokenId: token_id,\n          msg: msg,\n        }),\n      0,\n      30000000000000\n    );\n    near.promiseThen(\n      promise,\n      near.currentAccountId(),\n      \"_nftResolveTransfer\",\n      JSON.stringify({ sender_id, receiver_id, token_id }),\n      0,\n      30000000000000\n    );\n  }\n\n  @call({ privateFunction: true })\n  _nftResolveTransfer({ sender_id, receiver_id, token_id }) {\n    near.log(\n      `_nftResolveTransfer called, receiver_id ${receiver_id}, token_id ${token_id}`\n    );\n    const isTokenTransfered = JSON.parse(near.promiseResult(0));\n    near.log(\n      `${token_id} ${\n        isTokenTransfered ? \"was transfered\" : \"was NOT transfered\"\n      }`\n    );\n\n    if (!isTokenTransfered) {\n      near.log(`Returning ${token_id} to ${receiver_id}`);\n      const currentOwner = this.owner_by_id.get(token_id);\n      if (currentOwner === receiver_id) {\n        this.internalTransfer({\n          sender_id: receiver_id,\n          receiver_id: sender_id,\n          token_id: token_id,\n          approval_id: null,\n          memo: null,\n        });\n        near.log(`${token_id} returned to ${sender_id}`);\n        return;\n      }\n      near.log(\n        `Failed to return ${token_id}. It was burned or not owned by ${receiver_id} now.`\n      );\n    }\n  }\n\n  @call({})\n  nftMint({ token_id, token_owner_id, token_metadata: _ }) {\n    let sender_id = near.predecessorAccountId();\n    assert(sender_id === this.owner_id, \"Unauthorized\");\n    assert(this.owner_by_id.get(token_id) === null, \"Token ID must be unique\");\n\n    this.owner_by_id.set(token_id, token_owner_id);\n\n    return new Token(token_id, token_owner_id);\n  }\n\n  @view({})\n  nftToken({ token_id }) {\n    let owner_id = this.owner_by_id.get(token_id);\n    if (owner_id === null) {\n      return null;\n    }\n\n    return new Token(token_id, owner_id);\n  }\n}\n"
  },
  {
    "path": "examples/src/non-fungible-token/test-approval-receiver.ts",
    "content": "import {\n  initialize,\n  near,\n  NearBindgen,\n  NearPromise,\n  PromiseOrValue,\n  assert,\n  call,\n  serialize,\n} from \"near-sdk-js\";\nimport { AccountId } from \"near-sdk-js\";\nimport { NonFungibleTokenApprovalReceiver } from \"near-contract-standards/lib/non_fungible_token/approval/approval_receiver\";\n\nconst BASE_GAS = 20_000_000_000_000n;\nconst PROMISE_CALL = 20_000_000_000_000n;\nconst GAS_FOR_NFT_ON_APPROVE = BASE_GAS + PROMISE_CALL;\n\ninterface ValueReturnInterface {\n  ok_go({ msg }: { msg: string }): PromiseOrValue<string>;\n}\n\n@NearBindgen({ requireInit: true })\nexport class ApprovalReceiver\n  implements NonFungibleTokenApprovalReceiver, ValueReturnInterface\n{\n  public non_fungible_token_account_id: AccountId;\n\n  constructor() {\n    this.non_fungible_token_account_id = \"\";\n  }\n\n  @call({})\n  nft_on_approve({\n    token_id,\n    owner_id,\n    approval_id,\n    msg,\n  }: {\n    token_id: string;\n    owner_id: string;\n    approval_id: bigint;\n    msg: string;\n  }): PromiseOrValue<string> {\n    assert(\n      near.predecessorAccountId() === this.non_fungible_token_account_id,\n      \"Only supports the one non-fungible token contract\"\n    );\n\n    near.log(\n      `in nft_on_approve; token_id=${token_id}, owner_id=${owner_id}, approval_id=${approval_id}, msg=${msg}`\n    );\n    switch (msg) {\n      case \"return-now\":\n        return \"cool\";\n      default: {\n        const prepaid_gas = near.prepaidGas();\n        const account_id = near.currentAccountId();\n        return NearPromise.new(account_id).functionCallRaw(\n          \"ok_go\",\n          serialize({ msg }),\n          0n,\n          prepaid_gas - GAS_FOR_NFT_ON_APPROVE\n        );\n      }\n    }\n  }\n\n  @call({})\n  ok_go({ msg }: { msg: string }): PromiseOrValue<string> {\n    near.log(`in ok_go, msg=${msg}`);\n    return msg;\n  }\n\n  @initialize({})\n  init({\n    non_fungible_token_account_id,\n  }: {\n    non_fungible_token_account_id: AccountId;\n  }) {\n    this.non_fungible_token_account_id = non_fungible_token_account_id;\n  }\n}\n"
  },
  {
    "path": "examples/src/non-fungible-token/test-token-receiver.ts",
    "content": "import { NonFungibleTokenReceiver } from \"near-contract-standards/lib/non_fungible_token/core/receiver\";\nimport {\n  assert,\n  call,\n  initialize,\n  near,\n  NearBindgen,\n  NearPromise,\n  PromiseOrValue,\n  serialize,\n} from \"near-sdk-js\";\nimport { AccountId } from \"near-sdk-js\";\n\nconst BASE_GAS = 10_000_000_000_000n;\nconst PROMISE_CALL = 10_000_000_000_000n;\nconst GAS_FOR_NFT_ON_TRANSFER = BASE_GAS + PROMISE_CALL;\n\ninterface ValueReturnInterface {\n  ok_go({ return_it }: { return_it: boolean }): PromiseOrValue<boolean>;\n}\n\n@NearBindgen({ requireInit: true })\nexport class TokenReceiver\n  implements NonFungibleTokenReceiver, ValueReturnInterface\n{\n  public non_fungible_token_account_id: AccountId;\n\n  constructor() {\n    this.non_fungible_token_account_id = \"\";\n  }\n\n  @initialize({})\n  init({\n    non_fungible_token_account_id,\n  }: {\n    non_fungible_token_account_id: AccountId;\n  }) {\n    this.non_fungible_token_account_id = non_fungible_token_account_id;\n  }\n\n  @call({})\n  nft_on_transfer({\n    sender_id,\n    previous_owner_id,\n    token_id,\n    msg,\n  }: {\n    sender_id: string;\n    previous_owner_id: string;\n    token_id: string;\n    msg: string;\n  }): PromiseOrValue<boolean> {\n    assert(\n      near.predecessorAccountId() === this.non_fungible_token_account_id,\n      \"Only supports the one non-fungible token contract\"\n    );\n    near.log(\n      `in nft_on_transfer; sender_id=${sender_id}, previous_owner_id=${previous_owner_id}, token_id=${token_id}, msg=${msg}`\n    );\n    switch (msg) {\n      case \"return-it-now\":\n        return true;\n      case \"return-it-later\": {\n        const prepaid_gas = near.prepaidGas();\n        const account_id = near.currentAccountId();\n        return NearPromise.new(account_id).functionCallRaw(\n          \"ok_go\",\n          serialize({ return_it: true }),\n          0n,\n          prepaid_gas - GAS_FOR_NFT_ON_TRANSFER\n        );\n      }\n      case \"keep-it-now\":\n        return false;\n      case \"keep-it-later\": {\n        const prepaid_gas = near.prepaidGas();\n        const account_id = near.currentAccountId();\n        return NearPromise.new(account_id).functionCallRaw(\n          \"ok_go\",\n          serialize({ return_it: false }),\n          0n,\n          prepaid_gas - GAS_FOR_NFT_ON_TRANSFER\n        );\n      }\n      default:\n        throw new Error(\"unsupported msg\");\n    }\n  }\n\n  @call({})\n  ok_go({ return_it }: { return_it: boolean }): PromiseOrValue<boolean> {\n    near.log(`in ok_go, return_it=${return_it}`);\n    return return_it;\n  }\n}\n"
  },
  {
    "path": "examples/src/parking-lot.ts",
    "content": "import { NearBindgen, near, call, view, LookupMap } from \"near-sdk-js\";\n\nclass CarSpecs {\n  id: number;\n  color: string;\n  price: number;\n  engine: Engine;\n\n  constructor(id: number, color: string, price: number, engine: Engine) {\n    this.id = id;\n    this.color = color;\n    this.price = price;\n    this.engine = engine;\n  }\n}\n\nclass Engine {\n  hp: number;\n\n  constructor(hp: number) {\n    this.hp = hp;\n  }\n\n  run(): string {\n    if (this.hp > 400) {\n      return \"boom\";\n    } else {\n      return \"zoom\";\n    }\n  }\n}\n\n@NearBindgen({})\nexport class ParkingLot {\n  cars: LookupMap<CarSpecs>;\n\n  constructor() {\n    this.cars = new LookupMap<CarSpecs>(\"a\");\n  }\n\n  @call({})\n  addCar({\n    name,\n    id,\n    color,\n    price,\n    engineHp,\n  }: {\n    name: string;\n    id: number;\n    color: string;\n    price: number;\n    engineHp: number;\n  }) {\n    // args can be json arguments only, they cannot be of a JS/TS class like following, unless override NearContract.deserializeArgs method.\n    // addCar({ name, specs }: { name: string, specs: CarSpecs }) {\n    const engine = new Engine(engineHp);\n    const car = new CarSpecs(id, color, price, engine);\n    near.log(`addCar() called, name: ${name}, specs: ${JSON.stringify(car)}`);\n    this.cars.set(name, car);\n  }\n\n  @call({})\n  removeCar({ name }: { name: string }) {\n    near.log(`removeCar() called, name: ${name}`);\n    this.cars.remove(name);\n  }\n\n  @view({})\n  getCarSpecs({ name }: { name: string }): CarSpecs {\n    near.log(`getCarSpecs() called, name: ${name}`);\n    return this.cars.get(name);\n  }\n\n  @view({})\n  runCar({ name }: { name: string }) {\n    /* We are getting plain carSpecs object from the storage.\n        It needs to be converted to the class object in order to execute engine.run() function.*/\n    const carSpecs = this.cars.get(name) as CarSpecs;\n    const engine = new Engine(carSpecs.engine.hp);\n    return engine.run();\n  }\n}\n"
  },
  {
    "path": "examples/src/programmatic-updates/programmatic-update-after.ts",
    "content": "import { NearBindgen, near, initialize, assert, view } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class ProgrammaticUpdateAfter {\n  greeting = \"Hello\";\n\n  @initialize({ privateFunction: true })\n  init({ manager }: { manager: string }) {\n    near.log(`Setting manager to be ${manager}`);\n    near.storageWrite(\"MANAGER\", manager);\n  }\n\n  @view({}) // Method renamed and return \"Hi\" when greeting is \"Hello\"\n  view_greeting(): string {\n    return this.greeting.replace(\"Hello\", \"Hi\");\n  }\n}\n\nexport function updateContract() {\n  const manager = near.storageRead(\"MANAGER\");\n  assert(\n    near.predecessorAccountId() === manager,\n    \"Only the manager can update the code\"\n  );\n\n  const promiseId = near.promiseBatchCreate(near.currentAccountId());\n  near.promiseBatchActionDeployContract(promiseId, near.inputRaw());\n\n  return near.promiseReturn(promiseId);\n}\n"
  },
  {
    "path": "examples/src/programmatic-updates/programmatic-update-before.ts",
    "content": "import { NearBindgen, near, initialize, assert, view } from \"near-sdk-js\";\n\n@NearBindgen({ requireInit: true })\nexport class ProgrammaticUpdateBefore {\n  greeting = \"Hello\";\n\n  @initialize({ privateFunction: true })\n  init({ manager }: { manager: string }) {\n    near.log(`Setting manager to be ${manager}`);\n    near.storageWrite(\"MANAGER\", manager);\n  }\n\n  @view({}) // This method will be renamed after update and will return \"Hi\" if greeting is \"Hello\"\n  get_greeting(): string {\n    return this.greeting;\n  }\n}\n\nexport function updateContract() {\n  const manager = near.storageRead(\"MANAGER\");\n  assert(\n    near.predecessorAccountId() === manager,\n    \"Only the manager can update the code\"\n  );\n\n  const promiseId = near.promiseBatchCreate(near.currentAccountId());\n  near.promiseBatchActionDeployContract(promiseId, near.inputRaw());\n\n  return near.promiseReturn(promiseId);\n}\n"
  },
  {
    "path": "examples/src/state-migration/state-migration-new.ts",
    "content": "import { NearBindgen, view, near, migrate, call, Vector, assert } from 'near-sdk-js'\nimport { AccountId } from 'near-sdk-js/lib/types'\n\ntype OldMessageFormat = {\n    sender: AccountId,\n    header: string,\n    text: string,\n}\n\n// This is the new version of the Message type, it has an additional field\ntype NewMessageFormat = {\n    sender: AccountId,\n    recipient?: AccountId,\n    header: string,\n    text: string,\n}\n\n@NearBindgen({})\nexport class MigrationDemo {\n    messages: Vector<NewMessageFormat>;\n\n    constructor() {\n        this.messages = new Vector<NewMessageFormat>('messages');\n    }\n\n    @call({ payableFunction: true })\n    addMessage({ message }: {\n        message: NewMessageFormat\n    }): void {\n        this.messages.push(message);\n        near.log(`${near.signerAccountId()} added message ${JSON.stringify(message)}`);\n    }\n\n    @view({})\n    countMessages(): number {\n        return this.messages.toArray().length;\n    }\n\n\n    @migrate({})\n    migrateState(): Vector<NewMessageFormat> {\n        assert(this.messages.toArray().length == 0, \"Contract state should not be deserialized in @migrate\");\n        // retrieve the current state from the contract\n        let raw_vector = JSON.parse(near.storageRead(\"STATE\")).messages;\n        let old_messages: Vector<OldMessageFormat> = new Vector<OldMessageFormat>(raw_vector.prefix, raw_vector.length);\n        near.log(\"old_messages: \" + JSON.stringify(old_messages));\n\n        // iterate through the state migrating it to the new version\n        let new_messages: Vector<NewMessageFormat> = new Vector('messages');\n\n        for (let old_message of old_messages) {\n            near.log(`migrating ${JSON.stringify(old_message)}`);\n            const new_message: NewMessageFormat = {\n                sender: old_message.sender,\n                recipient: \"Unknown\",\n                header: old_message.header,\n                text: old_message.text,\n            };\n            if (new_message.text.length < 10) {\n                near.log(`adding ${new_message} to new_messages`);\n                new_messages.push(new_message);\n            } else {\n                near.log(`${new_message} is too long, skipping`);\n            }\n        }\n\n        this.messages = new_messages;\n\n        return this.messages;\n    }\n}"
  },
  {
    "path": "examples/src/state-migration/state-migration-original.ts",
    "content": "import { NearBindgen, view, near, call, Vector } from 'near-sdk-js'\nimport { AccountId } from 'near-sdk-js/lib/types'\n\ntype Message = {\n    sender: AccountId,\n    header: string,\n    text: string,\n}\n\n@NearBindgen({})\nexport class MigrationDemo {\n    messages: Vector<Message>;\n\n    constructor() {\n        this.messages = new Vector<Message>('messages');\n    }\n\n    @call({ payableFunction: true })\n    addMessage({ message }: {\n        message: Message\n    }): void {\n        this.messages.push(message);\n        near.log(`${near.signerAccountId()} added message ${JSON.stringify(message)}`);\n    }\n\n    @view({})\n    countMessages(): number {\n        return this.messages.toArray().length;\n    }\n}"
  },
  {
    "path": "examples/src/status-deserialize-class.js",
    "content": "import {\n    NearBindgen,\n    call,\n    view,\n    near,\n    UnorderedMap,\n    LookupMap,\n    Vector,\n    UnorderedSet,\n} from \"near-sdk-js\";\n\nclass Car {\n    static schema = {\n        name: \"string\",\n        speed: \"number\",\n    };\n    constructor() {\n        this.name = \"\";\n        this.speed = 0;\n    }\n\n    info() {\n        return this.name + \" run with speed \" + this.speed.toString()\n    }\n}\n\nclass Truck {\n    static schema = {\n        name: \"string\",\n        speed: \"number\",\n        loads: UnorderedMap\n    };\n    constructor() {\n        this.name = \"\";\n        this.speed = 0;\n        this.loads = new UnorderedMap(\"tra\");\n    }\n\n    info() {\n        return this.name + \" run with speed \" + this.speed.toString() + \" with loads length: \" + this.loads.toArray().length;\n    }\n}\n\n// sdk should first try if UnorderedMap has a static schema and use it to recursively decode.\n// In this case, UnorderedMap doesn't.\n// So sdk should next try call UnorderedMap.reconstruct.\n@NearBindgen({})\nexport class StatusDeserializeClass {\n    static schema = {\n        truck: Truck,\n        efficient_recordes: UnorderedMap,\n        nested_efficient_recordes: {class: UnorderedMap, value: UnorderedMap},\n        nested_lookup_recordes:  {class: UnorderedMap, value: LookupMap},\n        vector_nested_group: {class: Vector, value: LookupMap},\n        lookup_nest_vec: { class: LookupMap, value: Vector },\n        unordered_set: UnorderedSet,\n        user_car_map: {class: UnorderedMap, value: Car },\n        big_num: 'bigint',\n        date: 'date'\n    };\n    constructor() {\n        this.is_inited = false;\n        this.records = {};\n        this.truck = new Truck();\n        this.messages = [];\n        // account_id -> message\n        this.efficient_recordes = new UnorderedMap(\"a\");\n        // id -> account_id -> message\n        this.nested_efficient_recordes = new UnorderedMap(\"b\");\n        // id -> account_id -> message\n        this.nested_lookup_recordes = new UnorderedMap(\"c\");\n        // index -> account_id -> message\n        this.vector_nested_group = new Vector(\"d\");\n        // account_id -> index -> message\n        this.lookup_nest_vec = new LookupMap(\"e\");\n        this.unordered_set = new UnorderedSet(\"f\");\n        this.user_car_map = new UnorderedMap(\"g\");\n        this.big_num = 1n;\n        this.date = new Date();\n        this.message_without_schema_defined = \"\";\n        this.number_without_schema_defined = 0;\n        this.records_without_schema_defined = {};\n    }\n\n    @call({})\n    init_contract({ }) {\n        if (this.is_inited) {\n            near.log(`message inited`);\n            return;\n        }\n        this.is_inited = true;\n    }\n\n    @view({})\n    is_contract_inited({}) {\n        near.log(`query is_contract_inited`);\n        return this.is_inited;\n    }\n\n    @call({})\n    set_record({ message }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_status with message ${message}`);\n        this.records[account_id] = message;\n    }\n\n    @view({})\n    get_record({ account_id }) {\n        near.log(`get_record for account_id ${account_id}`);\n        return this.records[account_id] || null;\n    }\n\n\n    @call({})\n    set_truck_info({ name, speed }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_truck_info name ${name}, speed ${speed}`);\n        let truck = new Truck();\n        truck.name = name;\n        truck.speed = speed;\n        truck.loads = this.truck.loads;\n        this.truck = truck;\n        let car = new Car();\n        car.name = name;\n        car.speed = speed;\n        this.user_car_map.set(account_id, car);\n    }\n\n    @call({})\n    add_truck_load({ name, load }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} add_truck_load name ${name}, load ${load}`);\n        this.truck.loads.set(name, load);\n    }\n\n    @view({})\n    get_truck_info({ }) {\n        near.log(`get_truck_info`);\n        return this.truck.info();\n    }\n\n    @view({})\n    get_user_car_info({ account_id }) {\n        near.log(`get_user_car_info for account_id ${account_id}`);\n        let car = this.user_car_map.get(account_id);\n        if (car == null) {\n            return null;\n        }\n        return car.info();\n    }\n\n    @call({})\n    push_message({ message }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} push_message message ${message}`);\n        this.messages.push(message);\n    }\n\n    @view({})\n    get_messages({ }) {\n        near.log(`get_messages`);\n        return this.messages.join(',');\n    }\n\n    @call({})\n    set_nested_efficient_recordes({ message, id }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_nested_efficient_recordes with message ${message},id ${id}`);\n        this.efficient_recordes.set(account_id, message);\n        const nestedMap = this.nested_efficient_recordes.get(id, {\n            defaultValue: new UnorderedMap(\"i_\" + id + \"_\"),\n        });\n        nestedMap.set(account_id, message);\n        this.nested_efficient_recordes.set(id, nestedMap);\n\n        const nestedLookup = this.nested_lookup_recordes.get(id, {\n            defaultValue: new LookupMap(\"li_\" + id + \"_\"),\n        });\n        nestedLookup.set(account_id, message);\n        this.nested_lookup_recordes.set(id, nestedLookup);\n\n        // vector_nested_group: {vector: {value: { lookup_map: {value: 'string'}}}},\n        const vecNestedLookup = this.vector_nested_group.get(0, {\n            defaultValue: new LookupMap(\"di_0_\"),\n        });\n        vecNestedLookup.set(account_id, message);\n        if (this.vector_nested_group.isEmpty()) {\n            this.vector_nested_group.push(vecNestedLookup);\n        } else {\n            this.vector_nested_group.replace(0, vecNestedLookup);\n        }\n\n        const lookupNestVec = this.lookup_nest_vec.get(account_id, {\n            defaultValue: new Vector(\"ei_\" + account_id + \"_\"),\n        });\n        lookupNestVec.push(message);\n        this.lookup_nest_vec.set(account_id, lookupNestVec);\n\n        this.unordered_set.set(account_id);\n    }\n\n    @call({})\n    set_big_num_and_date({ bigint_num, new_date }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_bigint_and_date bigint_num ${bigint_num}, new_date: ${new_date}`);\n        this.big_num = bigint_num;\n        this.date = new_date;\n    }\n\n    @view({})\n    get_big_num({ }) {\n        near.log(`get_big_num`);\n        return this.big_num;\n    }\n\n    @view({})\n    get_date({ }) {\n        near.log(`get_date`);\n        return this.date;\n    }\n\n    @view({})\n    get_efficient_recordes({ account_id }) {\n        near.log(`get_efficient_recordes for account_id ${account_id}`);\n        return this.efficient_recordes.get(account_id);\n    }\n\n    @view({})\n    get_nested_efficient_recordes({ account_id, id }) {\n        near.log(`get_nested_efficient_recordes for account_id ${account_id}, id ${id}`);\n        return this.nested_efficient_recordes.get(id, {\n            defaultValue: new UnorderedMap(\"i_\" + id + \"_\"),\n        }).get(account_id);\n    }\n\n    @view({})\n    get_nested_lookup_recordes({ account_id, id }) {\n        near.log(`get_nested_lookup_recordes for account_id ${account_id}, id ${id}`);\n        return this.nested_lookup_recordes.get(id, {\n            defaultValue: new LookupMap(\"li_\" + id + \"_\"),\n        }).get(account_id);\n    }\n\n    @view({})\n    get_vector_nested_group({ idx, account_id }) {\n        near.log(`get_vector_nested_group for idx ${idx}, account_id ${account_id}`);\n        return this.vector_nested_group.get(idx).get(account_id);\n    }\n\n    @view({})\n    get_lookup_nested_vec({ account_id, idx }) {\n        near.log(`get_looup_nested_vec for account_id ${account_id}, idx ${idx}`);\n        return this.lookup_nest_vec.get(account_id).get(idx);\n    }\n\n    @view({})\n    get_is_contains_user({ account_id }) {\n        near.log(`get_is_contains_user for account_id ${account_id}`);\n        return this.unordered_set.contains(account_id);\n    }\n\n    @call({})\n    set_extra_data({ message, number }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_extra_data message ${message}, number: ${number}`);\n        this.message_without_schema_defined = message;\n        this.number_without_schema_defined = number;\n    }\n\n    @view({})\n    get_extra_msg({ }) {\n        near.log(`get_extra_msg`);\n        return this.message_without_schema_defined;\n    }\n\n    @view({})\n    get_extra_number({ }) {\n        near.log(`get_extra_number`);\n        return this.number_without_schema_defined;\n    }\n\n    @call({})\n    set_extra_record({ message }) {\n        let account_id = near.signerAccountId();\n        near.log(`${account_id} set_extra_record with message ${message}`);\n        this.records_without_schema_defined[account_id] = message;\n    }\n\n    @view({})\n    get_extra_record({ account_id }) {\n        near.log(`get_extra_record for account_id ${account_id}`);\n        return this.records_without_schema_defined[account_id] || null;\n    }\n\n    @view({})\n    get_subtype_of_efficient_recordes({  }) {\n        near.log(`get_subtype_of_efficient_recordes`);\n        return this.efficient_recordes.subtype();\n    }\n\n    @view({})\n    get_subtype_of_nested_efficient_recordes({  }) {\n        near.log(`get_subtype_of_nested_efficient_recordes`);\n        return this.nested_efficient_recordes.subtype();\n    }\n\n    @view({})\n    get_subtype_of_nested_lookup_recordes({  }) {\n        near.log(`get_subtype_of_nested_lookup_recordes`);\n        return this.nested_lookup_recordes.subtype();\n    }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message-borsh.js",
    "content": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\nimport * as borsh from 'borsh';\n\nconst schema = {\n    struct: { records: {map: { key: 'string', value: 'string' }} }\n};\n\n@NearBindgen({\n    serializer(statusMessage) {\n        return borsh.serialize(schema, statusMessage);\n    },\n    deserializer(value) {\n        return borsh.deserialize(schema, value);\n    }\n})\nexport class StatusMessage {\n    constructor() {\n        this.records = new Map()\n    }\n\n    @call({})\n    set_status({ message }) {\n        let account_id = near.signerAccountId()\n        env.log(`${account_id} set_status with message ${message}`)\n        this.records.set(account_id, message)\n    }\n\n    @view({})\n    get_status({ account_id }) {\n        env.log(`get_status for account_id ${account_id}`)\n        return this.records.get(account_id) || null\n    }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message-collections.js",
    "content": "import {\n  NearBindgen,\n  call,\n  view,\n  near,\n  LookupSet,\n  UnorderedMap,\n} from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class StatusMessage {\n  constructor() {\n    this.records = new UnorderedMap(\"a\");\n    this.uniqueValues = new LookupSet(\"b\");\n  }\n\n  @call({})\n  set_status({ message }) {\n    let account_id = near.signerAccountId();\n    near.log(`${account_id} set_status with message ${message}`);\n    this.records.set(account_id, message);\n    this.uniqueValues.set(message);\n  }\n\n  @view({})\n  get_status({ account_id }) {\n    near.log(`get_status for account_id ${account_id}`);\n    return this.records.get(account_id);\n  }\n\n  @view({})\n  has_status({ message }) {\n    // used for test LookupMap\n    return this.uniqueValues.contains(message);\n  }\n\n  @view({})\n  get_all_statuses() {\n    // used for test UnorderedMap\n    return this.records.toArray();\n  }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message-deserialize-err.js",
    "content": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\n\n@NearBindgen({\n    deserializer(_value) {\n        throw new Error('deserialize err')\n    },\n})\nexport class StatusMessage {\n    constructor() {\n        this.records = new Map()\n    }\n\n    @call({})\n    set_status({ message }) {\n        let account_id = near.signerAccountId()\n        env.log(`${account_id} set_status with message ${message}`)\n        this.records.set(account_id, message)\n    }\n\n    @view({})\n    get_status({ account_id }) {\n        env.log(`get_status for account_id ${account_id}`)\n        return this.records.get(account_id) || null\n    }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message-migrate-add-field.js",
    "content": "import {NearBindgen, call, view, near, migrate, assert} from \"near-sdk-js\";\n\nclass OldStatusMessage {\n  constructor() {\n    this.records = {};\n  }\n}\n\n@NearBindgen({})\nexport class StatusMessage {\n  constructor() {\n    this.records = {};\n    this.new_fields = {};\n  }\n\n  @call({})\n  set_status({ message }) {\n    let account_id = near.signerAccountId();\n    near.log(`${account_id} set_status with message ${message}`);\n    this.records[account_id] = message;\n  }\n\n  @call({})\n  set_new_status({ message }) {\n    let account_id = near.signerAccountId();\n    near.log(`${account_id} set_new_status with message ${message}`);\n    this.new_fields[account_id] = message;\n  }\n\n  @view({})\n  get_status({ account_id }) {\n    near.log(`get_status for account_id ${account_id}`);\n    return this.records[account_id] || null;\n  }\n\n  @view({})\n  get_new_status({ account_id }) {\n    near.log(`get_new_status for account_id ${account_id}`);\n    return this.records[account_id] || null;\n  }\n\n  // Migrate from OldStatusMessage to StatusMessage\n  @migrate({})\n  migrateState() {\n    assert(this.records !== undefined, \"Contract state should not be deserialized in @migrate\");\n    // retrieve the current state from the contract\n    let records = JSON.parse(near.storageRead(\"STATE\")).records;\n\n    this.records = records;\n    this.new_fields = {};\n  }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message-serialize-err.js",
    "content": "import {NearBindgen, call, view, near} from \"near-sdk-js\";\n\n@NearBindgen({\n    serializer(_value) {\n        throw new Error('serialize err')\n    },\n})\nexport class StatusMessage {\n    constructor() {\n        this.records = new Map()\n    }\n\n    @call({})\n    set_status({ message }) {\n        let account_id = near.signerAccountId()\n        env.log(`${account_id} set_status with message ${message}`)\n        this.records.set(account_id, message)\n    }\n\n    @view({})\n    get_status({ account_id }) {\n        env.log(`get_status for account_id ${account_id}`)\n        return this.records.get(account_id) || null\n    }\n}\n"
  },
  {
    "path": "examples/src/status-message/status-message.js",
    "content": "import { NearBindgen, call, view, near } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class StatusMessage {\n  constructor() {\n    this.records = {};\n  }\n\n  @call({})\n  set_status({ message }) {\n    let account_id = near.signerAccountId();\n    near.log(`${account_id} set_status with message ${message}`);\n    this.records[account_id] = message;\n  }\n\n  @view({})\n  get_status({ account_id }) {\n    near.log(`get_status for account_id ${account_id}`);\n    return this.records[account_id] || null;\n  }\n}\n"
  },
  {
    "path": "examples/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"experimentalDecorators\": true,\n    \"target\": \"es2020\",\n    \"moduleResolution\": \"node\",\n    \"noEmit\": true\n  },\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "generate-docs-markdown.js",
    "content": "const { readFileSync, writeFileSync, unlinkSync } = require(\"fs\");\nconst { execSync } = require(\"child_process\");\n\n// Load the base configuration from typedoc.json\nconst baseConfig = JSON.parse(readFileSync(\"./typedoc.json\", \"utf8\"));\n\n// Extend the base configuration for Markdown documentation\nconst markdownConfig = {\n  ...baseConfig,\n  githubPages: false,\n  out: \"markdown-docs\",\n  plugin: [\"typedoc-plugin-markdown\"],\n};\n\n// Write the extended configuration to a temporary file\nconst configFilePath = \"./typedoc-markdown.json\";\nwriteFileSync(configFilePath, JSON.stringify(markdownConfig, null, 2));\n\n// Run TypeDoc with the extended configuration\ntry {\n  execSync(`npx typedoc --options ${configFilePath}`, { stdio: \"inherit\" });\n} finally {\n  // Clean up the temporary file\n  unlinkSync(configFilePath);\n}\n"
  },
  {
    "path": "near-sdk-js@2.0.0-diff-1.0.0.md",
    "content": "# Breaking features diff from SDK 2.0.0 to 1.0.0\n## borsh data de/serializer for contract state\n* using for: new contracts or migrate from a borsh serialized contract\n[example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message/status-message-borsh.js)\n```js\n@NearBindgen({\n    serializer(statusMessage) {\n        return borsh.serialize(schema, statusMessage);\n    },\n    deserializer(value) {\n        return borsh.deserialize(schema, value);\n    }\n})\nexport class StatusMessage {\n    constructor() {\n        this.records = new Map()\n    }\n\n    @call({})\n    set_status({ message }) {\n        let account_id = near.signerAccountId()\n        env.log(`${account_id} set_status with message ${message}`)\n        this.records.set(account_id, message)\n    }\n\n    @view({})\n    get_status({ account_id }) {\n        env.log(`get_status for account_id ${account_id}`)\n        return this.records.get(account_id) || null\n    }\n}\n```\n\n## js contract migration with data fields\n### example1\n* using for: contract state migrations\n* [example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message/status-message-migrate-add-field.js)\n```js\nimport {NearBindgen, call, view, near, migrate, Vector, assert} from \"near-sdk-js\";\n\nclass OldStatusMessage {\n  constructor() {\n    this.records = {};\n  }\n}\n\n@NearBindgen({})\nexport class StatusMessage {\n  constructor() {\n    this.records = {};\n    this.new_fields = {}; // new added filed\n  }\n  ...\n\n  // Migrate from OldStatusMessage to StatusMessage\n  @migrate({})\n  migrateState() {\n    assert(this.records !== undefined, \"Contract state should not be deserialized in @migrate\");\n    // retrieve the current state from the contract\n    let records = JSON.parse(near.storageRead(\"STATE\")).records;\n\n    this.records = records;\n    this.new_fields = {};\n  }\n}\n```\n### example2\n* another migration example can be found in [test-basic-updates.ava.js](./examples/__tests__/test-basic-updates.ava.js) with [old state contract](./examples/src/basic-updates/basic-updates-base.js) and new [new state contract](./examples/src/basic-updates/basic-updates-update.js).  \nwith the test command in [examples directory](./examples):\n```shell\npnpm run test:basic-updates\n```\n\n## auto reconstruct class from object by static json schema\n* use for contract serialzed by default method(json), the detail document is here: https://github.com/near/near-sdk-js/blob/develop/AUTO_RECONSCTRUCT_BY_JSON_SCHEME.md#the-schema-format\n* [example](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-deserialize-class.js#L49)\n```js\nclass Car {\n    static schema = {\n        name: \"string\",\n        speed: \"number\",\n    };\n    constructor() {\n        this.name = \"\";\n        this.speed = 0;\n    }\n\n    info() {\n        return this.name + \" run with speed \" + this.speed.toString()\n    }\n}\n\nclass Truck {\n    static schema = {\n        name: \"string\",\n        speed: \"number\",\n        loads: UnorderedMap\n    };\n    constructor() {\n        this.name = \"\";\n        this.speed = 0;\n        this.loads = new UnorderedMap(\"tra\");\n    }\n\n    info() {\n        return this.name + \" run with speed \" + this.speed.toString() + \" with loads length: \" + this.loads.toArray().length;\n    }\n}\n\n// sdk should first try if UnorderedMap has a static schema and use it to recursively decode.\n@NearBindgen({})\nexport class StatusDeserializeClass {\n    static schema = {\n        truck: Truck,\n        efficient_recordes: UnorderedMap,\n        nested_efficient_recordes: {class: UnorderedMap, value: UnorderedMap},\n        nested_lookup_recordes:  {class: UnorderedMap, value: LookupMap},\n        vector_nested_group: {class: Vector, value: LookupMap},\n        lookup_nest_vec: { class: LookupMap, value: Vector },\n        unordered_set: UnorderedSet,\n        user_car_map: {class: UnorderedMap, value: Car },\n        big_num: 'bigint',\n        date: 'date'\n    };\n    constructor() {\n        this.is_inited = false;\n        this.records = {};\n        this.truck = new Truck();\n        this.messages = [];\n        this.efficient_recordes = new UnorderedMap(\"a\");\n        this.nested_efficient_recordes = new UnorderedMap(\"b\");\n        this.nested_lookup_recordes = new UnorderedMap(\"c\");\n        this.vector_nested_group = new Vector(\"d\");\n        this.lookup_nest_vec = new LookupMap(\"e\");\n        this.unordered_set = new UnorderedSet(\"f\");\n        this.user_car_map = new UnorderedMap(\"g\");\n        this.big_num = 1n;\n        this.date = new Date();\n        this.message_without_schema_defined = \"\";\n        this.number_without_schema_defined = 0;\n        this.records_without_schema_defined = {};\n    }\n    ...\n}\n```\n\n## query data Nesting of objects in SDK Collections without Nested Collection's reconstructor\n* using for SDK Collections which has description in static json schema\nIn [near-sdk-js 1.0.0](https://www.npmjs.com/package/near-sdk-js/v/1.0.0), users needed to call a `reconstructor` method in order for **Nested Collections** to be properly decoded:\n```typescript\n@NearBindgen({})\nexport class Contract {\n    outerMap: UnorderedMap<UnorderedMap<string>>;\n\n    constructor() {\n        this.outerMap = new UnorderedMap(\"o\");\n    }\n\n    @view({})\n    get({id, accountId}: { id: string; accountId: string }) {\n        const innerMap = this.outerMap.get(id, {\n            reconstructor: UnorderedMap.reconstruct,  // we need to announce reconstructor explicit\n        });\n        if (innerMap === null) {\n            return null;\n        }\n        return innerMap.get(accountId);\n    }\n}\n```\nIn [near-sdk-js 2.0.0](https://www.npmjs.com/package/near-sdk-js/v/2.0.0) With schemas, this is no longer needed, as the SDK can correctly infer how to decode the Nested Collections:\n\n```typescript\n@NearBindgen({})\nexport class Contract {\n    static schema = {\n      outerMap: {class: UnorderedMap, value: UnorderedMap}\n    };\n    \n    outerMap: UnorderedMap<UnorderedMap<string>>;\n\n    constructor() {\n        this.outerMap = new UnorderedMap(\"o\");\n    }\n\n    @view({})\n    get({id, accountId}: { id: string; accountId: string }) {\n        const innerMap = this.outerMap.get(id);  // reconstructor can be infered from static schema\n        if (innerMap === null) {\n            return null;\n        }\n        return innerMap.get(accountId);\n    }\n}\n```\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"private\": true,\n  \"engines\": {\n    \"node\": \">=14 <16.6.0 || >16.6.0\",\n    \"pnpm\": \">=7\"\n  },\n  \"scripts\": {\n    \"preinstall\": \"npx only-allow pnpm\",\n    \"build\": \"turbo run build\",\n    \"test\": \"turbo run test\",\n    \"lint\": \"turbo run lint\",\n    \"format\": \"turbo run format\",\n    \"docs:generate\": \"typedoc\",\n    \"docs:generate-markdown\": \"node generate-docs-markdown.js\"\n  },\n  \"devDependencies\": {\n    \"turbo\": \"1.10.16\",\n    \"typedoc\": \"0.26.6\",\n    \"typedoc-plugin-markdown\": \"4.2.6\",\n    \"typescript\": \"4.7.4\"\n  }\n}"
  },
  {
    "path": "packages/near-contract-standards/.gitignore",
    "content": "build\nnode_modules"
  },
  {
    "path": "packages/near-contract-standards/README.md",
    "content": "# Package for NEAR JS contract standards\n\nThis package provides a set of interfaces and implementations for NEAR's contract standards:\n - NFT\n - FT (NEP-141)\n"
  },
  {
    "path": "packages/near-contract-standards/ava.config.cjs",
    "content": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n  timeout: \"300000\",\n  files: [\"**/*.ava.js\"],\n  failWithoutAssertions: false,\n  extensions: [\"js\"],\n};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/event.d.ts",
    "content": "export declare abstract class NearEvent {\n    private internal_to_json_string;\n    private internal_to_json_event_string;\n    /**\n     * Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit(): void;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/event.js",
    "content": "import { near } from \"near-sdk-js\";\nexport class NearEvent {\n    internal_to_json_string() {\n        return JSON.stringify(this);\n    }\n    internal_to_json_event_string() {\n        return `EVENT_JSON: ${this.internal_to_json_string()}`;\n    }\n    /**\n     * Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        near.log(this.internal_to_json_event_string());\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/core.d.ts",
    "content": "import { AccountId, PromiseOrValue, Balance } from \"near-sdk-js\";\nimport { Option } from \"../non_fungible_token/utils\";\n/**\n * The core methods for a basic fungible token. Extension standards may be\n * added in addition to this interface.\n *\n * # Examples\n *\n * ```typescript\n\n * import { near, call, view, AccountId, PromiseOrValue, Balance } from \"near-sdk-js\";\n * import { Option } from \"../non_fungible_token/utils\";\n * import { FungibleTokenCore, FungibleToken } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *     @call({})\n *     ft_transfer({ receiver_id, amount, memo }: {\n *         receiver_id: AccountId,\n *         amount: Balance,\n *         memo?: String\n *     }): void {\n *         this.token.ft_transfer({ receiver_id, amount, memo });\n *     }\n *\n *     @call({})\n *     ft_transfer_call({ receiver_id, amount, memo, msg }: {\n *         receiver_id: AccountId,\n *         amount: Balance,\n *         memo?: Option<String>,\n *         msg: String\n *     }): PromiseOrValue<bigint> {\n *         return this.token.ft_transfer_call({ receiver_id, amount, memo, msg });\n *     }\n *\n *     @view({})\n *     ft_total_supply(): Balance {\n *         return this.token.ft_total_supply();\n *     }\n *\n *     @view({})\n *     ft_balance_of({ account_id }: { account_id: AccountId }): Balance {\n *         return this.token.ft_balance_of({ account_id });\n *     }\n * }\n * ```\n */\nexport interface FungibleTokenCore {\n    /**\n     * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id`.\n     * Both accounts must be registered with the contract for transfer to succeed. (See [NEP-145](https://github.com/near/NEPs/discussions/145))\n     * This method must to be able to accept attached deposits, and must not panic on attached deposit.\n     * Exactly 1 yoctoNEAR must be attached.\n     * See [the Security section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Arguments:\n     * @param receiver_id - the account ID of the receiver.\n     * @param amount - the amount of tokens to transfer. Must be a positive number in decimal string representation.\n     * @param memo - an optional string field in a free form to associate a memo with this transfer.\n     */\n    ft_transfer({ receiver_id, amount, memo }: {\n        receiver_id: AccountId;\n        amount: Balance;\n        memo?: String;\n    }): any;\n    /**\n     * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id` account. Then\n     * calls `ft_on_transfer` method on `receiver_id` contract and attaches a callback to resolve this transfer.\n     * `ft_on_transfer` method must return the amount of tokens unused by the receiver contract, the remaining tokens\n     * must be refunded to the `predecessor_account_id` at the resolve transfer callback.\n     *\n     * Token contract must pass all the remaining unused gas to the `ft_on_transfer` call.\n     *\n     * Malicious or invalid behavior by the receiver's contract:\n     * - If the receiver contract promise fails or returns invalid value, the full transfer amount must be refunded.\n     * - If the receiver contract overspent the tokens, and the `receiver_id` balance is lower than the required refund\n     * amount, the remaining balance must be refunded. See [the Security section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Both accounts must be registered with the contract for transfer to succeed. (See #145)\n     * This method must to be able to accept attached deposits, and must not panic on attached deposit. Exactly 1 yoctoNEAR must be attached. See [the Security\n     * section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Arguments:\n     * @param receiver_id - the account ID of the receiver contract. This contract will be called.\n     * @param amount - the amount of tokens to transfer. Must be a positive number in a decimal string representation.\n     * @param memo - an optional string field in a free form to associate a memo with this transfer.\n     * @param msg - a string message that will be passed to `ft_on_transfer` contract call.\n     *\n     * @returns a promise which will result in the amount of tokens withdrawn from sender's account.\n     */\n    ft_transfer_call({ receiver_id, amount, memo, msg }: {\n        receiver_id: AccountId;\n        amount: Balance;\n        memo: Option<String>;\n        msg: String;\n    }): PromiseOrValue<bigint>;\n    /** Returns the total supply of the token in a decimal string representation. */\n    ft_total_supply(): Balance;\n    /** Returns the balance of the account. If the account doesn't exist must returns `\"0\"`. */\n    ft_balance_of({ account_id }: {\n        account_id: AccountId;\n    }): Balance;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/core.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/core_impl.d.ts",
    "content": "import { StorageBalance, StorageBalanceBounds, StorageManagement } from \"../storage_management\";\nimport { FungibleTokenCore } from \"./core\";\nimport { FungibleTokenResolver } from \"./resolver\";\nimport { AccountId, LookupMap, Balance, PromiseOrValue, StorageUsage, IntoStorageKey } from \"near-sdk-js\";\nimport { Option } from '../non_fungible_token/utils';\n/** Implementation of a FungibleToken standard\n * Allows to include NEP-141 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - FungibleTokenCore -- interface with ft_transfer methods. FungibleToken provides methods for it.\n *     - FungibleTokenMetaData -- return metadata for the token in NEP-148, up to contract to implement.\n *     - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it.\n *     - AccountRegistrar -- interface for an account to register and unregister\n *\n * For example usage, see examples/src/fungible-token/my-ft.ts\n */\nexport declare class FungibleToken implements FungibleTokenCore, StorageManagement, FungibleTokenResolver {\n    accounts: LookupMap<Balance>;\n    total_supply: Balance;\n    account_storage_usage: StorageUsage;\n    constructor();\n    init(prefix: IntoStorageKey): this;\n    measure_account_storage_usage(): void;\n    internal_unwrap_balance_of(account_id: AccountId): Balance;\n    internal_deposit(account_id: AccountId, amount: Balance): void;\n    internal_withdraw(account_id: AccountId, amount: Balance): void;\n    internal_transfer(sender_id: AccountId, receiver_id: AccountId, amount: Balance, memo?: String): void;\n    internal_register_account(account_id: AccountId): void;\n    /** Internal method that returns the amount of burned tokens in a corner case when the sender\n     * has deleted (unregistered) their account while the `ft_transfer_call` was still in flight.\n     * Returns (Used token amount, Burned token amount)\n     */\n    internal_ft_resolve_transfer(sender_id: AccountId, receiver_id: AccountId, amount: Balance): [bigint, bigint];\n    /** Implementation of FungibleTokenCore */\n    ft_transfer({ receiver_id, amount, memo }: {\n        receiver_id: AccountId;\n        amount: Balance;\n        memo?: String;\n    }): void;\n    ft_transfer_call({ receiver_id, amount, memo, msg }: {\n        receiver_id: AccountId;\n        amount: Balance;\n        memo: Option<String>;\n        msg: string;\n    }): PromiseOrValue<bigint>;\n    ft_total_supply(): Balance;\n    ft_balance_of({ account_id }: {\n        account_id: AccountId;\n    }): Balance;\n    /** Implementation of storage\n     * Internal method that returns the Account ID and the balance in case the account was\n     * unregistered.\n     */\n    internal_storage_unregister(force?: boolean): Option<[AccountId, Balance]>;\n    internal_storage_balance_of(account_id: AccountId): Option<StorageBalance>;\n    /** Implementation of StorageManagement\n     * @param registration_only doesn't affect the implementation for vanilla fungible token.\n     */\n    storage_deposit({ account_id, registration_only, }: {\n        account_id?: AccountId;\n        registration_only?: boolean;\n    }): StorageBalance;\n    /**\n     * While storage_withdraw normally allows the caller to retrieve `available` balance, the basic\n     * Fungible Token implementation sets storage_balance_bounds.min == storage_balance_bounds.max,\n     * which means available balance will always be 0. So this implementation:\n     * - panics if `amount > 0`\n     * - never transfers Ⓝ to caller\n     * - returns a `storage_balance` struct if `amount` is 0\n     */\n    storage_withdraw({ amount }: {\n        amount?: bigint;\n    }): StorageBalance;\n    storage_unregister({ force }: {\n        force?: boolean;\n    }): boolean;\n    storage_balance_bounds(): StorageBalanceBounds;\n    storage_balance_of({ account_id }: {\n        account_id: AccountId;\n    }): Option<StorageBalance>;\n    /** Implementation of FungibleTokenResolver */\n    ft_resolve_transfer({ sender_id, receiver_id, amount }: {\n        sender_id: AccountId;\n        receiver_id: AccountId;\n        amount: Balance;\n    }): Balance;\n    bigIntMax: (...args: bigint[]) => bigint;\n    bigIntMin: (...args: bigint[]) => bigint;\n    static reconstruct(data: FungibleToken): FungibleToken;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/core_impl.js",
    "content": "import { StorageBalance, StorageBalanceBounds } from \"../storage_management\";\nimport { FtBurn, FtTransfer } from \"./events\";\nimport { near, LookupMap, NearPromise, assert, } from \"near-sdk-js\";\n// TODO: move to the main SDK package\nimport { assert_one_yocto } from \"../non_fungible_token/utils\";\nconst GAS_FOR_RESOLVE_TRANSFER = 15000000000000n;\nconst GAS_FOR_FT_TRANSFER_CALL = 25000000000000n + GAS_FOR_RESOLVE_TRANSFER;\nconst ERR_TOTAL_SUPPLY_OVERFLOW = \"Total supply overflow\";\n/** Implementation of a FungibleToken standard\n * Allows to include NEP-141 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - FungibleTokenCore -- interface with ft_transfer methods. FungibleToken provides methods for it.\n *     - FungibleTokenMetaData -- return metadata for the token in NEP-148, up to contract to implement.\n *     - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it.\n *     - AccountRegistrar -- interface for an account to register and unregister\n *\n * For example usage, see examples/src/fungible-token/my-ft.ts\n */\nexport class FungibleToken {\n    constructor() {\n        this.bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);\n        this.bigIntMin = (...args) => args.reduce((m, e) => e < m ? e : m);\n        this.accounts = new LookupMap(\"\");\n        this.total_supply = 0n;\n        this.account_storage_usage = 0n;\n    }\n    init(prefix) {\n        const storage_prefix = prefix.into_storage_key();\n        this.accounts = new LookupMap(storage_prefix);\n        this.total_supply = 0n;\n        this.account_storage_usage = 0n;\n        this.measure_account_storage_usage();\n        return this;\n    }\n    measure_account_storage_usage() {\n        let initial_storage_usage = near.storageUsage();\n        let tmp_account_id = \"a\".repeat(64);\n        this.accounts.set(tmp_account_id, 0n);\n        this.account_storage_usage = near.storageUsage() - initial_storage_usage;\n        this.accounts.remove(tmp_account_id);\n    }\n    internal_unwrap_balance_of(account_id) {\n        let balance = this.accounts.get(account_id);\n        if (balance === null) {\n            throw Error(`The account ${account_id} is not registered`);\n        }\n        return BigInt(balance);\n    }\n    internal_deposit(account_id, amount) {\n        let balance = BigInt(this.internal_unwrap_balance_of(account_id));\n        let new_balance = balance + amount;\n        this.accounts.set(account_id, new_balance);\n        let new_total_supply = this.total_supply + amount;\n        this.total_supply = new_total_supply;\n    }\n    internal_withdraw(account_id, amount) {\n        let balance = BigInt(this.internal_unwrap_balance_of(account_id));\n        let new_balance = balance - amount;\n        if (new_balance < 0) {\n            throw Error(\"The account doesn't have enough balance\");\n        }\n        this.accounts.set(account_id, new_balance);\n        let new_total_supply = this.total_supply - amount;\n        this.total_supply = new_total_supply;\n    }\n    internal_transfer(sender_id, receiver_id, amount, memo) {\n        assert(sender_id != receiver_id, \"Sender and receiver should be different\");\n        assert(amount > 0, \"The amount should be a positive number\");\n        this.internal_withdraw(sender_id, amount);\n        this.internal_deposit(receiver_id, amount);\n        new FtTransfer(sender_id, receiver_id, amount, memo).emit();\n    }\n    internal_register_account(account_id) {\n        if (this.accounts.containsKey(account_id)) {\n            throw Error(\"The account is already registered\");\n        }\n        this.accounts.set(account_id, 0n);\n    }\n    /** Internal method that returns the amount of burned tokens in a corner case when the sender\n     * has deleted (unregistered) their account while the `ft_transfer_call` was still in flight.\n     * Returns (Used token amount, Burned token amount)\n     */\n    internal_ft_resolve_transfer(sender_id, receiver_id, amount) {\n        // Get the unused amount from the `ft_on_transfer` call result.\n        let unused_amount;\n        try {\n            const promise_result = near.promiseResult(0).replace(/\"*/g, ''); //TODO: why promiseResult returns result with brackets?\n            unused_amount = this.bigIntMin(amount, BigInt(promise_result));\n        }\n        catch (e) {\n            if (e.message.includes('Failed')) {\n                unused_amount = amount;\n            }\n            else {\n                throw e;\n            }\n        }\n        if (unused_amount > 0) {\n            let receiver_balance = BigInt(this.accounts.get(receiver_id) ?? 0);\n            if (receiver_balance > 0n) {\n                let refund_amount = this.bigIntMin(receiver_balance, unused_amount);\n                let new_receiver_balance = receiver_balance - refund_amount;\n                if (new_receiver_balance < 0n) {\n                    throw Error(\"The receiver account doesn't have enough balance\");\n                }\n                this.accounts.set(receiver_id, new_receiver_balance);\n                let sender_balance = this.accounts.get(sender_id);\n                if (sender_balance) {\n                    sender_balance = BigInt(sender_balance);\n                    let new_sender_balance = sender_balance + refund_amount;\n                    this.accounts.set(sender_id, new_sender_balance);\n                    new FtTransfer(receiver_id, sender_id, refund_amount, \"refund\").emit();\n                    let used_amount = amount - refund_amount;\n                    if (used_amount < 0n) {\n                        throw Error(ERR_TOTAL_SUPPLY_OVERFLOW);\n                    }\n                    return [used_amount.valueOf(), 0n];\n                }\n                else {\n                    const new_total_supply = this.total_supply - refund_amount;\n                    if (new_total_supply < 0) {\n                        throw Error(ERR_TOTAL_SUPPLY_OVERFLOW);\n                    }\n                    this.total_supply = new_total_supply;\n                    near.log(\"The account of the sender was deleted\");\n                    new FtBurn(receiver_id, refund_amount, \"refund\").emit();\n                    return [amount, refund_amount];\n                }\n            }\n        }\n        return [amount, 0n];\n    }\n    /** Implementation of FungibleTokenCore */\n    ft_transfer({ receiver_id, amount, memo }) {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        let sender_id = near.predecessorAccountId();\n        this.internal_transfer(sender_id, receiver_id, amount, memo);\n    }\n    ft_transfer_call({ receiver_id, amount, memo, msg }) {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        assert(near.prepaidGas() > GAS_FOR_FT_TRANSFER_CALL, \"More gas is required\");\n        let sender_id = near.predecessorAccountId();\n        this.internal_transfer(sender_id, receiver_id, amount, memo);\n        let receiver_gas = near.prepaidGas() - GAS_FOR_FT_TRANSFER_CALL;\n        if (receiver_gas < 0) {\n            throw new Error(\"Prepaid gas overflow\");\n        }\n        return NearPromise.new(receiver_id)\n            .functionCall(\"ft_on_transfer\", JSON.stringify({ sender_id, amount: String(amount), msg }), BigInt(0), receiver_gas)\n            .then(NearPromise.new(near.currentAccountId())\n            .functionCall(\"ft_resolve_transfer\", JSON.stringify({ sender_id, receiver_id, amount: String(amount) }), BigInt(0), GAS_FOR_RESOLVE_TRANSFER));\n    }\n    ft_total_supply() {\n        return this.total_supply;\n    }\n    ft_balance_of({ account_id }) {\n        return this.accounts.get(account_id) ?? 0n;\n    }\n    /** Implementation of storage\n     * Internal method that returns the Account ID and the balance in case the account was\n     * unregistered.\n     */\n    internal_storage_unregister(force) {\n        assert_one_yocto();\n        let account_id = near.predecessorAccountId();\n        let balance = BigInt(this.accounts.get(account_id));\n        if (balance || balance == 0n) {\n            if (balance == 0n || force) {\n                this.accounts.remove(account_id);\n                this.total_supply = this.total_supply - balance;\n                NearPromise.new(account_id).transfer(this.storage_balance_bounds().min + 1n);\n                return [account_id, balance];\n            }\n            else {\n                throw Error(\"Can't unregister the account with the positive balance without force\");\n            }\n        }\n        else {\n            near.log(`The account ${account_id} is not registered`);\n            return null;\n        }\n    }\n    internal_storage_balance_of(account_id) {\n        if (this.accounts.containsKey(account_id)) {\n            return new StorageBalance(this.storage_balance_bounds().min, 0n);\n        }\n        else {\n            return null;\n        }\n    }\n    /** Implementation of StorageManagement\n     * @param registration_only doesn't affect the implementation for vanilla fungible token.\n     */\n    storage_deposit({ account_id, registration_only, }) {\n        let amount = near.attachedDeposit();\n        account_id = account_id ?? near.predecessorAccountId();\n        if (this.accounts.containsKey(account_id)) {\n            near.log(\"The account is already registered, refunding the deposit\");\n            if (amount > 0) {\n                NearPromise.new(near.predecessorAccountId()).transfer(amount);\n            }\n        }\n        else {\n            let min_balance = this.storage_balance_bounds().min;\n            if (amount < min_balance) {\n                throw Error(\"The attached deposit is less than the minimum storage balance\");\n            }\n            this.internal_register_account(account_id);\n            let refund = amount - min_balance;\n            if (refund > 0) {\n                NearPromise.new(near.predecessorAccountId()).transfer(refund);\n            }\n        }\n        return this.internal_storage_balance_of(account_id);\n    }\n    /**\n     * While storage_withdraw normally allows the caller to retrieve `available` balance, the basic\n     * Fungible Token implementation sets storage_balance_bounds.min == storage_balance_bounds.max,\n     * which means available balance will always be 0. So this implementation:\n     * - panics if `amount > 0`\n     * - never transfers Ⓝ to caller\n     * - returns a `storage_balance` struct if `amount` is 0\n     */\n    storage_withdraw({ amount }) {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        let predecessor_account_id = near.predecessorAccountId();\n        const storage_balance = this.internal_storage_balance_of(predecessor_account_id);\n        if (storage_balance) {\n            if (amount && amount > 0) {\n                throw Error(\"The amount is greater than the available storage balance\");\n            }\n            return storage_balance;\n        }\n        else {\n            throw Error(`The account ${predecessor_account_id} is not registered`);\n        }\n    }\n    storage_unregister({ force }) {\n        return this.internal_storage_unregister(force) ? true : false;\n    }\n    storage_balance_bounds() {\n        let required_storage_balance = this.account_storage_usage * near.storageByteCost();\n        return new StorageBalanceBounds(required_storage_balance, required_storage_balance);\n    }\n    storage_balance_of({ account_id }) {\n        return this.internal_storage_balance_of(account_id);\n    }\n    /** Implementation of FungibleTokenResolver */\n    ft_resolve_transfer({ sender_id, receiver_id, amount }) {\n        amount = BigInt(amount);\n        const res = this.internal_ft_resolve_transfer(sender_id, receiver_id, amount);\n        const used_amount = res[0];\n        const burned_amount = res[1];\n        if (burned_amount > 0) {\n            near.log(`Account @${sender_id} burned ${burned_amount}`);\n        }\n        return used_amount;\n    }\n    static reconstruct(data) {\n        const ret = new FungibleToken();\n        Object.assign(ret, data);\n        if (ret.accounts) {\n            ret.accounts = LookupMap.reconstruct(ret.accounts);\n        }\n        if (ret.total_supply) {\n            ret.total_supply = BigInt(ret.total_supply);\n        }\n        if (ret.account_storage_usage) {\n            ret.account_storage_usage = BigInt(ret.account_storage_usage);\n        }\n        return ret;\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/events.d.ts",
    "content": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <https://github.com/near/NEPs/blob/master/specs/Standards/FungibleToken/Event.md>\n *\n * This is an extension of the events format (nep-297):\n * <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>\n *\n * The three events in this standard are [`FtMint`], [`FtTransfer`], and [`FtBurn`].\n *\n * These events can be logged by calling `.emit()` on them if a single event, or calling\n * [`FtMint::emit_many`], [`FtTransfer::emit_many`],\n * or [`FtBurn::emit_many`] respectively.\n */\nimport { NearEvent } from \"../event\";\nimport { Option } from \"../non_fungible_token/utils\";\nimport { AccountId, Balance } from \"near-sdk-js\";\nexport declare type Nep141EventKind = FtMint[] | FtTransfer[] | FtBurn[];\nexport declare class Nep141Event extends NearEvent {\n    standard: string;\n    version: string;\n    event: string;\n    data: Nep141EventKind;\n    constructor(version: string, event_kind: Nep141EventKind);\n}\n/** Data to log for an FT mint event. To log this event, call [`.emit()`](FtMint::emit). */\nexport declare class FtMint {\n    owner_id: AccountId;\n    amount: number;\n    memo: Option<string>;\n    constructor(owner_id: AccountId, amount: number, memo: Option<string>);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit(): void;\n    /** Emits an FT mint event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtMint`] represents the data of each mint.\n     */\n    emit_many(data: FtMint[]): void;\n}\n/** Data to log for an FT transfer event. To log this event,\n * call [`.emit()`](FtTransfer::emit).\n */\nexport declare class FtTransfer {\n    old_owner_id: AccountId;\n    new_owner_id: AccountId;\n    amount: string;\n    memo: Option<String>;\n    constructor(old_owner_id: AccountId, new_owner_id: AccountId, amount: bigint, memo: Option<String>);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit(): void;\n    /** Emits an FT transfer event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtTransfer`] represents the data of each transfer.\n     */\n    emit_many(data: FtTransfer[]): void;\n}\n/** Data to log for an FT burn event. To log this event, call [`.emit()`](FtBurn::emit). */\nexport declare class FtBurn {\n    owner_id: AccountId;\n    amount: string;\n    memo: Option<string>;\n    constructor(owner_id: AccountId, amount: Balance, memo: Option<string>);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit(): void;\n    /** Emits an FT burn event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtBurn`] represents the data of each burn.\n     */\n    emit_many(data: FtBurn[]): void;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/events.js",
    "content": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <https://github.com/near/NEPs/blob/master/specs/Standards/FungibleToken/Event.md>\n *\n * This is an extension of the events format (nep-297):\n * <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>\n *\n * The three events in this standard are [`FtMint`], [`FtTransfer`], and [`FtBurn`].\n *\n * These events can be logged by calling `.emit()` on them if a single event, or calling\n * [`FtMint::emit_many`], [`FtTransfer::emit_many`],\n * or [`FtBurn::emit_many`] respectively.\n */\nimport { NearEvent } from \"../event\";\nimport { toSnakeCase } from \"../util\";\nexport class Nep141Event extends NearEvent {\n    constructor(version, event_kind) {\n        super();\n        this.standard = \"nep141\";\n        this.version = version;\n        this.event = toSnakeCase(event_kind[0].constructor.name);\n        this.data = event_kind;\n    }\n}\n/** Data to log for an FT mint event. To log this event, call [`.emit()`](FtMint::emit). */\nexport class FtMint {\n    constructor(owner_id, amount, memo) {\n        this.owner_id = owner_id;\n        this.amount = amount;\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this]);\n    }\n    /** Emits an FT mint event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtMint`] represents the data of each mint.\n     */\n    emit_many(data) {\n        new_141_v1(data).emit();\n    }\n}\n/** Data to log for an FT transfer event. To log this event,\n * call [`.emit()`](FtTransfer::emit).\n */\nexport class FtTransfer {\n    constructor(old_owner_id, new_owner_id, amount, memo) {\n        this.old_owner_id = old_owner_id;\n        this.new_owner_id = new_owner_id;\n        this.amount = amount.toString();\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this]);\n    }\n    /** Emits an FT transfer event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtTransfer`] represents the data of each transfer.\n     */\n    emit_many(data) {\n        new_141_v1(data).emit();\n    }\n}\n/** Data to log for an FT burn event. To log this event, call [`.emit()`](FtBurn::emit). */\nexport class FtBurn {\n    constructor(owner_id, amount, memo) {\n        this.owner_id = owner_id;\n        this.amount = amount.toString();\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this]);\n    }\n    /** Emits an FT burn event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtBurn`] represents the data of each burn.\n     */\n    emit_many(data) {\n        new_141_v1(data).emit();\n    }\n}\nfunction new_141(version, event_kind) {\n    return new Nep141Event(version, event_kind);\n}\nfunction new_141_v1(event_kind) {\n    return new_141(\"1.0.0\", event_kind);\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/index.d.ts",
    "content": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from './receiver';\nexport * from './resolver';\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/index.js",
    "content": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from './receiver';\nexport * from './resolver';\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/metadata.d.ts",
    "content": "import { Option } from \"../non_fungible_token/utils\";\n/**\n * Return metadata for the token, up to contract to implement.\n */\nexport declare class FungibleTokenMetadata {\n    spec: string;\n    name: string;\n    symbol: string;\n    icon: Option<string>;\n    reference: Option<string>;\n    reference_hash: Option<Uint8Array>;\n    decimals: number;\n    constructor(spec: string, name: string, symbol: string, icon: Option<string>, referance: Option<string>, referance_hash: Option<Uint8Array>, decimals: number);\n    assert_valid(): void;\n}\nexport interface FungibleTokenMetadataProvider {\n    ft_metadata(): FungibleTokenMetadata;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/metadata.js",
    "content": "import { assert, } from \"near-sdk-js\";\nconst FT_METADATA_SPEC = \"ft-1.0.0\";\n/**\n * Return metadata for the token, up to contract to implement.\n */\nexport class FungibleTokenMetadata {\n    constructor(spec, name, symbol, icon, referance, referance_hash, decimals) {\n        this.spec = spec;\n        this.name = name;\n        this.symbol = symbol;\n        this.icon = icon;\n        this.reference = referance;\n        this.reference_hash = referance_hash;\n        this.decimals = decimals;\n    }\n    assert_valid() {\n        assert(this.spec == FT_METADATA_SPEC, \"Invalid FT_METADATA_SPEC\");\n        const isReferenceProvided = this.reference ? true : false;\n        const isReferenceHashProvided = this.reference_hash ? true : false;\n        assert(isReferenceHashProvided === isReferenceProvided, \"reference and reference_hash must be either both provided or not\");\n        if (this.reference_hash) {\n            assert(this.reference_hash.length === 32, \"reference_hash must be 32 bytes\");\n        }\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/receiver.d.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n/**\n * Provides token transfer resolve functionality.\n *\n * # Examples\n *\n * ```typescript\n\n * import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n * import { FungibleTokenCore, FungibleToken, FungibleTokenReceiver } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore, FungibleTokenReceiver {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *   @call({})\n *    ft_on_transfer({ sender_id, amount, msg }: {\n *           sender_id: AccountId;\n *           amount: number;\n *           msg: String;\n *   }): PromiseOrValue<number> {\n *       return this.token.ft_on_transfer({ sender_id, amount, msg });\n *   };\n * }\n * ```\n */\nexport interface FungibleTokenReceiver {\n    /**\n     * Called by fungible token contract after `ft_transfer_call` was initiated by\n     * `sender_id` of the given `amount` with the transfer message given in `msg` field.\n     * The `amount` of tokens were already transferred to this contract account and ready to be used.\n     *\n     * The method must return the amount of tokens that are *not* used/accepted by this contract from the transferred\n     * amount. Examples:\n     * - The transferred amount was `500`, the contract completely takes it and must return `0`.\n     * - The transferred amount was `500`, but this transfer call only needs `450` for the action passed in the `msg`\n     *   field, then the method must return `50`.\n     * - The transferred amount was `500`, but the action in `msg` field has expired and the transfer must be\n     *   cancelled. The method must return `500` or panic.\n     *\n     * Arguments:\n     * @param sender_id - the account ID that initiated the transfer.\n     * @param amount - the amount of tokens that were transferred to this account in a decimal string representation.\n     * @param msg - a string message that was passed with this transfer call.\n     *\n     * @returns the amount of unused tokens that should be returned to sender, in a decimal string representation.\n     */\n    ft_on_transfer({ sender_id, amount, msg }: {\n        sender_id: AccountId;\n        amount: number;\n        msg: String;\n    }): PromiseOrValue<number>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/receiver.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/resolver.d.ts",
    "content": "import { AccountId, Balance } from \"near-sdk-js\";\n/**\n * Provides token transfer resolve functionality.\n *\n * # Examples\n *\n * ```typescript\n * import { AccountId, Balance, call } from \"near-sdk-js\";\n * import {\n *   FungibleTokenCore,\n *   FungibleTokenResolver,\n *   FungibleToken,\n * } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore, FungibleTokenResolver {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *     @call({ privateFunction: true })\n *     ft_resolve_transfer({\n *         sender_id,\n *         receiver_id,\n *         amount,\n *     }: {\n *         sender_id: AccountId,\n *         receiver_id: AccountId,\n *         amount: Balance\n *     }): Balance {\n *         const { used_amount, burned_amount } = this.token.internal_ft_resolve_transfer(sender_id, receiver_id, amount);\n *         if (burned_amount > 0) {\n *             console.log(`Account @${sender_id} burned ${burned_amount}`);\n *         }\n *         return used_amount;\n *     }\n * }\n * ```\n */\nexport interface FungibleTokenResolver {\n    /**\n    * Resolves the transfer of tokens between `sender_id` and `receiver_id`.\n    *\n    * @param sender_id - The account ID of the sender.\n    * @param receiver_id - The account ID of the receiver.\n    * @param amount - The amount of tokens to resolve in a decimal string representation.\n    *\n    * @returns The amount of tokens used during the transfer, returning the balance as a `Balance`.\n    */\n    ft_resolve_transfer({ sender_id, receiver_id, amount, }: {\n        sender_id: AccountId;\n        receiver_id: AccountId;\n        amount: Balance;\n    }): Balance;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/fungible_token/resolver.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/index.d.ts",
    "content": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \"./non_fungible_token\";\n/** Fungible tokens as described in [by the spec](https://nomicon.io/Standards/FungibleToken). */\nexport * from \"./fungible_token\";\nexport * from \"./storage_management\";\n"
  },
  {
    "path": "packages/near-contract-standards/lib/index.js",
    "content": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \"./non_fungible_token\";\n/** Fungible tokens as described in [by the spec](https://nomicon.io/Standards/FungibleToken). */\nexport * from \"./fungible_token\";\nexport * from \"./storage_management\";\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/approval/approval_receiver.d.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Approval receiver is the interface for the method called (or attempted to be called) when an NFT contract adds an approval for an account. */\nexport interface NonFungibleTokenApprovalReceiver {\n    /** Respond to notification that contract has been granted approval for a token.\n     *\n     * Notes\n     * - Contract knows the token contract ID from `predecessor_account_id`\n     *\n     * @param token_id - The token to which this contract has been granted approval\n     * @param owner_id - The owner of the token\n     * @param approval_id - The approval ID stored by NFT contract for this approval.\n     *        Expected to be a number within the 2^53 limit representable by JSON.\n     * @param msg: - specifies information needed by the approved contract in order to\n              handle the approval. Can indicate both a function to call and the\n              parameters to pass to that function.\n    */\n    nft_on_approve({ token_id, owner_id, approval_id, msg, }: {\n        token_id: TokenId;\n        owner_id: AccountId;\n        approval_id: bigint;\n        msg: string;\n    }): PromiseOrValue<string>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/approval/approval_receiver.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/approval/index.d.ts",
    "content": "import { AccountId, NearPromise } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n/** Interface used when it's desired to have a non-fungible token that has a\n * traditional escrow or approval system. This allows Alice to allow Bob\n * to take only the token with the unique identifier \"19\" but not others.\n * It should be noted that in the [core non-fungible token standard] there\n * is a method to do \"transfer and call\" which may be preferred over using\n * an approval management standard in certain use cases.\n *\n * [approval management standard]: https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html\n * [core non-fungible token standard]: https://nomicon.io/Standards/NonFungibleToken/Core.html\n */\nexport interface NonFungibleTokenApproval {\n    /** Add an approved account for a specific token.\n     *\n     * Requirements\n     * - Caller of the method must attach a deposit of at least 1 yoctoⓃ for\n     *   security purposes\n     * - Contract MAY require caller to attach larger deposit, to cover cost of\n     *   storing approver data\n     * - Contract MUST panic if called by someone other than token owner\n     * - Contract MUST panic if addition would cause `nft_revoke_all` to exceed\n     *   single-block gas limit\n     * - Contract MUST increment approval ID even if re-approving an account\n     * - If successfully approved or if had already been approved, and if `msg` is\n     *   present, contract MUST call `nft_on_approve` on `account_id`. See\n     *   `nft_on_approve` description below for details.\n     *\n     * @param token_id - The token for which to add an approval\n     * @param account_id - The account to add to `approvals`\n     * @param msg - Optional string to be passed to `nft_on_approve`\n     * @returns void, if no `msg` given. Otherwise, returns promise call to\n     *          `nft_on_approve`, which can resolve with whatever it wants.\n     */\n    nft_approve({ token_id, account_id, msg, }: {\n        token_id: TokenId;\n        account_id: AccountId;\n        msg?: string;\n    }): Option<NearPromise>;\n    /** Revoke an approved account for a specific token.\n     *\n     * Requirements\n     * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n     *   purposes\n     * - If contract requires >1yN deposit on `nft_approve`, contract\n     *   MUST refund associated storage deposit when owner revokes approval\n     * - Contract MUST panic if called by someone other than token owner\n     *\n     * @param token_id - The token for which to revoke an approval\n     * @param account_id - The account to remove from `approvals`\n     */\n    nft_revoke({ token_id, account_id, }: {\n        token_id: TokenId;\n        account_id: AccountId;\n    }): any;\n    /** Revoke all approved accounts for a specific token.\n     *\n     * Requirements\n     * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n     *   purposes\n     * - If contract requires >1yN deposit on `nft_approve`, contract\n     *   MUST refund all associated storage deposit when owner revokes approvals\n     * - Contract MUST panic if called by someone other than token owner\n     *\n     * @param token_id - The token with approvals to revoke\n     */\n    nft_revoke_all({ token_id }: {\n        token_id: TokenId;\n    }): any;\n    /** Check if a token is approved for transfer by a given account, optionally\n     * checking an approval_id\n     *\n     * @param token_id - The token for which to revoke an approval\n     * @param approved_account_id - The account to check the existence of in `approvals`\n     * @param approval_id - An optional approval ID to check against current approval ID for given account\n     * @returns if `approval_id` given, `true` if `approved_account_id` is approved with given `approval_id`\n     * otherwise, `true` if `approved_account_id` is in list of approved accounts\n     */\n    nft_is_approved({ token_id, approved_account_id, approval_id, }: {\n        token_id: TokenId;\n        approved_account_id: AccountId;\n        approval_id?: bigint;\n    }): boolean;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/approval/index.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/index.d.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { Token, TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n/** Used for all non-fungible tokens. The specification for the\n * [core non-fungible token standard] lays out the reasoning for each method.\n * It's important to check out [NonFungibleTokenReceiver](./receiver.ts)\n * and [NonFungibleTokenResolver](./resolver.ts) to\n * understand how the cross-contract call work.\n *\n * [core non-fungible token standard]: <https://nomicon.io/Standards/NonFungibleToken/Core.html>\n *\n * # Examples\n *\n * ```typescript\n\n * import { AccountId } from \"near-sdk-js\";\n * import { Option } from \"../non_fungible_token/utils\";\n * import { Token, TokenId } from \"../token\";\n * import { NonFungibleTokenCore, NonFungibleToken } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements NonFungibleTokenCore {\n *     private token: NonFungibleToken;\n *\n *     constructor() {\n *         this.tokens = new NonFungibleToken();\n *     }\n *\n *     @call({})\n *      nft_transfer({ receiver_id, token_id, approval_id, memo }: {\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approval_id?: bigint;\n            memo?: string;\n        }): any {\n *         this.tokens.nft_transfer({ receiver_id, token_id, approval_id, memo });\n *     }\n *\n *     @call({})\n *     nft_transfer_call({ receiver_id, token_id, approval_id, memo }: {\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approval_id?: bigint;\n            memo?: string;\n            msg: string;\n        }): any {\n *         return this.tokens.nft_transfer_call({ receiver_id, token_id, approval_id, memo });\n *     }\n *\n *     @view({})\n *     nft_token({ token_id }: {\n        token_id: TokenId;\n        }): Option<Token> {\n            return this.tokens.nft_token({ token_id });\n        };\n * }\n * ```\n */\nexport interface NonFungibleTokenCore {\n    /** Simple transfer. Transfer a given `token_id` from current owner to\n     * `receiver_id`.\n     *\n     * Requirements\n     * - Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes\n     * - Contract MUST panic if called by someone other than token owner or,\n     *   if using Approval Management, one of the approved accounts\n     * - `approval_id` is for use with Approval Management,\n     *   see <https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html>\n     * - If using Approval Management, contract MUST nullify approved accounts on\n     *   successful transfer.\n     * - TODO: needed? Both accounts must be registered with the contract for transfer to\n     *   succeed. See see <https://nomicon.io/Standards/StorageManagement.html>\n     *\n     * @param receiver_id - The valid NEAR account receiving the token\n     * @param token_id - The token to transfer\n     * @param approval_id - Expected approval ID. A number smaller than\n     *        2^53, and therefore representable as JSON. See Approval Management\n     *        standard for full explanation.\n     * @param memo (optional) - For use cases that may benefit from indexing or\n     *        providing information for a transfer\n     */\n    nft_transfer({ receiver_id, token_id, approval_id, memo, }: {\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approval_id?: bigint;\n        memo?: string;\n    }): any;\n    /** Transfer token and call a method on a receiver contract. A successful\n     * workflow will end in a success execution outcome to the callback on the NFT\n     * contract at the method `nft_resolve_transfer`.\n     *\n     * You can think of this as being similar to attaching native NEAR tokens to a\n     * function call. It allows you to attach any Non-Fungible Token in a call to a\n     * receiver contract.\n     *\n     * Requirements:\n     * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n     *   purposes\n     * - Contract MUST panic if called by someone other than token owner or,\n     *   if using Approval Management, one of the approved accounts\n     * - The receiving contract must implement `ft_on_transfer` according to the\n     *   standard. If it does not, FT contract's `ft_resolve_transfer` MUST deal\n     *   with the resulting failed cross-contract call and roll back the transfer.\n     * - Contract MUST implement the behavior described in `ft_resolve_transfer`\n     * - `approval_id` is for use with Approval Management extension, see\n     *   that document for full explanation.\n     * - If using Approval Management, contract MUST nullify approved accounts on\n     *   successful transfer.\n     *\n     * @param receiver_id - The valid NEAR account receiving the token.\n     * @param token_id - The token to send.\n     * @param approval_id - Expected approval ID. A number smaller than\n     *        2^53, and therefore representable as JSON. See Approval Management\n     *        standard for full explanation.\n     * @param memo (optional) - For use cases that may benefit from indexing or\n     *        providing information for a transfer.\n     * @param msg - Specifies information needed by the receiving contract in\n     *        order to properly handle the transfer. Can indicate both a function to\n     *        call and the parameters to pass to that function.\n     */\n    nft_transfer_call({ receiver_id, token_id, approval_id, memo, }: {\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approval_id?: bigint;\n        memo?: string;\n        msg: string;\n    }): any;\n    /** Returns the token with the given `token_id` or `null` if no such token. */\n    nft_token({ token_id }: {\n        token_id: TokenId;\n    }): Option<Token>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/index.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/receiver.d.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Used when an NFT is transferred using `nft_transfer_call`. This interface is implemented on the receiving contract, not on the NFT contract. \n * \n * # Examples\n *\n * ```typescript\n\n * import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n * import { TokenId } from \"../token\";\n * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenReceiver } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements NonFungibleTokenCore, NonFungibleTokenReceiver {\n *     private token: NonFungibleToken;\n *\n *     constructor() {\n *         this.tokens = new NonFungibleToken();\n *     }\n *\n *     @call({})\n *     nft_on_transfer({\n            sender_id,\n            previous_owner_id,\n            token_id,\n            msg,\n        }: {\n            sender_id: AccountId;\n            previous_owner_id: AccountId;\n            token_id: TokenId;\n            msg: string;\n        }): PromiseOrValue<boolean> {\n            return this.tokens.nft_on_transfer({\n                sender_id,\n                previous_owner_id,\n                token_id,\n                msg\n            })\n        }\n * }\n * ```\n*/\nexport interface NonFungibleTokenReceiver {\n  /** Take some action after receiving a non-fungible token\n   *\n   * Requirements:\n   * - Contract MUST restrict calls to this function to a set of whitelisted NFT\n   *   contracts\n   *\n   * @param sender_id - The sender of `nft_transfer_call`\n   * @param previous_owner_id - The account that owned the NFT prior to it being\n   *        transferred to this contract, which can differ from `sender_id` if using\n   *        Approval Management extension\n   * @param token_id - The `token_id` argument given to `nft_transfer_call`\n   * @param msg - Information necessary for this contract to know how to process the\n   *        request. This may include method names and/or arguments.\n   *\n   * @returns true if token should be returned to `sender_id`\n   */\n  nft_on_transfer({\n    sender_id,\n    previous_owner_id,\n    token_id,\n    msg,\n  }: {\n    sender_id: AccountId;\n    previous_owner_id: AccountId;\n    token_id: TokenId;\n    msg: string;\n  }): PromiseOrValue<boolean>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/receiver.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/resolver.d.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract.\n *\n * # Examples\n *\n * ```typescript\n\n * import { AccountId } from \"near-sdk-js\";\n * import { TokenId } from \"../token\";\n * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenResolver } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements NonFungibleTokenCore, NonFungibleTokenResolver {\n *     private token: NonFungibleToken;\n *\n *     constructor() {\n *         this.tokens = new NonFungibleToken();\n *     }\n *\n *     @call({})\n *     nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: {\n            previous_owner_id: AccountId;\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approved_account_ids?: {\n                [approval: AccountId]: bigint;\n            };\n    }): boolean; {\n        return this.tokens.nft_resolve_transfer({\n            previous_owner_id,\n            receiver_id,\n            token_id,\n            approved_account_ids,\n            });\n        }\n * }\n * ```\n*/\nexport interface NonFungibleTokenResolver {\n    /** Finalize an `nft_transfer_call` chain of cross-contract calls.\n     *\n     * The `nft_transfer_call` process:\n     *\n     * 1. Sender calls `nft_transfer_call` on FT contract\n     * 2. NFT contract transfers token from sender to receiver\n     * 3. NFT contract calls `nft_on_transfer` on receiver contract\n     * 4+. [receiver contract may make other cross-contract calls]\n     * N. NFT contract resolves promise chain with `nft_resolve_transfer`, and may\n     *    transfer token back to sender\n     *\n     * Requirements:\n     * - Contract MUST forbid calls to this function by any account except self\n     * - If promise chain failed, contract MUST revert token transfer\n     * - If promise chain resolves with `true`, contract MUST return token to\n     *   `sender_id`\n     *\n     * @param previous_owner_id - The owner prior to the call to `nft_transfer_call`\n     * @param receiver_id - The `receiver_id` argument given to `nft_transfer_call`\n     * @param token_id - The `token_id` argument given to `ft_transfer_call`\n     * @param approved_account_ids - If using Approval Management, contract MUST provide\n     *        set of original approved accounts in this argument, and restore these\n     *        approved accounts in case of revert.\n     *\n     * @returns true if token was successfully transferred to `receiver_id`.\n     */\n    nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: {\n        previous_owner_id: AccountId;\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approved_account_ids?: {\n            [approval: AccountId]: bigint;\n        };\n    }): boolean;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/core/resolver.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/enumeration/index.d.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { Token } from \"../token\";\n/** Offers methods helpful in determining account ownership of NFTs and provides a way to page through NFTs per owner, determine total supply, etc. */\nexport interface NonFungibleTokenEnumeration {\n    /** Returns the total supply of non-fungible tokens */\n    nft_total_supply(): number;\n    /** Get a list of all tokens\n     *\n     * @param from_index - The starting index of tokens to return\n     * @param limit - The maximum number of tokens to return\n     * @returns - An array of Token objects, as described in Core standard\n     */\n    nft_tokens({ from_index, limit, }: {\n        from_index?: number;\n        limit?: number;\n    }): Token[];\n    /** Get number of tokens owned by a given account\n     *\n     * @param account_id - A valid NEAR account\n     * @returns - The number of non-fungible tokens owned by given `account_id`\n     */\n    nft_supply_for_owner({ account_id }: {\n        account_id: AccountId;\n    }): number;\n    /** Get list of all tokens owned by a given account\n     *\n     * @param account_id - A valid NEAR account\n     * @param from_index - The starting index of tokens to return\n     * @param limit - The maximum number of tokens to return\n     * @returns - A paginated list of all tokens owned by this account\n     */\n    nft_tokens_for_owner({ account_id, from_index, limit, }: {\n        account_id: AccountId;\n        from_index?: number;\n        limit?: number;\n    }): Token[];\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/enumeration/index.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/events.d.ts",
    "content": "/** Standard for nep171 (Non-Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <https://github.com/near/NEPs/blob/69f76c6c78c2ebf05d856347c9c98ae48ad84ebd/specs/Standards/NonFungibleToken/Event.md>\n *\n * This is an extension of the events format (nep-297):\n * <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>\n *\n * The three events in this standard are [`NftMint`], [`NftTransfer`], and [`NftBurn`].\n *\n * These events can be logged by calling `.emit()` on them if a single event, or calling\n * [`NftMint.emit_many`], [`NftTransfer.emit_many`],\n * or [`NftBurn.emit_many`] respectively.\n */\nimport { AccountId } from \"near-sdk-js\";\nimport { NearEvent } from \"../event\";\nimport { TokenId } from \"./token\";\nexport declare type Nep171EventKind = NftMint[] | NftTransfer[] | NftBurn[] | NftContractMetadataUpdate[];\nexport declare class Nep171Event extends NearEvent {\n    standard: string;\n    version: string;\n    event: string;\n    data: Nep171EventKind;\n    constructor(version: string, event_kind: Nep171EventKind);\n}\n/** Data to log for an NFT mint event. To log this event, call `.emit()` */\nexport declare class NftMint {\n    owner_id: AccountId;\n    token_ids: TokenId[];\n    memo?: string;\n    constructor(owner_id: AccountId, token_ids: TokenId[], memo?: string);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit(): void;\n    /** Emits an nft mint event, through `near.log`,\n     * where each [`NftMint`] represents the data of each mint. */\n    static emit_many(data: NftMint[]): void;\n}\n/** Data to log for an NFT transfer event. To log this event,\n * call [`.emit()`](NftTransfer.emit). */\nexport declare class NftTransfer {\n    old_owner_id: AccountId;\n    new_owner_id: AccountId;\n    token_ids: TokenId[];\n    authorized_id?: AccountId;\n    memo?: string;\n    constructor(old_owner_id: AccountId, new_owner_id: AccountId, token_ids: TokenId[], authorized_id?: AccountId, memo?: string);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit(): void;\n    /** Emits an nft transfer event, through `near.log`,\n     * where each [`NftTransfer`] represents the data of each transfer. */\n    static emit_many(data: NftTransfer[]): void;\n}\n/** Data to log for an NFT burn event. To log this event, call [`.emit()`](NftBurn.emit). */\nexport declare class NftBurn {\n    owner_id: AccountId;\n    token_ids: TokenId[];\n    authorized_id?: string;\n    memo?: string;\n    constructor(owner_id: AccountId, token_ids: TokenId[], authorized_id?: string, memo?: string);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit(): void;\n    /** Emits an nft burn event, through `near.log`,\n     * where each [`NftBurn`] represents the data of each burn. */\n    static emit_many(data: NftBurn[]): void;\n}\n/** Data to log for an NFT contract metadata updates. To log this event, call [`.emit()`](NftContractMetadataUpdate.emit). */\nexport declare class NftContractMetadataUpdate {\n    memo?: string;\n    constructor(memo?: string);\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit(): void;\n    /** Emits an contract metadata update event, through `near.log`,\n     * where each [`NftBurn`] represents the data of each burn. */\n    static emit_many(data: NftContractMetadataUpdate[]): void;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/events.js",
    "content": "import { NearEvent } from \"../event\";\nimport { toSnakeCase } from \"../util\";\nexport class Nep171Event extends NearEvent {\n    constructor(version, event_kind) {\n        super();\n        this.standard = \"nep171\";\n        this.version = version;\n        this.event = toSnakeCase(event_kind[0].constructor.name);\n        this.data = event_kind;\n    }\n}\n/** Data to log for an NFT mint event. To log this event, call `.emit()` */\nexport class NftMint {\n    constructor(owner_id, token_ids, memo) {\n        this.owner_id = owner_id;\n        this.token_ids = token_ids;\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit() {\n        NftMint.emit_many([this]);\n    }\n    /** Emits an nft mint event, through `near.log`,\n     * where each [`NftMint`] represents the data of each mint. */\n    static emit_many(data) {\n        new_171_v1(data).emit();\n    }\n}\n/** Data to log for an NFT transfer event. To log this event,\n * call [`.emit()`](NftTransfer.emit). */\nexport class NftTransfer {\n    constructor(old_owner_id, new_owner_id, token_ids, authorized_id, memo) {\n        this.old_owner_id = old_owner_id;\n        this.new_owner_id = new_owner_id;\n        this.token_ids = token_ids;\n        this.authorized_id = authorized_id;\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit() {\n        NftTransfer.emit_many([this]);\n    }\n    /** Emits an nft transfer event, through `near.log`,\n     * where each [`NftTransfer`] represents the data of each transfer. */\n    static emit_many(data) {\n        new_171_v1(data).emit();\n    }\n}\n/** Data to log for an NFT burn event. To log this event, call [`.emit()`](NftBurn.emit). */\nexport class NftBurn {\n    constructor(owner_id, token_ids, authorized_id, memo) {\n        this.owner_id = owner_id;\n        this.token_ids = token_ids;\n        this.authorized_id = authorized_id;\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit() {\n        NftBurn.emit_many([this]);\n    }\n    /** Emits an nft burn event, through `near.log`,\n     * where each [`NftBurn`] represents the data of each burn. */\n    static emit_many(data) {\n        new_171_v1(data).emit();\n    }\n}\n/** Data to log for an NFT contract metadata updates. To log this event, call [`.emit()`](NftContractMetadataUpdate.emit). */\nexport class NftContractMetadataUpdate {\n    constructor(memo) {\n        this.memo = memo;\n    }\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event. */\n    emit() {\n        NftContractMetadataUpdate.emit_many([this]);\n    }\n    /** Emits an contract metadata update event, through `near.log`,\n     * where each [`NftBurn`] represents the data of each burn. */\n    static emit_many(data) {\n        new_171_v1(data).emit();\n    }\n}\nfunction new_171(version, event_kind) {\n    return new Nep171Event(version, event_kind);\n}\nfunction new_171_v1(event_kind) {\n    return new_171(\"1.0.0\", event_kind);\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/impl.d.ts",
    "content": "import { AccountId, UnorderedMap, LookupMap, UnorderedSet, NearPromise, IntoStorageKey } from \"near-sdk-js\";\nimport { TokenMetadata } from \"./metadata\";\nimport { Option } from \"./utils\";\nimport { NonFungibleTokenResolver } from \"./core/resolver\";\nimport { Token, TokenId } from \"./token\";\nimport { NonFungibleTokenCore } from \"./core\";\nimport { NonFungibleTokenApproval } from \"./approval\";\nimport { NonFungibleTokenEnumeration } from \"./enumeration\";\n/** Implementation of the non-fungible token standard.\n * Allows to include NEP-171 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - NonFungibleTokenCore -- interface with nft_transfer methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenApproval -- interface with nft_approve methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenEnumeration -- interface for getting lists of tokens. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenMetadata -- return metadata for the token in NEP-177, up to contract to implement.\n *\n * For example usage, see near-contract-standards/example-contracts/non-fungible-token/my-nft.ts.\n */\nexport declare class NonFungibleToken implements NonFungibleTokenCore, NonFungibleTokenResolver, NonFungibleTokenApproval, NonFungibleTokenEnumeration {\n    owner_id: AccountId;\n    extra_storage_in_bytes_per_token: bigint;\n    owner_by_id: UnorderedMap<AccountId>;\n    token_metadata_by_id: Option<LookupMap<TokenMetadata>>;\n    tokens_per_owner: Option<LookupMap<UnorderedSet<TokenId>>>;\n    approvals_by_id: Option<LookupMap<{\n        [approvals: AccountId]: bigint;\n    }>>;\n    next_approval_id_by_id: Option<LookupMap<bigint>>;\n    constructor();\n    nft_total_supply(): number;\n    private enum_get_token;\n    nft_tokens({ from_index, limit, }: {\n        from_index?: number;\n        limit?: number;\n    }): Token[];\n    nft_supply_for_owner({ account_id }: {\n        account_id: AccountId;\n    }): number;\n    nft_tokens_for_owner({ account_id, from_index, limit, }: {\n        account_id: AccountId;\n        from_index?: number;\n        limit?: number;\n    }): Token[];\n    nft_approve({ token_id, account_id, msg, }: {\n        token_id: TokenId;\n        account_id: AccountId;\n        msg: string;\n    }): Option<NearPromise>;\n    nft_revoke({ token_id, account_id, }: {\n        token_id: TokenId;\n        account_id: AccountId;\n    }): void;\n    nft_revoke_all({ token_id }: {\n        token_id: TokenId;\n    }): void;\n    nft_is_approved({ token_id, approved_account_id, approval_id, }: {\n        token_id: TokenId;\n        approved_account_id: AccountId;\n        approval_id?: bigint;\n    }): boolean;\n    init(owner_by_id_prefix: IntoStorageKey, owner_id: AccountId, token_metadata_prefix?: IntoStorageKey, enumeration_prefix?: IntoStorageKey, approval_prefix?: IntoStorageKey): void;\n    static reconstruct(data: NonFungibleToken): NonFungibleToken;\n    measure_min_token_storage_cost(): void;\n    internal_transfer_unguarded(token_id: TokenId, from: AccountId, to: AccountId): void;\n    internal_transfer(sender_id: AccountId, receiver_id: AccountId, token_id: TokenId, approval_id?: bigint, memo?: string): [AccountId, Option<{\n        [approvals: AccountId]: bigint;\n    }>];\n    static emit_transfer(owner_id: AccountId, receiver_id: AccountId, token_id: TokenId, sender_id?: AccountId, memo?: string): void;\n    internal_mint(token_id: TokenId, token_owner_id: AccountId, token_metadata?: TokenMetadata): Token;\n    internal_mint_with_refund(token_id: TokenId, token_owner_id: AccountId, token_metadata?: TokenMetadata, refund_id?: string): Token;\n    nft_transfer({ receiver_id, token_id, approval_id, memo, }: {\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approval_id?: bigint;\n        memo?: string;\n    }): void;\n    nft_transfer_call({ receiver_id, token_id, approval_id, memo, msg, }: {\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approval_id?: bigint;\n        memo?: string;\n        msg: string;\n    }): NearPromise;\n    nft_token({ token_id }: {\n        token_id: TokenId;\n    }): Option<Token>;\n    nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: {\n        previous_owner_id: AccountId;\n        receiver_id: AccountId;\n        token_id: TokenId;\n        approved_account_ids?: {\n            [approvals: AccountId]: bigint;\n        };\n    }): boolean;\n}\nexport declare type StorageKey = TokensPerOwner | TokenPerOwnerInner;\nexport declare class TokensPerOwner implements IntoStorageKey {\n    account_hash: Uint8Array;\n    constructor(account_hash: Uint8Array);\n    into_storage_key(): string;\n}\nexport declare class TokenPerOwnerInner implements IntoStorageKey {\n    account_id_hash: Uint8Array;\n    constructor(account_id_hash: Uint8Array);\n    into_storage_key(): string;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/impl.js",
    "content": "import { UnorderedMap, LookupMap, near, UnorderedSet, assert, NearPromise, bytes, serialize, str, } from \"near-sdk-js\";\nimport { TokenMetadata } from \"./metadata\";\nimport { refund_storage_deposit, refund_deposit, refund_deposit_to_account, assert_at_least_one_yocto, assert_one_yocto, } from \"./utils\";\nimport { NftMint, NftTransfer } from \"./events\";\nimport { Token } from \"./token\";\nconst GAS_FOR_RESOLVE_TRANSFER = 16000000000000n;\nconst GAS_FOR_NFT_TRANSFER_CALL = 30000000000000n + GAS_FOR_RESOLVE_TRANSFER;\nconst GAS_FOR_NFT_APPROVE = 21000000000000n;\nfunction repeat(str, n) {\n    return Array(n + 1).join(str);\n}\nfunction expect_token_found(option) {\n    if (option === null) {\n        throw new Error(\"Token not found\");\n    }\n    return option;\n}\nfunction expect_approval(option) {\n    if (option === null) {\n        throw new Error(\"next_approval_by_id must be set for approval ext\");\n    }\n    return option;\n}\n/** Implementation of the non-fungible token standard.\n * Allows to include NEP-171 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - NonFungibleTokenCore -- interface with nft_transfer methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenApproval -- interface with nft_approve methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenEnumeration -- interface for getting lists of tokens. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenMetadata -- return metadata for the token in NEP-177, up to contract to implement.\n *\n * For example usage, see near-contract-standards/example-contracts/non-fungible-token/my-nft.ts.\n */\nexport class NonFungibleToken {\n    constructor() {\n        this.owner_id = \"\";\n        this.extra_storage_in_bytes_per_token = 0n;\n        this.owner_by_id = new UnorderedMap(\"\");\n        this.token_metadata_by_id = null;\n        this.tokens_per_owner = null;\n        this.approvals_by_id = null;\n        this.next_approval_id_by_id = null;\n    }\n    nft_total_supply() {\n        return this.owner_by_id.length;\n    }\n    enum_get_token(owner_id, token_id) {\n        const metadata = this.token_metadata_by_id.get(token_id, {\n            reconstructor: TokenMetadata.reconstruct,\n        });\n        const approved_account_ids = this.approvals_by_id.get(token_id, {\n            defaultValue: {},\n        });\n        return new Token(token_id, owner_id, metadata, approved_account_ids);\n    }\n    nft_tokens({ from_index, limit, }) {\n        const start_index = from_index === undefined ? 0 : from_index;\n        assert(this.owner_by_id.length >= start_index, \"Out of bounds, please use a smaller from_index.\");\n        let l = limit === undefined ? 2 ** 32 : limit;\n        assert(l > 0, \"limit must be greater than 0.\");\n        l = Math.min(l, this.owner_by_id.length - start_index);\n        const ret = [];\n        const tokens = this.owner_by_id.keys({ start: from_index, limit: l });\n        for (let token_id of tokens) {\n            const owner_id = this.owner_by_id.get(token_id);\n            ret.push(this.enum_get_token(owner_id, token_id));\n        }\n        return ret;\n    }\n    nft_supply_for_owner({ account_id }) {\n        const tokens_per_owner = this.tokens_per_owner;\n        assert(tokens_per_owner !== null, \"Could not find tokens_per_owner when calling a method on the enumeration standard.\");\n        const account_tokens = tokens_per_owner.get(account_id, {\n            reconstructor: UnorderedSet.reconstruct,\n        });\n        return account_tokens === null ? 0 : account_tokens.length;\n    }\n    nft_tokens_for_owner({ account_id, from_index, limit, }) {\n        const tokens_per_owner = this.tokens_per_owner;\n        assert(tokens_per_owner !== undefined, \"Could not find tokens_per_owner when calling a method on the enumeration standard.\");\n        const token_set = tokens_per_owner.get(account_id, {\n            reconstructor: UnorderedSet.reconstruct,\n        });\n        assert(token_set !== null, \"Token set is empty\");\n        const start_index = from_index === undefined ? 0 : from_index;\n        assert(token_set.length >= start_index, \"Out of bounds, please use a smaller from_index.\");\n        let l = limit === undefined ? 2 ** 32 : limit;\n        assert(l > 0, \"limit must be greater than 0.\");\n        l = Math.min(l, token_set.length - start_index);\n        const ret = [];\n        const tokens = token_set.elements({ start: from_index, limit: l });\n        for (let token_id of tokens) {\n            const owner_id = this.owner_by_id.get(token_id);\n            ret.push(this.enum_get_token(owner_id, token_id));\n        }\n        return ret;\n    }\n    nft_approve({ token_id, account_id, msg, }) {\n        assert_at_least_one_yocto();\n        if (this.approvals_by_id === null) {\n            throw new Error(\"NFT does not support Approval Management\");\n        }\n        const approvals_by_id = this.approvals_by_id;\n        const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n        assert(near.predecessorAccountId() === owner_id, \"Predecessor must be token owner.\");\n        const next_approval_id_by_id = expect_approval(this.next_approval_id_by_id);\n        const approved_account_ids = approvals_by_id.get(token_id) ?? {};\n        const approval_id = next_approval_id_by_id.get(token_id) ?? 1n;\n        const old_approved_account_ids_size = serialize(approved_account_ids).length;\n        approved_account_ids[account_id] = approval_id;\n        const new_approved_account_ids_size = serialize(approved_account_ids).length;\n        approvals_by_id.set(token_id, approved_account_ids);\n        next_approval_id_by_id.set(token_id, approval_id + 1n);\n        const storage_used = new_approved_account_ids_size - old_approved_account_ids_size;\n        refund_deposit(BigInt(storage_used));\n        if (msg) {\n            return NearPromise.new(account_id).functionCallRaw(\"nft_on_approve\", serialize({ token_id, owner_id, approval_id, msg }), 0n, near.prepaidGas() - GAS_FOR_NFT_APPROVE);\n        }\n        return null;\n    }\n    nft_revoke({ token_id, account_id, }) {\n        assert_one_yocto();\n        if (this.approvals_by_id === null) {\n            throw new Error(\"NFT does not support Approval Management\");\n        }\n        const approvals_by_id = this.approvals_by_id;\n        const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n        const predecessorAccountId = near.predecessorAccountId();\n        assert(predecessorAccountId === owner_id, \"Predecessor must be token owner.\");\n        const approved_account_ids = approvals_by_id.get(token_id);\n        const old_approved_account_ids_size = serialize(approved_account_ids).length;\n        let new_approved_account_ids_size;\n        if (approved_account_ids[account_id]) {\n            delete approved_account_ids[account_id];\n            if (Object.keys(approved_account_ids).length === 0) {\n                approvals_by_id.remove(token_id);\n                new_approved_account_ids_size = serialize(approved_account_ids).length;\n            }\n            else {\n                approvals_by_id.set(token_id, approved_account_ids);\n                new_approved_account_ids_size = 0;\n            }\n            refund_storage_deposit(predecessorAccountId, new_approved_account_ids_size - old_approved_account_ids_size);\n        }\n    }\n    nft_revoke_all({ token_id }) {\n        assert_one_yocto();\n        if (this.approvals_by_id === null) {\n            throw new Error(\"NFT does not support Approval Management\");\n        }\n        const approvals_by_id = this.approvals_by_id;\n        const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n        const predecessorAccountId = near.predecessorAccountId();\n        assert(predecessorAccountId === owner_id, \"Predecessor must be token owner.\");\n        const approved_account_ids = approvals_by_id.get(token_id);\n        if (approved_account_ids) {\n            refund_storage_deposit(predecessorAccountId, serialize(approved_account_ids).length);\n            approvals_by_id.remove(token_id);\n        }\n    }\n    nft_is_approved({ token_id, approved_account_id, approval_id, }) {\n        expect_token_found(this.owner_by_id.get(token_id));\n        if (this.approvals_by_id === null) {\n            return false;\n        }\n        const approvals_by_id = this.approvals_by_id;\n        const approved_account_ids = approvals_by_id.get(token_id);\n        if (approved_account_ids === null) {\n            return false;\n        }\n        const actual_approval_id = approved_account_ids[approved_account_id];\n        if (actual_approval_id === undefined) {\n            return false;\n        }\n        if (approval_id) {\n            return BigInt(approval_id) === actual_approval_id;\n        }\n        return true;\n    }\n    init(owner_by_id_prefix, owner_id, token_metadata_prefix, enumeration_prefix, approval_prefix) {\n        let approvals_by_id;\n        let next_approval_id_by_id;\n        if (approval_prefix) {\n            const prefix = approval_prefix.into_storage_key();\n            approvals_by_id = new LookupMap(prefix);\n            next_approval_id_by_id = new LookupMap(prefix + \"n\");\n        }\n        else {\n            approvals_by_id = null;\n            next_approval_id_by_id = null;\n        }\n        this.owner_id = owner_id;\n        this.extra_storage_in_bytes_per_token = 0n;\n        this.owner_by_id = new UnorderedMap(owner_by_id_prefix.into_storage_key());\n        this.token_metadata_by_id = token_metadata_prefix\n            ? new LookupMap(token_metadata_prefix.into_storage_key())\n            : null;\n        this.tokens_per_owner = enumeration_prefix\n            ? new LookupMap(enumeration_prefix.into_storage_key())\n            : null;\n        this.approvals_by_id = approvals_by_id;\n        this.next_approval_id_by_id = next_approval_id_by_id;\n        this.measure_min_token_storage_cost();\n    }\n    static reconstruct(data) {\n        const ret = new NonFungibleToken();\n        Object.assign(ret, data);\n        ret.owner_by_id = UnorderedMap.reconstruct(ret.owner_by_id);\n        if (ret.token_metadata_by_id) {\n            ret.token_metadata_by_id = LookupMap.reconstruct(ret.token_metadata_by_id);\n        }\n        if (ret.tokens_per_owner) {\n            ret.tokens_per_owner = LookupMap.reconstruct(ret.tokens_per_owner);\n        }\n        if (ret.approvals_by_id) {\n            ret.approvals_by_id = LookupMap.reconstruct(ret.approvals_by_id);\n        }\n        if (ret.next_approval_id_by_id) {\n            ret.next_approval_id_by_id = LookupMap.reconstruct(ret.next_approval_id_by_id);\n        }\n        return ret;\n    }\n    measure_min_token_storage_cost() {\n        const initial_storage_usage = near.storageUsage();\n        // 64 Length because this is the max account id length\n        const tmp_token_id = repeat(\"a\", 64);\n        const tmp_owner_id = repeat(\"a\", 64);\n        // 1. set some dummy data\n        this.owner_by_id.set(tmp_token_id, tmp_owner_id);\n        if (this.token_metadata_by_id) {\n            this.token_metadata_by_id.set(tmp_token_id, new TokenMetadata(repeat(\"a\", 64), repeat(\"a\", 64), repeat(\"a\", 64), repeat(\"a\", 64), 1n, null, null, null, null, null, null, null));\n        }\n        if (this.tokens_per_owner) {\n            const u = new UnorderedSet(new TokensPerOwner(near.sha256(bytes(tmp_owner_id))).into_storage_key());\n            u.set(tmp_token_id);\n            this.tokens_per_owner.set(tmp_owner_id, u);\n        }\n        if (this.approvals_by_id) {\n            const approvals = {};\n            approvals[tmp_owner_id] = 1n;\n            this.approvals_by_id.set(tmp_token_id, approvals);\n        }\n        if (this.next_approval_id_by_id) {\n            this.next_approval_id_by_id.set(tmp_token_id, 1n);\n        }\n        // 2. see how much space it took\n        this.extra_storage_in_bytes_per_token =\n            near.storageUsage() - initial_storage_usage;\n        // 3. roll it all back\n        if (this.next_approval_id_by_id) {\n            this.next_approval_id_by_id.remove(tmp_token_id);\n        }\n        if (this.approvals_by_id) {\n            this.approvals_by_id.remove(tmp_token_id);\n        }\n        if (this.tokens_per_owner) {\n            const u = this.tokens_per_owner.remove(tmp_owner_id, {\n                reconstructor: UnorderedSet.reconstruct,\n            });\n            u.remove(tmp_token_id);\n        }\n        if (this.token_metadata_by_id) {\n            this.token_metadata_by_id.remove(tmp_token_id);\n        }\n        this.owner_by_id.remove(tmp_token_id);\n    }\n    internal_transfer_unguarded(token_id, from, to) {\n        this.owner_by_id.set(token_id, to);\n        if (this.tokens_per_owner) {\n            const owner_tokens_set = this.tokens_per_owner.get(from, {\n                reconstructor: UnorderedSet.reconstruct,\n            });\n            if (owner_tokens_set == null) {\n                throw new Error(\"Unable to access tokens per owner in unguarded call.\");\n            }\n            owner_tokens_set.remove(token_id);\n            if (owner_tokens_set.isEmpty()) {\n                this.tokens_per_owner.remove(from);\n            }\n            else {\n                this.tokens_per_owner.set(from, owner_tokens_set);\n            }\n            let receiver_tokens_set = this.tokens_per_owner.get(to, {\n                reconstructor: UnorderedSet.reconstruct,\n            });\n            if (receiver_tokens_set === null) {\n                receiver_tokens_set = new UnorderedSet(new TokensPerOwner(near.sha256(bytes(to))).into_storage_key());\n            }\n            receiver_tokens_set.set(token_id);\n            this.tokens_per_owner.set(to, receiver_tokens_set);\n        }\n    }\n    internal_transfer(sender_id, receiver_id, token_id, approval_id, memo) {\n        const owner_id = this.owner_by_id.get(token_id);\n        if (owner_id == null) {\n            throw new Error(\"Token not found\");\n        }\n        const approved_account_ids = this.approvals_by_id?.remove(token_id);\n        let sender_id_authorized;\n        if (sender_id != owner_id) {\n            if (!approved_account_ids) {\n                throw new Error(\"Unauthorized\");\n            }\n            const actual_approval_id = approved_account_ids[sender_id];\n            if (!actual_approval_id) {\n                throw new Error(\"Sender not approved\");\n            }\n            assert(approval_id === undefined || approval_id == actual_approval_id, `The actual approval_id ${actual_approval_id} is different from the given ${approval_id}`);\n            sender_id_authorized = sender_id;\n        }\n        else {\n            sender_id_authorized = undefined;\n        }\n        assert(owner_id != receiver_id, \"Current and next owner must differ\");\n        this.internal_transfer_unguarded(token_id, owner_id, receiver_id);\n        NonFungibleToken.emit_transfer(owner_id, receiver_id, token_id, sender_id_authorized, memo);\n        return [owner_id, approved_account_ids];\n    }\n    static emit_transfer(owner_id, receiver_id, token_id, sender_id, memo) {\n        new NftTransfer(owner_id, receiver_id, [token_id], sender_id && sender_id == owner_id ? sender_id : undefined, memo).emit();\n    }\n    internal_mint(token_id, token_owner_id, token_metadata) {\n        const token = this.internal_mint_with_refund(token_id, token_owner_id, token_metadata, near.predecessorAccountId());\n        new NftMint(token.owner_id, [token.token_id]).emit();\n        return token;\n    }\n    internal_mint_with_refund(token_id, token_owner_id, token_metadata, refund_id) {\n        let initial_storage_usage = null;\n        if (refund_id) {\n            initial_storage_usage = [refund_id, near.storageUsage()];\n        }\n        if (this.token_metadata_by_id && token_metadata === undefined) {\n            throw new Error(\"Must provide metadata\");\n        }\n        if (this.owner_by_id.get(token_id)) {\n            throw new Error(\"token_id must be unique\");\n        }\n        const owner_id = token_owner_id;\n        this.owner_by_id.set(token_id, owner_id);\n        this.token_metadata_by_id?.set(token_id, token_metadata);\n        if (this.tokens_per_owner) {\n            let token_ids = this.tokens_per_owner.get(owner_id, {\n                reconstructor: UnorderedSet.reconstruct,\n            });\n            if (token_ids === null) {\n                token_ids = new UnorderedSet(new TokensPerOwner(near.sha256(bytes(owner_id))).into_storage_key());\n            }\n            token_ids.set(token_id);\n            this.tokens_per_owner.set(owner_id, token_ids);\n        }\n        const approved_account_ids = this.approvals_by_id ? {} : undefined;\n        if (initial_storage_usage) {\n            const [id, storage_usage] = initial_storage_usage;\n            refund_deposit_to_account(near.storageUsage() - storage_usage, id);\n        }\n        return new Token(token_id, owner_id, token_metadata, approved_account_ids);\n    }\n    nft_transfer({ receiver_id, token_id, approval_id, memo, }) {\n        assert_at_least_one_yocto();\n        const sender_id = near.predecessorAccountId();\n        this.internal_transfer(sender_id, receiver_id, token_id, approval_id, memo);\n    }\n    nft_transfer_call({ receiver_id, token_id, approval_id, memo, msg, }) {\n        assert_at_least_one_yocto();\n        assert(near.prepaidGas() > GAS_FOR_NFT_TRANSFER_CALL, \"Not enough prepaid gas\");\n        const sender_id = near.predecessorAccountId();\n        const [previous_owner_id, approved_account_ids] = this.internal_transfer(sender_id, receiver_id, token_id, approval_id, memo);\n        const promise = NearPromise.new(receiver_id)\n            .functionCall(\"nft_on_transfer\", JSON.stringify({ sender_id, previous_owner_id, token_id, msg }), 0n, near.prepaidGas() - GAS_FOR_NFT_TRANSFER_CALL)\n            .then(NearPromise.new(near.currentAccountId()).functionCall(\"nft_resolve_transfer\", JSON.stringify({\n            previous_owner_id,\n            receiver_id,\n            token_id,\n            approved_account_ids,\n        }), 0n, GAS_FOR_RESOLVE_TRANSFER));\n        return promise;\n    }\n    nft_token({ token_id }) {\n        const owner_id = this.owner_by_id.get(token_id);\n        if (owner_id == null) {\n            return null;\n        }\n        const metadata = this.token_metadata_by_id?.get(token_id, {\n            reconstructor: TokenMetadata.reconstruct,\n        });\n        const approved_account_ids = this.approvals_by_id?.get(token_id);\n        return new Token(token_id, owner_id, metadata, approved_account_ids);\n    }\n    nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }) {\n        let must_revert = false;\n        let p;\n        try {\n            p = near.promiseResult(0);\n        }\n        catch (e) {\n            if (e.message.includes(\"Not Ready\")) {\n                throw new Error();\n            }\n            else {\n                must_revert = true;\n            }\n        }\n        if (!must_revert) {\n            try {\n                const yes_or_no = JSON.parse(p);\n                if (typeof yes_or_no == \"boolean\") {\n                    must_revert = yes_or_no;\n                }\n                else {\n                    must_revert = true;\n                }\n            }\n            catch (_e) {\n                must_revert = true;\n            }\n        }\n        if (!must_revert) {\n            return true;\n        }\n        const current_owner = this.owner_by_id.get(token_id);\n        if (current_owner) {\n            if (current_owner != receiver_id) {\n                return true;\n            }\n        }\n        else {\n            if (approved_account_ids) {\n                refund_storage_deposit(previous_owner_id, serialize(approved_account_ids).length);\n            }\n            return true;\n        }\n        this.internal_transfer_unguarded(token_id, receiver_id, previous_owner_id);\n        if (this.approvals_by_id) {\n            const receiver_approvals = this.approvals_by_id.get(token_id);\n            if (receiver_approvals) {\n                refund_storage_deposit(receiver_id, serialize(receiver_approvals).length);\n            }\n            if (approved_account_ids) {\n                this.approvals_by_id.set(token_id, approved_account_ids);\n            }\n        }\n        NonFungibleToken.emit_transfer(receiver_id, previous_owner_id, token_id, null, null);\n        return false;\n    }\n}\nexport class TokensPerOwner {\n    constructor(account_hash) {\n        this.account_hash = account_hash;\n    }\n    into_storage_key() {\n        return \"\\x00\" + str(this.account_hash);\n    }\n}\nexport class TokenPerOwnerInner {\n    constructor(account_id_hash) {\n        this.account_id_hash = account_id_hash;\n    }\n    into_storage_key() {\n        return \"\\x01\" + str(this.account_id_hash);\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/index.d.ts",
    "content": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. */\nexport * from \"./approval\";\n/** The [core non-fungible token standard](https://nomicon.io/Standards/NonFungibleToken/Core.html). This can be though of as the base standard, with the others being extension standards. */\nexport * from \"./core\";\n/** Interface for the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Enumeration.html).\n * This provides useful view-only methods returning token supply, tokens by owner, etc.\n */\nexport * from \"./enumeration\";\nexport * from \"./events\";\nexport * from \"./impl\";\n/** Metadata interfaces and implementation according to the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Metadata.html).\n * This covers both the contract metadata and the individual token metadata.\n */\nexport * from \"./metadata\";\n/** The Token struct for the non-fungible token. */\nexport * from \"./token\";\n/** NFT utility functions */\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/index.js",
    "content": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. */\nexport * from \"./approval\";\n/** The [core non-fungible token standard](https://nomicon.io/Standards/NonFungibleToken/Core.html). This can be though of as the base standard, with the others being extension standards. */\nexport * from \"./core\";\n/** Interface for the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Enumeration.html).\n * This provides useful view-only methods returning token supply, tokens by owner, etc.\n */\nexport * from \"./enumeration\";\nexport * from \"./events\";\nexport * from \"./impl\";\n/** Metadata interfaces and implementation according to the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Metadata.html).\n * This covers both the contract metadata and the individual token metadata.\n */\nexport * from \"./metadata\";\n/** The Token struct for the non-fungible token. */\nexport * from \"./token\";\n/** NFT utility functions */\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/metadata.d.ts",
    "content": "import { Option } from \"./utils\";\n/** This spec can be treated like a version of the standard. */\nexport declare const NFT_METADATA_SPEC = \"nft-1.0.0\";\n/** Metadata for the NFT contract itself. */\nexport declare class NFTContractMetadata {\n    spec: string;\n    name: string;\n    symbol: string;\n    icon: Option<string>;\n    base_uri: Option<string>;\n    reference: Option<string>;\n    reference_hash: Option<string>;\n    constructor();\n    init(spec: string, name: string, symbol: string, icon: Option<string>, base_uri: Option<string>, reference: Option<string>, reference_hash: Option<string>): void;\n    assert_valid(): void;\n    static reconstruct(data: NFTContractMetadata): NFTContractMetadata;\n}\n/** Metadata on the individual token level. */\nexport declare class TokenMetadata {\n    title: Option<string>;\n    description: Option<string>;\n    media: Option<string>;\n    media_hash: Option<string>;\n    copies: Option<bigint>;\n    issued_at: Option<string>;\n    expires_at: Option<string>;\n    starts_at: Option<string>;\n    updated_at: Option<string>;\n    extra: Option<string>;\n    reference: Option<string>;\n    reference_hash: Option<string>;\n    constructor(title: Option<string>, // ex. \"Arch Nemesis: Mail Carrier\" or \"Parcel #5055\"\n    description: Option<string>, // free-form description\n    media: Option<string>, // URL to associated media, preferably to decentralized, content-addressed storage\n    media_hash: Option<string>, // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.\n    copies: Option<bigint>, // number of copies of this set of metadata in existence when token was minted.\n    issued_at: Option<string>, // ISO 8601 datetime when token was issued or minted\n    expires_at: Option<string>, // ISO 8601 datetime when token expires\n    starts_at: Option<string>, // ISO 8601 datetime when token starts being valid\n    updated_at: Option<string>, // ISO 8601 datetime when token was last updated\n    extra: Option<string>, // anything extra the NFT wants to store on-chain. Can be stringified JSON.\n    reference: Option<string>, // URL to an off-chain JSON file with more info.\n    reference_hash: Option<string>);\n    assert_valid(): void;\n    static reconstruct(data: TokenMetadata): TokenMetadata;\n}\n/** Offers details on the contract-level metadata. */\nexport interface NonFungibleTokenMetadataProvider {\n    nft_metadata(): NFTContractMetadata;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/metadata.js",
    "content": "import { assert } from \"near-sdk-js\";\n/** This spec can be treated like a version of the standard. */\nexport const NFT_METADATA_SPEC = \"nft-1.0.0\";\n/** Metadata for the NFT contract itself. */\nexport class NFTContractMetadata {\n    constructor() {\n        this.spec = NFT_METADATA_SPEC;\n        this.name = \"\";\n        this.symbol = \"\";\n        this.icon = null;\n        this.base_uri = null;\n        this.reference = null;\n        this.reference_hash = null;\n    }\n    init(spec, name, symbol, icon, base_uri, reference, reference_hash) {\n        this.spec = spec;\n        this.name = name;\n        this.symbol = symbol;\n        this.icon = icon;\n        this.base_uri = base_uri;\n        this.reference = reference;\n        this.reference_hash = reference_hash;\n    }\n    assert_valid() {\n        assert(this.spec == NFT_METADATA_SPEC, \"Spec is not NFT metadata\");\n        assert((this.reference != null) == (this.reference_hash != null), \"Reference and reference hash must be present\");\n        if (this.reference_hash != null) {\n            assert(this.reference_hash.length == 32, \"Hash has to be 32 bytes\");\n        }\n    }\n    static reconstruct(data) {\n        const metadata = new NFTContractMetadata();\n        Object.assign(metadata, data);\n        return metadata;\n    }\n}\n/** Metadata on the individual token level. */\nexport class TokenMetadata {\n    constructor(title, // ex. \"Arch Nemesis: Mail Carrier\" or \"Parcel #5055\"\n    description, // free-form description\n    media, // URL to associated media, preferably to decentralized, content-addressed storage\n    media_hash, // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.\n    copies, // number of copies of this set of metadata in existence when token was minted.\n    issued_at, // ISO 8601 datetime when token was issued or minted\n    expires_at, // ISO 8601 datetime when token expires\n    starts_at, // ISO 8601 datetime when token starts being valid\n    updated_at, // ISO 8601 datetime when token was last updated\n    extra, // anything extra the NFT wants to store on-chain. Can be stringified JSON.\n    reference, // URL to an off-chain JSON file with more info.\n    reference_hash // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.\n    ) {\n        this.title = title;\n        this.description = description;\n        this.media = media;\n        this.media_hash = media_hash;\n        this.copies = copies;\n        this.issued_at = issued_at;\n        this.expires_at = expires_at;\n        this.starts_at = starts_at;\n        this.updated_at = updated_at;\n        this.extra = extra;\n        this.reference = reference;\n        this.reference_hash = reference_hash;\n    }\n    assert_valid() {\n        assert((this.media != null) == (this.media_hash != null), \"Media and media hash must be present\");\n        if (this.media_hash != null) {\n            assert(this.media_hash.length == 32, \"Media hash has to be 32 bytes\");\n        }\n        assert((this.reference != null) == (this.reference_hash != null), \"Reference and reference hash must be present\");\n        if (this.reference_hash != null) {\n            assert(this.reference_hash.length == 32, \"Reference hash has to be 32 bytes\");\n        }\n    }\n    static reconstruct(data) {\n        return new TokenMetadata(data.title, data.description, data.media, data.media_hash, data.copies, data.issued_at, data.expires_at, data.starts_at, data.updated_at, data.extra, data.reference, data.reference_hash);\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/token.d.ts",
    "content": "import { TokenMetadata } from \"./metadata\";\nimport { AccountId } from \"near-sdk-js\";\n/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use auto incrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */\nexport declare type TokenId = string;\n/** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, as they are frequently used in modern NFTs. */\nexport declare class Token {\n    token_id: TokenId;\n    owner_id: AccountId;\n    metadata?: TokenMetadata;\n    approved_account_ids?: {\n        [approved_account_id: AccountId]: bigint;\n    };\n    constructor(token_id: TokenId, owner_id: AccountId, metadata?: TokenMetadata, approved_account_ids?: {\n        [approved_account_id: AccountId]: bigint;\n    });\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/token.js",
    "content": "/** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, as they are frequently used in modern NFTs. */\nexport class Token {\n    constructor(token_id, owner_id, metadata, approved_account_ids) {\n        this.token_id = token_id;\n        this.owner_id = owner_id;\n        this.metadata = metadata;\n        this.approved_account_ids = approved_account_ids;\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/utils.d.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nexport declare function refund_storage_deposit(account_id: AccountId, storage_released: number): void;\nexport declare function refund_deposit_to_account(storage_used: bigint, account_id: AccountId): void;\n/** Assumes that the predecessor will be refunded */\nexport declare function refund_deposit(storage_used: bigint): void;\nexport declare function hash_account_id(account_id: AccountId): Uint8Array;\n/** Assert that at least 1 yoctoNEAR was attached. */\nexport declare function assert_at_least_one_yocto(): void;\n/** Assert that exactly 1 yoctoNEAR was attached */\nexport declare function assert_one_yocto(): void;\nexport declare type Option<T> = T | null;\n"
  },
  {
    "path": "packages/near-contract-standards/lib/non_fungible_token/utils.js",
    "content": "import { near, assert, bytes } from \"near-sdk-js\";\nexport function refund_storage_deposit(account_id, storage_released) {\n    const promise_id = near.promiseBatchCreate(account_id);\n    near.promiseBatchActionTransfer(promise_id, BigInt(storage_released) * near.storageByteCost());\n    near.promiseReturn(promise_id);\n}\nexport function refund_deposit_to_account(storage_used, account_id) {\n    const required_cost = near.storageByteCost() * storage_used;\n    const attached_deposit = near.attachedDeposit();\n    assert(required_cost <= attached_deposit, `Must attach ${required_cost} yoctoNEAR to cover storage`);\n    const refund = attached_deposit - required_cost;\n    if (refund > 1n) {\n        const promise_id = near.promiseBatchCreate(account_id);\n        near.promiseBatchActionTransfer(promise_id, refund);\n        near.promiseReturn(promise_id);\n    }\n}\n/** Assumes that the predecessor will be refunded */\nexport function refund_deposit(storage_used) {\n    refund_deposit_to_account(storage_used, near.predecessorAccountId());\n}\nexport function hash_account_id(account_id) {\n    return near.sha256(bytes(account_id));\n}\n/** Assert that at least 1 yoctoNEAR was attached. */\nexport function assert_at_least_one_yocto() {\n    assert(near.attachedDeposit() >= 1n, \"Requires attached deposit of at least 1 yoctoNEAR\");\n}\n/** Assert that exactly 1 yoctoNEAR was attached */\nexport function assert_one_yocto() {\n    assert(near.attachedDeposit() === 1n, \"Requires attached deposit of 1 yoctoNEAR\");\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/storage_management/index.d.ts",
    "content": "import { AccountId, Balance } from \"near-sdk-js\";\nimport { Option } from \"../non_fungible_token/utils\";\nexport declare class StorageBalance {\n    total: Balance;\n    available: Balance;\n    constructor(total: Balance, available: Balance);\n}\nexport declare class StorageBalanceBounds {\n    constructor(min: Balance, max: Option<Balance>);\n    min: Balance;\n    max: Option<Balance>;\n}\nexport interface StorageManagement {\n    /**\n     * @param registration_only if `true` MUST refund above the minimum balance if the account didn't exist and\n     *   refund full deposit if the account exists.\n     */\n    storage_deposit({ account_id, registration_only }: {\n        account_id: Option<AccountId>;\n        registration_only: Option<boolean>;\n    }): StorageBalance;\n    /** Withdraw specified amount of available Ⓝ for predecessor account.\n    *\n    * This method is safe to call. It MUST NOT remove data.\n    *\n    * @param amount is sent as a string representing an unsigned 128-bit integer. If\n    * omitted, contract MUST refund full `available` balance. If `amount` exceeds\n    * predecessor account's available balance, contract MUST panic.\n    *\n    * If predecessor account not registered, contract MUST panic.\n    *\n    * MUST require exactly 1 yoctoNEAR attached balance to prevent restricted\n    * function-call access-key call (UX wallet security)\n    *\n    * @returns the StorageBalance structure showing updated balances.\n    */\n    storage_withdraw({ amount }: {\n        amount?: bigint;\n    }): StorageBalance;\n    /** Unregisters the predecessor account and returns the storage NEAR deposit back.\n    *\n    * If the predecessor account is not registered, the function MUST return `false` without panic.\n    *\n    * @param force If `force=true` the function SHOULD ignore account balances (burn them) and close the account.\n    * Otherwise, MUST panic if caller has a positive registered balance (eg token holdings) or\n    *     the contract doesn't support force unregistration.\n    * MUST require exactly 1 yoctoNEAR attached balance to prevent restricted function-call access-key call\n    * (UX wallet security)\n    * @returns `true` if the account was unregistered, `false` if account was not registered before.\n    */\n    storage_unregister({ force }: {\n        force: Option<boolean>;\n    }): boolean;\n    storage_balance_bounds(): StorageBalanceBounds;\n    storage_balance_of({ account_id }: {\n        account_id: AccountId;\n    }): Option<StorageBalance>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/storage_management/index.js",
    "content": "export class StorageBalance {\n    constructor(total, available) {\n        this.total = total;\n        this.available = available;\n    }\n}\nexport class StorageBalanceBounds {\n    constructor(min, max) {\n        this.min = min;\n        this.max = max;\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/lib/util.d.ts",
    "content": "export declare const toSnakeCase: (str: string) => string;\n"
  },
  {
    "path": "packages/near-contract-standards/lib/util.js",
    "content": "export const toSnakeCase = (str) => {\n    return str.replace(/[A-Z]/g, (letter, index) => { return index == 0 ? letter.toLowerCase() : '_' + letter.toLowerCase(); });\n};\n"
  },
  {
    "path": "packages/near-contract-standards/package.json",
    "content": "{\n  \"name\": \"near-contract-standards\",\n  \"version\": \"2.0.0\",\n  \"description\": \"Compatible near-contract-standards implementation in JS\",\n  \"main\": \"index.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"tsc\"\n  },\n  \"author\": \"Near Inc <hello@nearprotocol.com>\",\n  \"license\": \"Apache-2.0\",\n  \"dependencies\": {\n    \"lodash-es\": \"4.17.21\",\n    \"near-sdk-js\": \"workspace:*\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"4.7.4\"\n  },\n  \"files\": [\n    \"lib\"\n  ]\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/event.ts",
    "content": "import { near } from \"near-sdk-js\";\n\nexport abstract class NearEvent {\n\n  private internal_to_json_string(): string {\n    return JSON.stringify(this);\n  }\n\n  private internal_to_json_event_string(): string {\n    return `EVENT_JSON: ${this.internal_to_json_string()}`;\n  }\n\n  /**\n   * Logs the event to the host. This is required to ensure that the event is triggered\n   * and to consume the event.\n   */\n  emit(): void {\n    near.log(this.internal_to_json_event_string());\n  }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/core.ts",
    "content": "import { AccountId, PromiseOrValue, Balance } from \"near-sdk-js\"\nimport { Option } from \"../non_fungible_token/utils\"\n\n/**\n * The core methods for a basic fungible token. Extension standards may be\n * added in addition to this interface.\n *\n * # Examples\n *\n * ```typescript\n\n * import { near, call, view, AccountId, PromiseOrValue, Balance } from \"near-sdk-js\";\n * import { Option } from \"../non_fungible_token/utils\";\n * import { FungibleTokenCore, FungibleToken } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *     @call({})\n *     ft_transfer({ receiver_id, amount, memo }: {\n *         receiver_id: AccountId,\n *         amount: Balance,\n *         memo?: String\n *     }): void {\n *         this.token.ft_transfer({ receiver_id, amount, memo });\n *     }\n *\n *     @call({})\n *     ft_transfer_call({ receiver_id, amount, memo, msg }: {\n *         receiver_id: AccountId,\n *         amount: Balance,\n *         memo?: Option<String>,\n *         msg: String\n *     }): PromiseOrValue<bigint> {\n *         return this.token.ft_transfer_call({ receiver_id, amount, memo, msg });\n *     }\n *\n *     @view({})\n *     ft_total_supply(): Balance {\n *         return this.token.ft_total_supply();\n *     }\n *\n *     @view({})\n *     ft_balance_of({ account_id }: { account_id: AccountId }): Balance {\n *         return this.token.ft_balance_of({ account_id });\n *     }\n * }\n * ```\n */\nexport interface FungibleTokenCore {\n    /**\n     * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id`.\n     * Both accounts must be registered with the contract for transfer to succeed. (See [NEP-145](https://github.com/near/NEPs/discussions/145))\n     * This method must to be able to accept attached deposits, and must not panic on attached deposit.\n     * Exactly 1 yoctoNEAR must be attached.\n     * See [the Security section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Arguments:\n     * @param receiver_id - the account ID of the receiver.\n     * @param amount - the amount of tokens to transfer. Must be a positive number in decimal string representation.\n     * @param memo - an optional string field in a free form to associate a memo with this transfer.\n     */\n    ft_transfer({\n        receiver_id,\n        amount,\n        memo\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo?: String\n    });\n\n    /**\n     * Transfers positive `amount` of tokens from the `near.predecessorAccountId()` to `receiver_id` account. Then\n     * calls `ft_on_transfer` method on `receiver_id` contract and attaches a callback to resolve this transfer.\n     * `ft_on_transfer` method must return the amount of tokens unused by the receiver contract, the remaining tokens\n     * must be refunded to the `predecessor_account_id` at the resolve transfer callback.\n     *\n     * Token contract must pass all the remaining unused gas to the `ft_on_transfer` call.\n     *\n     * Malicious or invalid behavior by the receiver's contract:\n     * - If the receiver contract promise fails or returns invalid value, the full transfer amount must be refunded.\n     * - If the receiver contract overspent the tokens, and the `receiver_id` balance is lower than the required refund\n     * amount, the remaining balance must be refunded. See [the Security section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Both accounts must be registered with the contract for transfer to succeed. (See #145)\n     * This method must to be able to accept attached deposits, and must not panic on attached deposit. Exactly 1 yoctoNEAR must be attached. See [the Security\n     * section](https://github.com/near/NEPs/issues/141#user-content-security) of the standard.\n     *\n     * Arguments:\n     * @param receiver_id - the account ID of the receiver contract. This contract will be called.\n     * @param amount - the amount of tokens to transfer. Must be a positive number in a decimal string representation.\n     * @param memo - an optional string field in a free form to associate a memo with this transfer.\n     * @param msg - a string message that will be passed to `ft_on_transfer` contract call.\n     *\n     * @returns a promise which will result in the amount of tokens withdrawn from sender's account.\n     */\n    ft_transfer_call({\n        receiver_id,\n        amount,\n        memo,\n        msg\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo: Option<String>,\n        msg: String\n    }): PromiseOrValue<bigint>;\n\n    /** Returns the total supply of the token in a decimal string representation. */\n    ft_total_supply(): Balance;\n\n    /** Returns the balance of the account. If the account doesn't exist must returns `\"0\"`. */\n    ft_balance_of({\n        account_id\n    }: {\n        account_id: AccountId\n    }): Balance;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/core_impl.ts",
    "content": "import { StorageBalance, StorageBalanceBounds, StorageManagement } from \"../storage_management\";\nimport { FungibleTokenCore } from \"./core\";\nimport { FtBurn, FtTransfer } from \"./events\";\nimport { FungibleTokenResolver } from \"./resolver\";\nimport {\n    near,\n    AccountId,\n    LookupMap,\n    Balance,\n    Gas,\n    PromiseOrValue,\n    NearPromise,\n    StorageUsage,\n    assert,\n    IntoStorageKey,\n} from \"near-sdk-js\";\n\nimport { Option } from '../non_fungible_token/utils';\n\n// TODO: move to the main SDK package\nimport { assert_one_yocto } from \"../non_fungible_token/utils\";\n\nconst GAS_FOR_RESOLVE_TRANSFER: Gas = 15_000_000_000_000n;\nconst GAS_FOR_FT_TRANSFER_CALL: Gas = 25_000_000_000_000n + GAS_FOR_RESOLVE_TRANSFER;\nconst ERR_TOTAL_SUPPLY_OVERFLOW: string = \"Total supply overflow\";\n\n/** Implementation of a FungibleToken standard\n * Allows to include NEP-141 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - FungibleTokenCore -- interface with ft_transfer methods. FungibleToken provides methods for it.\n *     - FungibleTokenMetaData -- return metadata for the token in NEP-148, up to contract to implement.\n *     - StorageManager -- interface for NEP-145 for allocating storage per account. FungibleToken provides methods for it.\n *     - AccountRegistrar -- interface for an account to register and unregister\n *\n * For example usage, see examples/src/fungible-token/my-ft.ts\n */\nexport class FungibleToken implements FungibleTokenCore, StorageManagement, FungibleTokenResolver {\n    // AccountID -> Account balance.\n    accounts: LookupMap<Balance>;\n\n    // Total supply of the all token.\n    total_supply: Balance;\n\n    // The storage size in bytes for one account.\n    account_storage_usage: StorageUsage;\n\n    constructor() {\n        this.accounts = new LookupMap(\"\");\n        this.total_supply = 0n;\n        this.account_storage_usage = 0n;\n    }\n\n    init(prefix: IntoStorageKey) {\n        const storage_prefix = prefix.into_storage_key();\n        this.accounts = new LookupMap<Balance>(storage_prefix);\n        this.total_supply = 0n;\n        this.account_storage_usage = 0n;\n        this.measure_account_storage_usage();\n        return this;\n    }\n\n\n    measure_account_storage_usage() {\n        let initial_storage_usage: bigint = near.storageUsage();\n        let tmp_account_id: string = \"a\".repeat(64);\n        this.accounts.set(tmp_account_id, 0n);\n        this.account_storage_usage = near.storageUsage() - initial_storage_usage;\n        this.accounts.remove(tmp_account_id);\n    }\n\n    internal_unwrap_balance_of(account_id: AccountId): Balance {\n        let balance = this.accounts.get(account_id);\n        if (balance === null) {\n            throw Error(`The account ${account_id} is not registered`);\n        }\n        return BigInt(balance);\n    }\n\n    internal_deposit(account_id: AccountId, amount: Balance) {\n        let balance: Balance = BigInt(this.internal_unwrap_balance_of(account_id));\n        let new_balance: Balance = balance + amount;\n        this.accounts.set(account_id, new_balance);\n        let new_total_supply: Balance = this.total_supply + amount;\n        this.total_supply = new_total_supply;\n    }\n\n    internal_withdraw(account_id: AccountId, amount: Balance) {\n        let balance: Balance = BigInt(this.internal_unwrap_balance_of(account_id));\n        let new_balance: Balance = balance - amount;\n        if (new_balance < 0) {\n            throw Error(\"The account doesn't have enough balance\");\n        }\n        this.accounts.set(account_id, new_balance);\n        let new_total_supply: Balance = this.total_supply - amount;\n        this.total_supply = new_total_supply;\n    }\n\n    internal_transfer(\n        sender_id: AccountId,\n        receiver_id: AccountId,\n        amount: Balance,\n        memo?: String,\n    ) {\n        assert(sender_id != receiver_id, \"Sender and receiver should be different\");\n        assert(amount > 0, \"The amount should be a positive number\");\n        this.internal_withdraw(sender_id, amount);\n        this.internal_deposit(receiver_id, amount);\n        new FtTransfer(sender_id, receiver_id, amount, memo).emit();\n    }\n\n    internal_register_account(account_id: AccountId) {\n        if (this.accounts.containsKey(account_id)) {\n            throw Error(\"The account is already registered\");\n        }\n        this.accounts.set(account_id, 0n);\n    }\n\n    /** Internal method that returns the amount of burned tokens in a corner case when the sender\n     * has deleted (unregistered) their account while the `ft_transfer_call` was still in flight.\n     * Returns (Used token amount, Burned token amount)\n     */\n    internal_ft_resolve_transfer(sender_id: AccountId, receiver_id: AccountId, amount: Balance): [bigint, bigint] {\n        // Get the unused amount from the `ft_on_transfer` call result.\n        let unused_amount: Balance;\n        try {\n            const promise_result = near.promiseResult(0).replace(/\"*/g, ''); //TODO: why promiseResult returns result with brackets?\n            unused_amount = this.bigIntMin(amount, BigInt(promise_result));\n        } catch (e) {\n            if (e.message.includes('Failed')) {\n                unused_amount = amount;\n            } else {\n                throw e;\n            }\n        }\n\n        if (unused_amount > 0) {\n            let receiver_balance: Balance = BigInt(this.accounts.get(receiver_id) ?? 0);\n            if (receiver_balance > 0n) {\n                let refund_amount: Balance = this.bigIntMin(receiver_balance, unused_amount);\n                let new_receiver_balance: Balance = receiver_balance - refund_amount;\n                if (new_receiver_balance < 0n) {\n                    throw Error(\"The receiver account doesn't have enough balance\");\n                }\n                this.accounts.set(receiver_id, new_receiver_balance);\n                let sender_balance = this.accounts.get(sender_id);\n                if (sender_balance) {\n                    sender_balance = BigInt(sender_balance);\n                    let new_sender_balance: Balance = sender_balance + refund_amount;\n                    this.accounts.set(sender_id, new_sender_balance);\n                    new FtTransfer(\n                        receiver_id,\n                        sender_id,\n                        refund_amount,\n                        \"refund\",\n                    ).emit();\n\n                    let used_amount: Balance = amount - refund_amount;\n                    if (used_amount < 0n) {\n                        throw Error(ERR_TOTAL_SUPPLY_OVERFLOW);\n                    }\n                    return [used_amount.valueOf(), 0n];\n                } else {\n                    const new_total_supply = this.total_supply - refund_amount;\n                    if (new_total_supply < 0) {\n                        throw Error(ERR_TOTAL_SUPPLY_OVERFLOW);\n                    }\n                    this.total_supply = new_total_supply\n                    near.log(\"The account of the sender was deleted\");\n                    new FtBurn(\n                        receiver_id,\n                        refund_amount,\n                        \"refund\",\n                    ).emit();\n                    return [amount, refund_amount];\n                }\n            }\n        }\n        return [amount, 0n];\n    }\n\n    /** Implementation of FungibleTokenCore */\n    ft_transfer({\n        receiver_id,\n        amount,\n        memo\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo?: String\n    }) {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        let sender_id: AccountId = near.predecessorAccountId();\n        this.internal_transfer(sender_id, receiver_id, amount, memo);\n    }\n\n    ft_transfer_call({\n        receiver_id,\n        amount,\n        memo,\n        msg\n    }: {\n        receiver_id: AccountId,\n        amount: Balance,\n        memo: Option<String>,\n        msg: string\n    }): PromiseOrValue<bigint> {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        assert(near.prepaidGas() > GAS_FOR_FT_TRANSFER_CALL, \"More gas is required\");\n        let sender_id: AccountId = near.predecessorAccountId();\n        this.internal_transfer(sender_id, receiver_id, amount, memo);\n        let receiver_gas: bigint = near.prepaidGas() - GAS_FOR_FT_TRANSFER_CALL;\n        if (receiver_gas < 0) {\n            throw new Error(\"Prepaid gas overflow\");\n        }\n\n        return NearPromise.new(receiver_id)\n            .functionCall(\"ft_on_transfer\", JSON.stringify({ sender_id, amount: String(amount), msg }), BigInt(0), receiver_gas)\n            .then(\n                NearPromise.new(near.currentAccountId())\n                    .functionCall(\n                        \"ft_resolve_transfer\",\n                        JSON.stringify({ sender_id, receiver_id, amount: String(amount) }),\n                        BigInt(0),\n                        GAS_FOR_RESOLVE_TRANSFER\n                    )\n            );\n    }\n\n    ft_total_supply(): Balance {\n        return this.total_supply;\n    }\n\n    ft_balance_of({ account_id }: { account_id: AccountId }): Balance {\n        return this.accounts.get(account_id) ?? 0n;\n    }\n\n    /** Implementation of storage\n     * Internal method that returns the Account ID and the balance in case the account was\n     * unregistered.\n     */\n    internal_storage_unregister(force?: boolean): Option<[AccountId, Balance]> {\n        assert_one_yocto();\n        let account_id: AccountId = near.predecessorAccountId();\n\n        let balance: Balance = BigInt(this.accounts.get(account_id));\n        if (balance || balance == 0n) {\n            if (balance == 0n || force) {\n                this.accounts.remove(account_id);\n                this.total_supply = this.total_supply - balance;\n                NearPromise.new(account_id).transfer(this.storage_balance_bounds().min + 1n);\n                return [account_id, balance];\n            } else {\n                throw Error(\"Can't unregister the account with the positive balance without force\");\n            }\n        } else {\n            near.log(`The account ${account_id} is not registered`);\n            return null;\n        }\n    }\n\n    internal_storage_balance_of(account_id: AccountId): Option<StorageBalance> {\n        if (this.accounts.containsKey(account_id)) {\n            return new StorageBalance(this.storage_balance_bounds().min, 0n);\n        } else {\n            return null;\n        }\n    }\n\n    /** Implementation of StorageManagement\n     * @param registration_only doesn't affect the implementation for vanilla fungible token.\n     */\n    storage_deposit(\n        {\n            account_id,\n            registration_only,\n        }: {\n            account_id?: AccountId,\n            registration_only?: boolean,\n        }\n    ): StorageBalance {\n        let amount: Balance = near.attachedDeposit();\n        account_id = account_id ?? near.predecessorAccountId();\n        if (this.accounts.containsKey(account_id)) {\n            near.log!(\"The account is already registered, refunding the deposit\");\n            if (amount > 0) {\n                NearPromise.new(near.predecessorAccountId()).transfer(amount);\n            }\n        } else {\n            let min_balance: Balance = this.storage_balance_bounds().min;\n            if (amount < min_balance) {\n                throw Error(\"The attached deposit is less than the minimum storage balance\");\n            }\n\n            this.internal_register_account(account_id);\n            let refund: Balance = amount - min_balance;\n            if (refund > 0) {\n                NearPromise.new(near.predecessorAccountId()).transfer(refund);\n            }\n        }\n        return this.internal_storage_balance_of(account_id);\n    }\n\n    /**\n     * While storage_withdraw normally allows the caller to retrieve `available` balance, the basic\n     * Fungible Token implementation sets storage_balance_bounds.min == storage_balance_bounds.max,\n     * which means available balance will always be 0. So this implementation:\n     * - panics if `amount > 0`\n     * - never transfers Ⓝ to caller\n     * - returns a `storage_balance` struct if `amount` is 0\n     */\n    storage_withdraw({ amount }: { amount?: bigint }): StorageBalance {\n        amount = BigInt(amount);\n        assert_one_yocto();\n        let predecessor_account_id: AccountId = near.predecessorAccountId();\n        const storage_balance = this.internal_storage_balance_of(predecessor_account_id);\n        if (storage_balance) {\n            if (amount && amount > 0) {\n                throw Error(\"The amount is greater than the available storage balance\");\n            }\n            return storage_balance;\n        } else {\n            throw Error(`The account ${predecessor_account_id} is not registered`)\n        }\n    }\n\n    storage_unregister({ force }: { force?: boolean }): boolean {\n        return this.internal_storage_unregister(force) ? true : false;\n    }\n\n    storage_balance_bounds(): StorageBalanceBounds {\n        let required_storage_balance: Balance = this.account_storage_usage * near.storageByteCost();\n        return new StorageBalanceBounds(required_storage_balance, required_storage_balance);\n    }\n\n    storage_balance_of({ account_id }: { account_id: AccountId }): Option<StorageBalance> {\n        return this.internal_storage_balance_of(account_id);\n    }\n\n    /** Implementation of FungibleTokenResolver */\n    ft_resolve_transfer({\n        sender_id,\n        receiver_id,\n        amount\n    }: {\n        sender_id: AccountId,\n        receiver_id: AccountId,\n        amount: Balance\n    }): Balance {\n        amount = BigInt(amount);\n        const res = this.internal_ft_resolve_transfer(sender_id, receiver_id, amount);\n        const used_amount = res[0];\n        const burned_amount = res[1];\n        if (burned_amount > 0) {\n            near.log(`Account @${sender_id} burned ${burned_amount}`);\n        }\n        return used_amount;\n    }\n\n    bigIntMax = (...args: bigint[]) => args.reduce((m, e) => e > m ? e : m);\n    bigIntMin = (...args: bigint[]) => args.reduce((m, e) => e < m ? e : m);\n\n    static reconstruct(data: FungibleToken): FungibleToken {\n        const ret = new FungibleToken();\n        Object.assign(ret, data);\n        if (ret.accounts) {\n            ret.accounts = LookupMap.reconstruct(ret.accounts);\n        }\n\n        if (ret.total_supply) {\n            ret.total_supply = BigInt(ret.total_supply) as Balance;\n        }\n\n        if (ret.account_storage_usage) {\n            ret.account_storage_usage = BigInt(ret.account_storage_usage) as StorageUsage;\n        }\n\n        return ret;\n    }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/events.ts",
    "content": "/**\n * Standard for nep141 (Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <https://github.com/near/NEPs/blob/master/specs/Standards/FungibleToken/Event.md>\n *\n * This is an extension of the events format (nep-297):\n * <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>\n *\n * The three events in this standard are [`FtMint`], [`FtTransfer`], and [`FtBurn`].\n *\n * These events can be logged by calling `.emit()` on them if a single event, or calling\n * [`FtMint::emit_many`], [`FtTransfer::emit_many`],\n * or [`FtBurn::emit_many`] respectively.\n */\n\nimport { NearEvent } from \"../event\";\nimport { Option } from \"../non_fungible_token/utils\";\nimport { AccountId, Balance } from \"near-sdk-js\";\nimport { toSnakeCase } from \"../util\";\n\nexport type Nep141EventKind = FtMint[] | FtTransfer[] | FtBurn[];\n\nexport class Nep141Event extends NearEvent {\n  standard: string;\n  version: string;\n  event: string;\n  data: Nep141EventKind;\n\n  constructor(version: string, event_kind: Nep141EventKind) {\n    super();\n    this.standard = \"nep141\"\n    this.version = version\n    this.event = toSnakeCase(event_kind[0].constructor.name)\n    this.data = event_kind\n  }\n}\n\n/** Data to log for an FT mint event. To log this event, call [`.emit()`](FtMint::emit). */\nexport class FtMint {\n    owner_id: AccountId;\n    amount: number;\n    memo: Option<string>;\n\n    constructor(owner_id: AccountId, amount: number, memo: Option<string>) {\n        this.owner_id = owner_id;\n        this.amount = amount;\n        this.memo = memo;\n    }\n\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this])\n    }\n\n    /** Emits an FT mint event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtMint`] represents the data of each mint.\n     */\n    emit_many(data: FtMint[]) {\n        new_141_v1(data).emit()\n    }\n}\n\n/** Data to log for an FT transfer event. To log this event,\n * call [`.emit()`](FtTransfer::emit).\n */\nexport class FtTransfer {\n    old_owner_id: AccountId;\n    new_owner_id: AccountId;\n    amount: string;\n    memo: Option<String>;\n\n    constructor(old_owner_id: AccountId, new_owner_id: AccountId, amount: bigint, memo: Option<String>) {\n        this.old_owner_id = old_owner_id;\n        this.new_owner_id = new_owner_id;\n        this.amount = amount.toString();\n        this.memo = memo;\n    }\n\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this])\n    }\n\n    /** Emits an FT transfer event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtTransfer`] represents the data of each transfer.\n     */\n     emit_many(data: FtTransfer[]) {\n        new_141_v1(data).emit()\n     }\n}\n\n/** Data to log for an FT burn event. To log this event, call [`.emit()`](FtBurn::emit). */\nexport class FtBurn {\n    owner_id: AccountId;\n    amount: string;\n    memo: Option<string>;\n\n    constructor(owner_id: AccountId, amount: Balance, memo: Option<string>) {\n        this.owner_id = owner_id;\n        this.amount = amount.toString();\n        this.memo = memo;\n    }\n\n    /** Logs the event to the host. This is required to ensure that the event is triggered\n     * and to consume the event.\n     */\n    emit() {\n        this.emit_many([this])\n    }\n\n    /** Emits an FT burn event, through [`env::log_str`](near_sdk::env::log_str),\n     * where each [`FtBurn`] represents the data of each burn.\n     */\n    emit_many(data: FtBurn[]) {\n        new_141_v1(data).emit()\n    }\n}\n\nfunction new_141(version: string, event_kind: Nep141EventKind): NearEvent {\n    return new Nep141Event(version, event_kind);\n}\n\nfunction new_141_v1(event_kind: Nep141EventKind) : NearEvent {\n    return new_141(\"1.0.0\", event_kind)\n}\n\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/index.ts",
    "content": "export * from './core_impl';\nexport * from './core';\nexport * from './events';\nexport * from './metadata';\nexport * from './receiver';\nexport * from './resolver';"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/metadata.ts",
    "content": "import {\n    assert,\n} from \"near-sdk-js\";\n\nimport { Option } from \"../non_fungible_token/utils\";\n\nconst FT_METADATA_SPEC: string = \"ft-1.0.0\";\n\n/**\n * Return metadata for the token, up to contract to implement.\n */\nexport class FungibleTokenMetadata {\n    spec: string;\n    name: string;\n    symbol: string;\n    icon: Option<string>;\n    reference: Option<string>;\n    reference_hash: Option<Uint8Array>;\n    decimals: number;\n\n    constructor(\n        spec: string,\n        name: string,\n        symbol: string,\n        icon: Option<string>,\n        referance: Option<string>,\n        referance_hash: Option<Uint8Array>,\n        decimals: number,\n    ) {\n        this.spec = spec;\n        this.name = name;\n        this.symbol = symbol;\n        this.icon = icon;\n        this.reference = referance;\n        this.reference_hash = referance_hash;\n        this.decimals = decimals;\n    }\n\n    assert_valid() {\n        assert(this.spec == FT_METADATA_SPEC, \"Invalid FT_METADATA_SPEC\");\n        const isReferenceProvided: boolean = this.reference ? true : false;\n        const isReferenceHashProvided: boolean = this.reference_hash ? true : false;\n        assert(isReferenceHashProvided === isReferenceProvided, \"reference and reference_hash must be either both provided or not\");\n        if (this.reference_hash) {\n            assert(this.reference_hash.length === 32, \"reference_hash must be 32 bytes\");\n        }\n    }\n}\n\nexport interface FungibleTokenMetadataProvider {\n    ft_metadata() : FungibleTokenMetadata;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/receiver.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n\n/**\n * Provides token transfer resolve functionality.\n * \n * # Examples\n *\n * ```typescript\n\n * import { AccountId, PromiseOrValue } from \"near-sdk-js\";\n * import { FungibleTokenCore, FungibleToken, FungibleTokenReceiver } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore, FungibleTokenReceiver {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *   @call({})\n *    ft_on_transfer({ sender_id, amount, msg }: {\n *           sender_id: AccountId;\n *           amount: number;\n *           msg: String;\n *   }): PromiseOrValue<number> {\n *       return this.token.ft_on_transfer({ sender_id, amount, msg });\n *   };\n * }\n * ```\n */\nexport interface FungibleTokenReceiver {\n    /**\n     * Called by fungible token contract after `ft_transfer_call` was initiated by\n     * `sender_id` of the given `amount` with the transfer message given in `msg` field.\n     * The `amount` of tokens were already transferred to this contract account and ready to be used.\n     *\n     * The method must return the amount of tokens that are *not* used/accepted by this contract from the transferred\n     * amount. Examples:\n     * - The transferred amount was `500`, the contract completely takes it and must return `0`.\n     * - The transferred amount was `500`, but this transfer call only needs `450` for the action passed in the `msg`\n     *   field, then the method must return `50`.\n     * - The transferred amount was `500`, but the action in `msg` field has expired and the transfer must be\n     *   cancelled. The method must return `500` or panic.\n     *\n     * Arguments:\n     * @param sender_id - the account ID that initiated the transfer.\n     * @param amount - the amount of tokens that were transferred to this account in a decimal string representation.\n     * @param msg - a string message that was passed with this transfer call.\n     *\n     * @returns the amount of unused tokens that should be returned to sender, in a decimal string representation.\n     */\n    ft_on_transfer({\n        sender_id,\n        amount,\n        msg\n    }: {\n        sender_id: AccountId,\n        amount: number,\n        msg: String\n    }\n    ): PromiseOrValue<number>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/fungible_token/resolver.ts",
    "content": "import { AccountId, Balance } from \"near-sdk-js\";\n\n/**\n * Provides token transfer resolve functionality.\n *\n * # Examples\n *\n * ```typescript\n * import { AccountId, Balance, call } from \"near-sdk-js\";\n * import {\n *   FungibleTokenCore,\n *   FungibleTokenResolver,\n *   FungibleToken,\n * } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements FungibleTokenCore, FungibleTokenResolver {\n *     private token: FungibleToken;\n *\n *     constructor() {\n *         this.token = new FungibleToken();\n *     }\n *\n *     @call({ privateFunction: true })\n *     ft_resolve_transfer({\n *         sender_id,\n *         receiver_id,\n *         amount,\n *     }: {\n *         sender_id: AccountId,\n *         receiver_id: AccountId,\n *         amount: Balance\n *     }): Balance {\n *         const { used_amount, burned_amount } = this.token.internal_ft_resolve_transfer(sender_id, receiver_id, amount);\n *         if (burned_amount > 0) {\n *             console.log(`Account @${sender_id} burned ${burned_amount}`);\n *         }\n *         return used_amount;\n *     }\n * }\n * ```\n */\nexport interface FungibleTokenResolver {\n   /**\n   * Resolves the transfer of tokens between `sender_id` and `receiver_id`.\n   *\n   * @param sender_id - The account ID of the sender.\n   * @param receiver_id - The account ID of the receiver.\n   * @param amount - The amount of tokens to resolve in a decimal string representation.\n   *\n   * @returns The amount of tokens used during the transfer, returning the balance as a `Balance`.\n   */\n    ft_resolve_transfer({\n        sender_id,\n        receiver_id,\n        amount,\n    }: {\n        sender_id: AccountId,\n        receiver_id: AccountId,\n        amount: Balance,\n    }): Balance;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/index.ts",
    "content": "/** Non-fungible tokens as described in [by the spec](https://nomicon.io/Standards/NonFungibleToken). */\nexport * from \"./non_fungible_token\";\n/** Fungible tokens as described in [by the spec](https://nomicon.io/Standards/FungibleToken). */\nexport * from \"./fungible_token\";\n\nexport * from \"./storage_management\";"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/approval/approval_receiver.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Approval receiver is the interface for the method called (or attempted to be called) when an NFT contract adds an approval for an account. */\nexport interface NonFungibleTokenApprovalReceiver {\n  /** Respond to notification that contract has been granted approval for a token.\n   * \n   * Notes\n   * - Contract knows the token contract ID from `predecessor_account_id`\n   *\n   * @param token_id - The token to which this contract has been granted approval\n   * @param owner_id - The owner of the token\n   * @param approval_id - The approval ID stored by NFT contract for this approval. \n   *        Expected to be a number within the 2^53 limit representable by JSON.\n   * @param msg: - specifies information needed by the approved contract in order to\n            handle the approval. Can indicate both a function to call and the\n            parameters to pass to that function. \n  */\n  nft_on_approve({\n    token_id,\n    owner_id,\n    approval_id,\n    msg,\n  }: {\n    token_id: TokenId;\n    owner_id: AccountId;\n    approval_id: bigint;\n    msg: string;\n  }): PromiseOrValue<string>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/approval/index.ts",
    "content": "import { AccountId, NearPromise } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n\n/** Interface used when it's desired to have a non-fungible token that has a\n * traditional escrow or approval system. This allows Alice to allow Bob\n * to take only the token with the unique identifier \"19\" but not others.\n * It should be noted that in the [core non-fungible token standard] there\n * is a method to do \"transfer and call\" which may be preferred over using\n * an approval management standard in certain use cases.\n *\n * [approval management standard]: https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html\n * [core non-fungible token standard]: https://nomicon.io/Standards/NonFungibleToken/Core.html\n */\nexport interface NonFungibleTokenApproval {\n  /** Add an approved account for a specific token.\n   *\n   * Requirements\n   * - Caller of the method must attach a deposit of at least 1 yoctoⓃ for\n   *   security purposes\n   * - Contract MAY require caller to attach larger deposit, to cover cost of\n   *   storing approver data\n   * - Contract MUST panic if called by someone other than token owner\n   * - Contract MUST panic if addition would cause `nft_revoke_all` to exceed\n   *   single-block gas limit\n   * - Contract MUST increment approval ID even if re-approving an account\n   * - If successfully approved or if had already been approved, and if `msg` is\n   *   present, contract MUST call `nft_on_approve` on `account_id`. See\n   *   `nft_on_approve` description below for details.\n   *\n   * @param token_id - The token for which to add an approval\n   * @param account_id - The account to add to `approvals`\n   * @param msg - Optional string to be passed to `nft_on_approve`\n   * @returns void, if no `msg` given. Otherwise, returns promise call to\n   *          `nft_on_approve`, which can resolve with whatever it wants.\n   */\n  nft_approve({\n    token_id,\n    account_id,\n    msg,\n  }: {\n    token_id: TokenId;\n    account_id: AccountId;\n    msg?: string;\n  }): Option<NearPromise>;\n\n  /** Revoke an approved account for a specific token.\n   *\n   * Requirements\n   * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n   *   purposes\n   * - If contract requires >1yN deposit on `nft_approve`, contract\n   *   MUST refund associated storage deposit when owner revokes approval\n   * - Contract MUST panic if called by someone other than token owner\n   *\n   * @param token_id - The token for which to revoke an approval\n   * @param account_id - The account to remove from `approvals`\n   */\n  nft_revoke({\n    token_id,\n    account_id,\n  }: {\n    token_id: TokenId;\n    account_id: AccountId;\n  });\n\n  /** Revoke all approved accounts for a specific token.\n   *\n   * Requirements\n   * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n   *   purposes\n   * - If contract requires >1yN deposit on `nft_approve`, contract\n   *   MUST refund all associated storage deposit when owner revokes approvals\n   * - Contract MUST panic if called by someone other than token owner\n   *\n   * @param token_id - The token with approvals to revoke\n   */\n  nft_revoke_all({ token_id }: { token_id: TokenId });\n\n  /** Check if a token is approved for transfer by a given account, optionally\n   * checking an approval_id\n   *\n   * @param token_id - The token for which to revoke an approval\n   * @param approved_account_id - The account to check the existence of in `approvals`\n   * @param approval_id - An optional approval ID to check against current approval ID for given account\n   * @returns if `approval_id` given, `true` if `approved_account_id` is approved with given `approval_id`\n   * otherwise, `true` if `approved_account_id` is in list of approved accounts\n   */\n  nft_is_approved({\n    token_id,\n    approved_account_id,\n    approval_id,\n  }: {\n    token_id: TokenId;\n    approved_account_id: AccountId;\n    approval_id?: bigint;\n  }): boolean;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/core/index.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { Token, TokenId } from \"../token\";\nimport { Option } from \"../utils\";\n\n/** Used for all non-fungible tokens. The specification for the\n * [core non-fungible token standard] lays out the reasoning for each method.\n * It's important to check out [NonFungibleTokenReceiver](./receiver.ts)\n * and [NonFungibleTokenResolver](./resolver.ts) to\n * understand how the cross-contract call work.\n *\n * [core non-fungible token standard]: <https://nomicon.io/Standards/NonFungibleToken/Core.html>\n * \n * # Examples\n *\n * ```typescript\n\n * import { AccountId } from \"near-sdk-js\";\n * import { Option } from \"../non_fungible_token/utils\";\n * import { Token, TokenId } from \"../token\";\n * import { NonFungibleTokenCore, NonFungibleToken } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements NonFungibleTokenCore {\n *     private token: NonFungibleToken;\n *\n *     constructor() {\n *         this.tokens = new NonFungibleToken();\n *     }\n *\n *     @call({})\n *      nft_transfer({ receiver_id, token_id, approval_id, memo }: {\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approval_id?: bigint;\n            memo?: string;\n        }): any {\n *         this.tokens.nft_transfer({ receiver_id, token_id, approval_id, memo });\n *     }\n *\n *     @call({})\n *     nft_transfer_call({ receiver_id, token_id, approval_id, memo }: {\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approval_id?: bigint;\n            memo?: string;\n            msg: string;\n        }): any {\n *         return this.tokens.nft_transfer_call({ receiver_id, token_id, approval_id, memo });\n *     }\n *\n *     @view({})\n *     nft_token({ token_id }: {\n        token_id: TokenId;\n        }): Option<Token> {\n            return this.tokens.nft_token({ token_id });\n        };\n * }\n * ```\n */\nexport interface NonFungibleTokenCore {\n  /** Simple transfer. Transfer a given `token_id` from current owner to\n   * `receiver_id`.\n   *\n   * Requirements\n   * - Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes\n   * - Contract MUST panic if called by someone other than token owner or,\n   *   if using Approval Management, one of the approved accounts\n   * - `approval_id` is for use with Approval Management,\n   *   see <https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html>\n   * - If using Approval Management, contract MUST nullify approved accounts on\n   *   successful transfer.\n   * - TODO: needed? Both accounts must be registered with the contract for transfer to\n   *   succeed. See see <https://nomicon.io/Standards/StorageManagement.html>\n   *\n   * @param receiver_id - The valid NEAR account receiving the token\n   * @param token_id - The token to transfer\n   * @param approval_id - Expected approval ID. A number smaller than\n   *        2^53, and therefore representable as JSON. See Approval Management\n   *        standard for full explanation.\n   * @param memo (optional) - For use cases that may benefit from indexing or\n   *        providing information for a transfer\n   */\n  nft_transfer({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n  }: {\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approval_id?: bigint;\n    memo?: string;\n  });\n\n  /** Transfer token and call a method on a receiver contract. A successful\n   * workflow will end in a success execution outcome to the callback on the NFT\n   * contract at the method `nft_resolve_transfer`.\n   *\n   * You can think of this as being similar to attaching native NEAR tokens to a\n   * function call. It allows you to attach any Non-Fungible Token in a call to a\n   * receiver contract.\n   *\n   * Requirements:\n   * - Caller of the method must attach a deposit of 1 yoctoⓃ for security\n   *   purposes\n   * - Contract MUST panic if called by someone other than token owner or,\n   *   if using Approval Management, one of the approved accounts\n   * - The receiving contract must implement `ft_on_transfer` according to the\n   *   standard. If it does not, FT contract's `ft_resolve_transfer` MUST deal\n   *   with the resulting failed cross-contract call and roll back the transfer.\n   * - Contract MUST implement the behavior described in `ft_resolve_transfer`\n   * - `approval_id` is for use with Approval Management extension, see\n   *   that document for full explanation.\n   * - If using Approval Management, contract MUST nullify approved accounts on\n   *   successful transfer.\n   *\n   * @param receiver_id - The valid NEAR account receiving the token.\n   * @param token_id - The token to send.\n   * @param approval_id - Expected approval ID. A number smaller than\n   *        2^53, and therefore representable as JSON. See Approval Management\n   *        standard for full explanation.\n   * @param memo (optional) - For use cases that may benefit from indexing or\n   *        providing information for a transfer.\n   * @param msg - Specifies information needed by the receiving contract in\n   *        order to properly handle the transfer. Can indicate both a function to\n   *        call and the parameters to pass to that function.\n   */\n  nft_transfer_call({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n  }: {\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approval_id?: bigint;\n    memo?: string;\n    msg: string;\n  });\n\n  /** Returns the token with the given `token_id` or `null` if no such token. */\n  nft_token({ token_id }: { token_id: TokenId }): Option<Token>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/core/receiver.ts",
    "content": "import { AccountId, PromiseOrValue } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Used when an NFT is transferred using `nft_transfer_call`. This interface is implemented on the receiving contract, not on the NFT contract. */\nexport interface NonFungibleTokenReceiver {\n  /** Take some action after receiving a non-fungible token\n   *\n   * Requirements:\n   * - Contract MUST restrict calls to this function to a set of whitelisted NFT\n   *   contracts\n   *\n   * @param sender_id - The sender of `nft_transfer_call`\n   * @param previous_owner_id - The account that owned the NFT prior to it being\n   *        transferred to this contract, which can differ from `sender_id` if using\n   *        Approval Management extension\n   * @param token_id - The `token_id` argument given to `nft_transfer_call`\n   * @param msg - Information necessary for this contract to know how to process the\n   *        request. This may include method names and/or arguments.\n   *\n   * @returns true if token should be returned to `sender_id`\n   */\n  nft_on_transfer({\n    sender_id,\n    previous_owner_id,\n    token_id,\n    msg,\n  }: {\n    sender_id: AccountId;\n    previous_owner_id: AccountId;\n    token_id: TokenId;\n    msg: string;\n  }): PromiseOrValue<boolean>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/core/resolver.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { TokenId } from \"../token\";\n\n/** Used when an NFT is transferred using `nft_transfer_call`. This is the method that's called after `nft_on_transfer`. This interface is implemented on the NFT contract. \n * \n * # Examples\n *\n * ```typescript\n\n * import { AccountId } from \"near-sdk-js\";\n * import { TokenId } from \"../token\";\n * import { NonFungibleTokenCore, NonFungibleToken, NonFungibleTokenResolver } from \"near-contract-standards/lib\"\n *\n * @NearBindgen({ requireInit: false })\n * export class Contract implements NonFungibleTokenCore, NonFungibleTokenResolver {\n *     private token: NonFungibleToken;\n *\n *     constructor() {\n *         this.tokens = new NonFungibleToken();\n *     }\n *\n *     @call({})\n *     nft_resolve_transfer({ previous_owner_id, receiver_id, token_id, approved_account_ids, }: {\n            previous_owner_id: AccountId;\n            receiver_id: AccountId;\n            token_id: TokenId;\n            approved_account_ids?: {\n                [approval: AccountId]: bigint;\n            };\n    }): boolean; {\n        return this.tokens.nft_resolve_transfer({\n            previous_owner_id,\n            receiver_id,\n            token_id,\n            approved_account_ids,\n            });\n        }\n * }\n * ```\n*/\nexport interface NonFungibleTokenResolver {\n  /** Finalize an `nft_transfer_call` chain of cross-contract calls.\n   *\n   * The `nft_transfer_call` process:\n   *\n   * 1. Sender calls `nft_transfer_call` on FT contract\n   * 2. NFT contract transfers token from sender to receiver\n   * 3. NFT contract calls `nft_on_transfer` on receiver contract\n   * 4+. [receiver contract may make other cross-contract calls]\n   * N. NFT contract resolves promise chain with `nft_resolve_transfer`, and may\n   *    transfer token back to sender\n   *\n   * Requirements:\n   * - Contract MUST forbid calls to this function by any account except self\n   * - If promise chain failed, contract MUST revert token transfer\n   * - If promise chain resolves with `true`, contract MUST return token to\n   *   `sender_id`\n   *\n   * @param previous_owner_id - The owner prior to the call to `nft_transfer_call`\n   * @param receiver_id - The `receiver_id` argument given to `nft_transfer_call`\n   * @param token_id - The `token_id` argument given to `ft_transfer_call`\n   * @param approved_account_ids - If using Approval Management, contract MUST provide\n   *        set of original approved accounts in this argument, and restore these\n   *        approved accounts in case of revert.\n   *\n   * @returns true if token was successfully transferred to `receiver_id`.\n   */\n  nft_resolve_transfer({\n    previous_owner_id,\n    receiver_id,\n    token_id,\n    approved_account_ids,\n  }: {\n    previous_owner_id: AccountId;\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approved_account_ids?: { [approval: AccountId]: bigint };\n  }): boolean;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/enumeration/index.ts",
    "content": "import { AccountId } from \"near-sdk-js\";\nimport { Token } from \"../token\";\n\n/** Offers methods helpful in determining account ownership of NFTs and provides a way to page through NFTs per owner, determine total supply, etc. */\nexport interface NonFungibleTokenEnumeration {\n  /** Returns the total supply of non-fungible tokens */\n  nft_total_supply(): number;\n\n  /** Get a list of all tokens\n   *\n   * @param from_index - The starting index of tokens to return\n   * @param limit - The maximum number of tokens to return\n   * @returns - An array of Token objects, as described in Core standard\n   */\n  nft_tokens({\n    from_index,\n    limit,\n  }: {\n    from_index?: number; // default: \"0\"\n    limit?: number; // default: unlimited (could fail due to gas limit)\n  }): Token[];\n\n  /** Get number of tokens owned by a given account\n   *\n   * @param account_id - A valid NEAR account\n   * @returns - The number of non-fungible tokens owned by given `account_id`\n   */\n  nft_supply_for_owner({ account_id }: { account_id: AccountId }): number;\n\n  /** Get list of all tokens owned by a given account\n   *\n   * @param account_id - A valid NEAR account\n   * @param from_index - The starting index of tokens to return\n   * @param limit - The maximum number of tokens to return\n   * @returns - A paginated list of all tokens owned by this account\n   */\n  nft_tokens_for_owner({\n    account_id,\n    from_index,\n    limit,\n  }: {\n    account_id: AccountId;\n    from_index?: number; // default: \"0\"\n    limit?: number; // default: unlimited (could fail due to gas limit)\n  }): Token[];\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/events.ts",
    "content": "/** Standard for nep171 (Non-Fungible Token) events.\n *\n * These events will be picked up by the NEAR indexer.\n *\n * <https://github.com/near/NEPs/blob/69f76c6c78c2ebf05d856347c9c98ae48ad84ebd/specs/Standards/NonFungibleToken/Event.md>\n *\n * This is an extension of the events format (nep-297):\n * <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>\n *\n * The three events in this standard are [`NftMint`], [`NftTransfer`], and [`NftBurn`].\n *\n * These events can be logged by calling `.emit()` on them if a single event, or calling\n * [`NftMint.emit_many`], [`NftTransfer.emit_many`],\n * or [`NftBurn.emit_many`] respectively.\n */\nimport { AccountId } from \"near-sdk-js\";\nimport { NearEvent } from \"../event\";\nimport { TokenId } from \"./token\";\nimport { toSnakeCase } from \"../util\";\n\nexport type Nep171EventKind = NftMint[] | NftTransfer[] | NftBurn[] | NftContractMetadataUpdate[];\n\nexport class Nep171Event extends NearEvent {\n  standard: string;\n  version: string;\n  event: string;\n  data: Nep171EventKind;\n\n  constructor(version: string, event_kind: Nep171EventKind) {\n    super();\n    this.standard = \"nep171\"\n    this.version = version\n    this.event = toSnakeCase(event_kind[0].constructor.name)\n    this.data = event_kind\n  }\n}\n\n/** Data to log for an NFT mint event. To log this event, call `.emit()` */\nexport class NftMint {\n  constructor(\n    public owner_id: AccountId,\n    public token_ids: TokenId[],\n    public memo?: string\n  ) {}\n\n  /** Logs the event to the host. This is required to ensure that the event is triggered\n   * and to consume the event. */\n  emit() {\n    NftMint.emit_many([this]);\n  }\n\n  /** Emits an nft mint event, through `near.log`,\n   * where each [`NftMint`] represents the data of each mint. */\n  static emit_many(data: NftMint[]) {\n    new_171_v1(data).emit();\n  }\n}\n\n/** Data to log for an NFT transfer event. To log this event,\n * call [`.emit()`](NftTransfer.emit). */\nexport class NftTransfer {\n  constructor(\n    public old_owner_id: AccountId,\n    public new_owner_id: AccountId,\n    public token_ids: TokenId[],\n    public authorized_id?: AccountId,\n    public memo?: string\n  ) {}\n\n  /** Logs the event to the host. This is required to ensure that the event is triggered\n   * and to consume the event. */\n  emit() {\n    NftTransfer.emit_many([this]);\n  }\n\n  /** Emits an nft transfer event, through `near.log`,\n   * where each [`NftTransfer`] represents the data of each transfer. */\n  static emit_many(data: NftTransfer[]) {\n    new_171_v1(data).emit();\n  }\n}\n\n/** Data to log for an NFT burn event. To log this event, call [`.emit()`](NftBurn.emit). */\nexport class NftBurn {\n  constructor(\n    public owner_id: AccountId,\n    public token_ids: TokenId[],\n    public authorized_id?: string,\n    public memo?: string\n  ) {}\n\n  /** Logs the event to the host. This is required to ensure that the event is triggered\n   * and to consume the event. */\n  emit() {\n    NftBurn.emit_many([this]);\n  }\n\n  /** Emits an nft burn event, through `near.log`,\n   * where each [`NftBurn`] represents the data of each burn. */\n  static emit_many(data: NftBurn[]) {\n    new_171_v1(data).emit();\n  }\n}\n\n/** Data to log for an NFT contract metadata updates. To log this event, call [`.emit()`](NftContractMetadataUpdate.emit). */\nexport class NftContractMetadataUpdate {\n  constructor(\n      public memo?: string\n  ) {}\n\n  /** Logs the event to the host. This is required to ensure that the event is triggered\n   * and to consume the event. */\n  emit() {\n    NftContractMetadataUpdate.emit_many([this]);\n  }\n\n  /** Emits an contract metadata update event, through `near.log`,\n   * where each [`NftBurn`] represents the data of each burn. */\n  static emit_many(data: NftContractMetadataUpdate[]) {\n    new_171_v1(data).emit();\n  }\n}\n\nfunction new_171(version: string, event_kind: Nep171EventKind): NearEvent {\n  return new Nep171Event(version, event_kind);\n}\n\nfunction new_171_v1(event_kind: Nep171EventKind): NearEvent {\n  return new_171(\"1.0.0\", event_kind);\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/impl.ts",
    "content": "import {\n  AccountId,\n  UnorderedMap,\n  LookupMap,\n  near,\n  UnorderedSet,\n  assert,\n  NearPromise,\n  bytes,\n  serialize,\n  str,\n  IntoStorageKey,\n} from \"near-sdk-js\";\nimport { TokenMetadata } from \"./metadata\";\nimport {\n  refund_storage_deposit,\n  refund_deposit,\n  refund_deposit_to_account,\n  assert_at_least_one_yocto,\n  Option,\n  assert_one_yocto,\n} from \"./utils\";\nimport { NftMint, NftTransfer } from \"./events\";\nimport { NonFungibleTokenResolver } from \"./core/resolver\";\nimport { Token, TokenId } from \"./token\";\nimport { NonFungibleTokenCore } from \"./core\";\nimport { NonFungibleTokenApproval } from \"./approval\";\nimport { NonFungibleTokenEnumeration } from \"./enumeration\";\n\nconst GAS_FOR_RESOLVE_TRANSFER = 16_000_000_000_000n;\nconst GAS_FOR_NFT_TRANSFER_CALL =\n  30_000_000_000_000n + GAS_FOR_RESOLVE_TRANSFER;\nconst GAS_FOR_NFT_APPROVE = 21_000_000_000_000n;\n\nfunction repeat(str: string, n: number) {\n  return Array(n + 1).join(str);\n}\n\nfunction expect_token_found<T>(option: Option<T>): T {\n  if (option === null) {\n    throw new Error(\"Token not found\");\n  }\n  return option;\n}\n\nfunction expect_approval<T>(option: Option<T>): T {\n  if (option === null) {\n    throw new Error(\"next_approval_by_id must be set for approval ext\");\n  }\n  return option;\n}\n\n/** Implementation of the non-fungible token standard.\n * Allows to include NEP-171 compatible token to any contract.\n * There are next interfaces that any contract may implement:\n *     - NonFungibleTokenCore -- interface with nft_transfer methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenApproval -- interface with nft_approve methods. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenEnumeration -- interface for getting lists of tokens. NonFungibleToken provides methods for it.\n *     - NonFungibleTokenMetadata -- return metadata for the token in NEP-177, up to contract to implement.\n *\n * For example usage, see near-contract-standards/example-contracts/non-fungible-token/my-nft.ts.\n */\nexport class NonFungibleToken\n  implements\n    NonFungibleTokenCore,\n    NonFungibleTokenResolver,\n    NonFungibleTokenApproval,\n    NonFungibleTokenEnumeration\n{\n  public owner_id: AccountId;\n  public extra_storage_in_bytes_per_token: bigint;\n  public owner_by_id: UnorderedMap<AccountId>;\n  public token_metadata_by_id: Option<LookupMap<TokenMetadata>>;\n  public tokens_per_owner: Option<LookupMap<UnorderedSet<TokenId>>>;\n  public approvals_by_id: Option<LookupMap<{ [approvals: AccountId]: bigint }>>;\n  public next_approval_id_by_id: Option<LookupMap<bigint>>;\n\n  constructor() {\n    this.owner_id = \"\";\n    this.extra_storage_in_bytes_per_token = 0n;\n    this.owner_by_id = new UnorderedMap(\"\");\n    this.token_metadata_by_id = null;\n    this.tokens_per_owner = null;\n    this.approvals_by_id = null;\n    this.next_approval_id_by_id = null;\n  }\n\n  nft_total_supply(): number {\n    return this.owner_by_id.length;\n  }\n\n  private enum_get_token(owner_id: AccountId, token_id: TokenId): Token {\n    const metadata = this.token_metadata_by_id.get(token_id, {\n      reconstructor: TokenMetadata.reconstruct,\n    });\n    const approved_account_ids = this.approvals_by_id.get(token_id, {\n      defaultValue: {},\n    });\n    return new Token(token_id, owner_id, metadata, approved_account_ids);\n  }\n\n  nft_tokens({\n    from_index,\n    limit,\n  }: {\n    from_index?: number;\n    limit?: number;\n  }): Token[] {\n    const start_index = from_index === undefined ? 0 : from_index;\n    assert(\n      this.owner_by_id.length >= start_index,\n      \"Out of bounds, please use a smaller from_index.\"\n    );\n    let l = limit === undefined ? 2 ** 32 : limit;\n    assert(l > 0, \"limit must be greater than 0.\");\n    l = Math.min(l, this.owner_by_id.length - start_index);\n    const ret: Token[] = [];\n    const tokens = this.owner_by_id.keys({start: from_index, limit: l});\n    for (let token_id of tokens) {\n      const owner_id = this.owner_by_id.get(token_id);\n      ret.push(this.enum_get_token(owner_id, token_id));\n    }\n    return ret;\n  }\n\n  nft_supply_for_owner({ account_id }: { account_id: AccountId }): number {\n    const tokens_per_owner = this.tokens_per_owner;\n    assert(\n      tokens_per_owner !== null,\n      \"Could not find tokens_per_owner when calling a method on the enumeration standard.\"\n    );\n\n    const account_tokens = tokens_per_owner.get(account_id, {\n      reconstructor: UnorderedSet.reconstruct,\n    });\n    return account_tokens === null ? 0 : account_tokens.length;\n  }\n\n  nft_tokens_for_owner({\n    account_id,\n    from_index,\n    limit,\n  }: {\n    account_id: AccountId;\n    from_index?: number;\n    limit?: number;\n  }): Token[] {\n    const tokens_per_owner = this.tokens_per_owner;\n    assert(\n      tokens_per_owner !== undefined,\n      \"Could not find tokens_per_owner when calling a method on the enumeration standard.\"\n    );\n    const token_set = tokens_per_owner.get(account_id, {\n      reconstructor: UnorderedSet.reconstruct,\n    });\n    assert(token_set !== null, \"Token set is empty\");\n\n    const start_index = from_index === undefined ? 0 : from_index;\n    assert(\n      token_set.length >= start_index,\n      \"Out of bounds, please use a smaller from_index.\"\n    );\n    let l = limit === undefined ? 2 ** 32 : limit;\n    assert(l > 0, \"limit must be greater than 0.\");\n    l = Math.min(l, token_set.length - start_index);\n\n    const ret: Token[] = [];\n    const tokens = token_set.elements({start: from_index, limit: l});\n    for (let token_id of tokens) {\n      const owner_id = this.owner_by_id.get(token_id);\n      ret.push(this.enum_get_token(owner_id, token_id));\n    }\n    return ret;\n  }\n\n  nft_approve({\n    token_id,\n    account_id,\n    msg,\n  }: {\n    token_id: TokenId;\n    account_id: AccountId;\n    msg: string;\n  }): Option<NearPromise> {\n    assert_at_least_one_yocto();\n    if (this.approvals_by_id === null) {\n      throw new Error(\"NFT does not support Approval Management\");\n    }\n    const approvals_by_id = this.approvals_by_id;\n    const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n\n    assert(\n      near.predecessorAccountId() === owner_id,\n      \"Predecessor must be token owner.\"\n    );\n\n    const next_approval_id_by_id = expect_approval(this.next_approval_id_by_id);\n    const approved_account_ids = approvals_by_id.get(token_id) ?? {};\n    const approval_id = next_approval_id_by_id.get(token_id) ?? 1n;\n    const old_approved_account_ids_size =\n      serialize(approved_account_ids).length;\n    approved_account_ids[account_id] = approval_id;\n    const new_approved_account_ids_size =\n      serialize(approved_account_ids).length;\n\n    approvals_by_id.set(token_id, approved_account_ids);\n\n    next_approval_id_by_id.set(token_id, approval_id + 1n);\n\n    const storage_used =\n      new_approved_account_ids_size - old_approved_account_ids_size;\n    refund_deposit(BigInt(storage_used));\n\n    if (msg) {\n      return NearPromise.new(account_id).functionCallRaw(\n        \"nft_on_approve\",\n        serialize({ token_id, owner_id, approval_id, msg }),\n        0n,\n        near.prepaidGas() - GAS_FOR_NFT_APPROVE\n      );\n    }\n    return null;\n  }\n\n  nft_revoke({\n    token_id,\n    account_id,\n  }: {\n    token_id: TokenId;\n    account_id: AccountId;\n  }) {\n    assert_one_yocto();\n    if (this.approvals_by_id === null) {\n      throw new Error(\"NFT does not support Approval Management\");\n    }\n    const approvals_by_id = this.approvals_by_id;\n    const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n\n    const predecessorAccountId = near.predecessorAccountId();\n    assert(\n      predecessorAccountId === owner_id,\n      \"Predecessor must be token owner.\"\n    );\n\n    const approved_account_ids = approvals_by_id.get(token_id);\n    const old_approved_account_ids_size =\n      serialize(approved_account_ids).length;\n    let new_approved_account_ids_size;\n\n    if (approved_account_ids[account_id]) {\n      delete approved_account_ids[account_id];\n      if (Object.keys(approved_account_ids).length === 0) {\n        approvals_by_id.remove(token_id);\n        new_approved_account_ids_size = serialize(approved_account_ids).length;\n      } else {\n        approvals_by_id.set(token_id, approved_account_ids);\n        new_approved_account_ids_size = 0;\n      }\n      refund_storage_deposit(\n        predecessorAccountId,\n        new_approved_account_ids_size - old_approved_account_ids_size\n      );\n    }\n  }\n\n  nft_revoke_all({ token_id }: { token_id: TokenId }) {\n    assert_one_yocto();\n    if (this.approvals_by_id === null) {\n      throw new Error(\"NFT does not support Approval Management\");\n    }\n    const approvals_by_id = this.approvals_by_id;\n    const owner_id = expect_token_found(this.owner_by_id.get(token_id));\n\n    const predecessorAccountId = near.predecessorAccountId();\n    assert(\n      predecessorAccountId === owner_id,\n      \"Predecessor must be token owner.\"\n    );\n\n    const approved_account_ids = approvals_by_id.get(token_id);\n    if (approved_account_ids) {\n      refund_storage_deposit(\n        predecessorAccountId,\n        serialize(approved_account_ids).length\n      );\n\n      approvals_by_id.remove(token_id);\n    }\n  }\n\n  nft_is_approved({\n    token_id,\n    approved_account_id,\n    approval_id,\n  }: {\n    token_id: TokenId;\n    approved_account_id: AccountId;\n    approval_id?: bigint;\n  }): boolean {\n    expect_token_found(this.owner_by_id.get(token_id));\n\n    if (this.approvals_by_id === null) {\n      return false;\n    }\n    const approvals_by_id = this.approvals_by_id;\n\n    const approved_account_ids = approvals_by_id.get(token_id);\n    if (approved_account_ids === null) {\n      return false;\n    }\n\n    const actual_approval_id = approved_account_ids[approved_account_id];\n    if (actual_approval_id === undefined) {\n      return false;\n    }\n\n    if (approval_id) {\n      return BigInt(approval_id) === actual_approval_id;\n    }\n    return true;\n  }\n\n  init(\n    owner_by_id_prefix: IntoStorageKey,\n    owner_id: AccountId,\n    token_metadata_prefix?: IntoStorageKey,\n    enumeration_prefix?: IntoStorageKey,\n    approval_prefix?: IntoStorageKey\n  ) {\n    let approvals_by_id: Option<LookupMap<{ [approvals: AccountId]: bigint }>>;\n    let next_approval_id_by_id: Option<LookupMap<bigint>>;\n    if (approval_prefix) {\n      const prefix = approval_prefix.into_storage_key();\n      approvals_by_id = new LookupMap(prefix);\n      next_approval_id_by_id = new LookupMap(prefix + \"n\");\n    } else {\n      approvals_by_id = null;\n      next_approval_id_by_id = null;\n    }\n\n    this.owner_id = owner_id;\n    this.extra_storage_in_bytes_per_token = 0n;\n    this.owner_by_id = new UnorderedMap(\n      owner_by_id_prefix.into_storage_key()\n    );\n    this.token_metadata_by_id = token_metadata_prefix\n      ? new LookupMap(token_metadata_prefix.into_storage_key())\n      : null;\n    this.tokens_per_owner = enumeration_prefix\n      ? new LookupMap(enumeration_prefix.into_storage_key())\n      : null;\n    this.approvals_by_id = approvals_by_id;\n    this.next_approval_id_by_id = next_approval_id_by_id;\n    this.measure_min_token_storage_cost();\n  }\n\n  static reconstruct(data: NonFungibleToken): NonFungibleToken {\n    const ret = new NonFungibleToken();\n    Object.assign(ret, data);\n    ret.owner_by_id = UnorderedMap.reconstruct(ret.owner_by_id);\n    if (ret.token_metadata_by_id) {\n      ret.token_metadata_by_id = LookupMap.reconstruct(\n        ret.token_metadata_by_id\n      );\n    }\n    if (ret.tokens_per_owner) {\n      ret.tokens_per_owner = LookupMap.reconstruct(ret.tokens_per_owner);\n    }\n    if (ret.approvals_by_id) {\n      ret.approvals_by_id = LookupMap.reconstruct(ret.approvals_by_id);\n    }\n    if (ret.next_approval_id_by_id) {\n      ret.next_approval_id_by_id = LookupMap.reconstruct(\n        ret.next_approval_id_by_id\n      );\n    }\n    return ret;\n  }\n\n  measure_min_token_storage_cost() {\n    const initial_storage_usage = near.storageUsage();\n    // 64 Length because this is the max account id length\n    const tmp_token_id = repeat(\"a\", 64);\n    const tmp_owner_id = repeat(\"a\", 64);\n\n    // 1. set some dummy data\n    this.owner_by_id.set(tmp_token_id, tmp_owner_id);\n    if (this.token_metadata_by_id) {\n      this.token_metadata_by_id.set(\n        tmp_token_id,\n        new TokenMetadata(\n          repeat(\"a\", 64),\n          repeat(\"a\", 64),\n          repeat(\"a\", 64),\n          repeat(\"a\", 64),\n          1n,\n          null,\n          null,\n          null,\n          null,\n          null,\n          null,\n          null\n        )\n      );\n    }\n    if (this.tokens_per_owner) {\n      const u = new UnorderedSet<AccountId>(\n          new TokensPerOwner(\n            near.sha256(bytes(tmp_owner_id))\n          ).into_storage_key()\n      );\n      u.set(tmp_token_id);\n      this.tokens_per_owner.set(tmp_owner_id, u);\n    }\n    if (this.approvals_by_id) {\n      const approvals = {};\n      approvals[tmp_owner_id] = 1n;\n      this.approvals_by_id.set(tmp_token_id, approvals);\n    }\n    if (this.next_approval_id_by_id) {\n      this.next_approval_id_by_id.set(tmp_token_id, 1n);\n    }\n\n    // 2. see how much space it took\n    this.extra_storage_in_bytes_per_token =\n      near.storageUsage() - initial_storage_usage;\n\n    // 3. roll it all back\n    if (this.next_approval_id_by_id) {\n      this.next_approval_id_by_id.remove(tmp_token_id);\n    }\n    if (this.approvals_by_id) {\n      this.approvals_by_id.remove(tmp_token_id);\n    }\n    if (this.tokens_per_owner) {\n      const u = this.tokens_per_owner.remove(tmp_owner_id, {\n        reconstructor: UnorderedSet.reconstruct,\n      });\n      u.remove(tmp_token_id);\n    }\n    if (this.token_metadata_by_id) {\n      this.token_metadata_by_id.remove(tmp_token_id);\n    }\n    this.owner_by_id.remove(tmp_token_id);\n  }\n\n  internal_transfer_unguarded(\n    token_id: TokenId,\n    from: AccountId,\n    to: AccountId\n  ) {\n    this.owner_by_id.set(token_id, to);\n\n    if (this.tokens_per_owner) {\n      const owner_tokens_set = this.tokens_per_owner.get(from, {\n        reconstructor: UnorderedSet.reconstruct,\n      });\n      if (owner_tokens_set == null) {\n        throw new Error(\"Unable to access tokens per owner in unguarded call.\");\n      }\n      owner_tokens_set.remove(token_id);\n      if (owner_tokens_set.isEmpty()) {\n        this.tokens_per_owner.remove(from);\n      } else {\n        this.tokens_per_owner.set(from, owner_tokens_set);\n      }\n\n      let receiver_tokens_set = this.tokens_per_owner.get(to, {\n        reconstructor: UnorderedSet.reconstruct,\n      });\n      if (receiver_tokens_set === null) {\n        receiver_tokens_set = new UnorderedSet<TokenId>(\n          new TokensPerOwner(near.sha256(bytes(to))).into_storage_key()\n        );\n      }\n      receiver_tokens_set.set(token_id);\n      this.tokens_per_owner.set(to, receiver_tokens_set);\n    }\n  }\n\n  internal_transfer(\n    sender_id: AccountId,\n    receiver_id: AccountId,\n    token_id: TokenId,\n    approval_id?: bigint,\n    memo?: string\n  ): [AccountId, Option<{ [approvals: AccountId]: bigint }>] {\n    const owner_id = this.owner_by_id.get(token_id);\n    if (owner_id == null) {\n      throw new Error(\"Token not found\");\n    }\n\n    const approved_account_ids = this.approvals_by_id?.remove(token_id);\n\n    let sender_id_authorized: string | undefined;\n    if (sender_id != owner_id) {\n      if (!approved_account_ids) {\n        throw new Error(\"Unauthorized\");\n      }\n\n      const actual_approval_id = approved_account_ids[sender_id];\n      if (!actual_approval_id) {\n        throw new Error(\"Sender not approved\");\n      }\n\n      assert(\n        approval_id === undefined || approval_id == actual_approval_id,\n        `The actual approval_id ${actual_approval_id} is different from the given ${approval_id}`\n      );\n      sender_id_authorized = sender_id;\n    } else {\n      sender_id_authorized = undefined;\n    }\n    assert(owner_id != receiver_id, \"Current and next owner must differ\");\n    this.internal_transfer_unguarded(token_id, owner_id, receiver_id);\n    NonFungibleToken.emit_transfer(\n      owner_id,\n      receiver_id,\n      token_id,\n      sender_id_authorized,\n      memo\n    );\n    return [owner_id, approved_account_ids];\n  }\n\n  static emit_transfer(\n    owner_id: AccountId,\n    receiver_id: AccountId,\n    token_id: TokenId,\n    sender_id?: AccountId,\n    memo?: string\n  ) {\n    new NftTransfer(\n      owner_id,\n      receiver_id,\n      [token_id],\n      sender_id && sender_id == owner_id ? sender_id : undefined,\n      memo\n    ).emit();\n  }\n\n  internal_mint(\n    token_id: TokenId,\n    token_owner_id: AccountId,\n    token_metadata?: TokenMetadata\n  ): Token {\n    const token = this.internal_mint_with_refund(\n      token_id,\n      token_owner_id,\n      token_metadata,\n      near.predecessorAccountId()\n    );\n    new NftMint(token.owner_id, [token.token_id]).emit();\n    return token;\n  }\n\n  internal_mint_with_refund(\n    token_id: TokenId,\n    token_owner_id: AccountId,\n    token_metadata?: TokenMetadata,\n    refund_id?: string\n  ): Token {\n    let initial_storage_usage: Option<[string, bigint]> = null;\n    if (refund_id) {\n      initial_storage_usage = [refund_id, near.storageUsage()];\n    }\n    if (this.token_metadata_by_id && token_metadata === undefined) {\n      throw new Error(\"Must provide metadata\");\n    }\n    if (this.owner_by_id.get(token_id)) {\n      throw new Error(\"token_id must be unique\");\n    }\n\n    const owner_id = token_owner_id;\n    this.owner_by_id.set(token_id, owner_id);\n    this.token_metadata_by_id?.set(token_id, token_metadata);\n    if (this.tokens_per_owner) {\n      let token_ids = this.tokens_per_owner.get(owner_id, {\n        reconstructor: UnorderedSet.reconstruct,\n      });\n      if (token_ids === null) {\n        token_ids = new UnorderedSet(\n            new TokensPerOwner(near.sha256(bytes(owner_id))).into_storage_key()\n        );\n      }\n      token_ids.set(token_id);\n      this.tokens_per_owner.set(owner_id, token_ids);\n    }\n\n    const approved_account_ids = this.approvals_by_id ? {} : undefined;\n    if (initial_storage_usage) {\n      const [id, storage_usage] = initial_storage_usage;\n      refund_deposit_to_account(near.storageUsage() - storage_usage, id);\n    }\n    return new Token(token_id, owner_id, token_metadata, approved_account_ids);\n  }\n\n  nft_transfer({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n  }: {\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approval_id?: bigint;\n    memo?: string;\n  }) {\n    assert_at_least_one_yocto();\n    const sender_id = near.predecessorAccountId();\n    this.internal_transfer(sender_id, receiver_id, token_id, approval_id, memo);\n  }\n\n  nft_transfer_call({\n    receiver_id,\n    token_id,\n    approval_id,\n    memo,\n    msg,\n  }: {\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approval_id?: bigint;\n    memo?: string;\n    msg: string;\n  }) {\n    assert_at_least_one_yocto();\n    assert(\n      near.prepaidGas() > GAS_FOR_NFT_TRANSFER_CALL,\n      \"Not enough prepaid gas\"\n    );\n    const sender_id = near.predecessorAccountId();\n    const [previous_owner_id, approved_account_ids] = this.internal_transfer(\n      sender_id,\n      receiver_id,\n      token_id,\n      approval_id,\n      memo\n    );\n\n    const promise = NearPromise.new(receiver_id)\n      .functionCall(\n        \"nft_on_transfer\",\n        JSON.stringify({ sender_id, previous_owner_id, token_id, msg }),\n        0n,\n        near.prepaidGas() - GAS_FOR_NFT_TRANSFER_CALL\n      )\n      .then(\n        NearPromise.new(near.currentAccountId()).functionCall(\n          \"nft_resolve_transfer\",\n            JSON.stringify({\n              previous_owner_id,\n              receiver_id,\n              token_id,\n              approved_account_ids,\n            }),\n          0n,\n          GAS_FOR_RESOLVE_TRANSFER\n        )\n      );\n    return promise;\n  }\n\n  nft_token({ token_id }: { token_id: TokenId }): Option<Token> {\n    const owner_id = this.owner_by_id.get(token_id);\n    if (owner_id == null) {\n      return null;\n    }\n    const metadata = this.token_metadata_by_id?.get(token_id, {\n      reconstructor: TokenMetadata.reconstruct,\n    });\n    const approved_account_ids = this.approvals_by_id?.get(token_id) as Option<{\n      [approvals: AccountId]: bigint;\n    }>;\n    return new Token(token_id, owner_id, metadata, approved_account_ids);\n  }\n\n  nft_resolve_transfer({\n    previous_owner_id,\n    receiver_id,\n    token_id,\n    approved_account_ids,\n  }: {\n    previous_owner_id: AccountId;\n    receiver_id: AccountId;\n    token_id: TokenId;\n    approved_account_ids?: { [approvals: AccountId]: bigint };\n  }): boolean {\n    let must_revert = false;\n    let p: string;\n    try {\n      p = near.promiseResult(0);\n    } catch (e) {\n      if (e.message.includes(\"Not Ready\")) {\n        throw new Error();\n      } else {\n        must_revert = true;\n      }\n    }\n    if (!must_revert) {\n      try {\n        const yes_or_no = JSON.parse(p);\n        if (typeof yes_or_no == \"boolean\") {\n          must_revert = yes_or_no;\n        } else {\n          must_revert = true;\n        }\n      } catch (_e) {\n        must_revert = true;\n      }\n    }\n\n    if (!must_revert) {\n      return true;\n    }\n\n    const current_owner = this.owner_by_id.get(token_id) as Option<AccountId>;\n    if (current_owner) {\n      if (current_owner != receiver_id) {\n        return true;\n      }\n    } else {\n      if (approved_account_ids) {\n        refund_storage_deposit(\n          previous_owner_id,\n          serialize(approved_account_ids).length\n        );\n      }\n      return true;\n    }\n\n    this.internal_transfer_unguarded(token_id, receiver_id, previous_owner_id);\n\n    if (this.approvals_by_id) {\n      const receiver_approvals = this.approvals_by_id.get(token_id);\n      if (receiver_approvals) {\n        refund_storage_deposit(\n          receiver_id,\n          serialize(receiver_approvals).length\n        );\n      }\n      if (approved_account_ids) {\n        this.approvals_by_id.set(token_id, approved_account_ids);\n      }\n    }\n    NonFungibleToken.emit_transfer(\n      receiver_id,\n      previous_owner_id,\n      token_id,\n      null,\n      null\n    );\n    return false;\n  }\n}\n\nexport type StorageKey = TokensPerOwner | TokenPerOwnerInner;\n\nexport class TokensPerOwner implements IntoStorageKey {\n  constructor(public account_hash: Uint8Array) {}\n\n  into_storage_key(): string {\n    return \"\\x00\" + str(this.account_hash);\n  }\n}\n\nexport class TokenPerOwnerInner implements IntoStorageKey {\n  constructor(public account_id_hash: Uint8Array) {}\n\n  into_storage_key(): string {\n    return \"\\x01\" + str(this.account_id_hash);\n  }\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/index.ts",
    "content": "/** The [approval management standard](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement.html) for NFTs. */\nexport * from \"./approval\";\n\n/** The [core non-fungible token standard](https://nomicon.io/Standards/NonFungibleToken/Core.html). This can be though of as the base standard, with the others being extension standards. */\nexport * from \"./core\";\n\n/** Interface for the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Enumeration.html).\n * This provides useful view-only methods returning token supply, tokens by owner, etc.\n */\nexport * from \"./enumeration\";\n\nexport * from \"./events\";\nexport * from \"./impl\";\n\n/** Metadata interfaces and implementation according to the [NFT enumeration standard](https://nomicon.io/Standards/NonFungibleToken/Metadata.html).\n * This covers both the contract metadata and the individual token metadata.\n */\nexport * from \"./metadata\";\n\n/** The Token struct for the non-fungible token. */\nexport * from \"./token\";\n\n/** NFT utility functions */\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/metadata.ts",
    "content": "import { assert } from \"near-sdk-js\";\nimport { Option } from \"./utils\";\n\n/** This spec can be treated like a version of the standard. */\nexport const NFT_METADATA_SPEC = \"nft-1.0.0\";\n\n/** Metadata for the NFT contract itself. */\nexport class NFTContractMetadata {\n  public spec: string; // required, essentially a version like \"nft-1.0.0\"\n  public name: string; // required, ex. \"Mosaics\"\n  public symbol: string; // required, ex. \"MOSIAC\"\n  public icon: Option<string>; // Data URL\n  public base_uri: Option<string>; // Centralized gateway known to have reliable access to decentralized storage assets referenced by `reference` or `media` URLs\n  public reference: Option<string>; // URL to a JSON file with more info\n  public reference_hash: Option<string>; // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.\n\n  constructor() {\n    this.spec = NFT_METADATA_SPEC;\n    this.name = \"\";\n    this.symbol = \"\";\n    this.icon = null;\n    this.base_uri = null;\n    this.reference = null;\n    this.reference_hash = null;\n  }\n\n  init(\n    spec: string,\n    name: string,\n    symbol: string,\n    icon: Option<string>,\n    base_uri: Option<string>,\n    reference: Option<string>,\n    reference_hash: Option<string>\n  ) {\n    this.spec = spec;\n    this.name = name;\n    this.symbol = symbol;\n    this.icon = icon;\n    this.base_uri = base_uri;\n    this.reference = reference;\n    this.reference_hash = reference_hash;\n  }\n\n  assert_valid() {\n    assert(this.spec == NFT_METADATA_SPEC, \"Spec is not NFT metadata\");\n    assert(\n      (this.reference != null) == (this.reference_hash != null),\n      \"Reference and reference hash must be present\"\n    );\n    if (this.reference_hash != null) {\n      assert(this.reference_hash.length == 32, \"Hash has to be 32 bytes\");\n    }\n  }\n\n  static reconstruct(data: NFTContractMetadata): NFTContractMetadata {\n    const metadata = new NFTContractMetadata();\n    Object.assign(metadata, data);\n    return metadata;\n  }\n}\n\n/** Metadata on the individual token level. */\nexport class TokenMetadata {\n  constructor(\n    public title: Option<string>, // ex. \"Arch Nemesis: Mail Carrier\" or \"Parcel #5055\"\n    public description: Option<string>, // free-form description\n    public media: Option<string>, // URL to associated media, preferably to decentralized, content-addressed storage\n    public media_hash: Option<string>, // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.\n    public copies: Option<bigint>, // number of copies of this set of metadata in existence when token was minted.\n    public issued_at: Option<string>, // ISO 8601 datetime when token was issued or minted\n    public expires_at: Option<string>, // ISO 8601 datetime when token expires\n    public starts_at: Option<string>, // ISO 8601 datetime when token starts being valid\n    public updated_at: Option<string>, // ISO 8601 datetime when token was last updated\n    public extra: Option<string>, // anything extra the NFT wants to store on-chain. Can be stringified JSON.\n    public reference: Option<string>, // URL to an off-chain JSON file with more info.\n    public reference_hash: Option<string> // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.\n  ) {}\n\n  assert_valid() {\n    assert(\n      (this.media != null) == (this.media_hash != null),\n      \"Media and media hash must be present\"\n    );\n    if (this.media_hash != null) {\n      assert(this.media_hash.length == 32, \"Media hash has to be 32 bytes\");\n    }\n\n    assert(\n      (this.reference != null) == (this.reference_hash != null),\n      \"Reference and reference hash must be present\"\n    );\n    if (this.reference_hash != null) {\n      assert(\n        this.reference_hash.length == 32,\n        \"Reference hash has to be 32 bytes\"\n      );\n    }\n  }\n\n  static reconstruct(data: TokenMetadata): TokenMetadata {\n    return new TokenMetadata(\n      data.title,\n      data.description,\n      data.media,\n      data.media_hash,\n      data.copies,\n      data.issued_at,\n      data.expires_at,\n      data.starts_at,\n      data.updated_at,\n      data.extra,\n      data.reference,\n      data.reference_hash\n    );\n  }\n}\n\n/** Offers details on the contract-level metadata. */\nexport interface NonFungibleTokenMetadataProvider {\n  nft_metadata(): NFTContractMetadata;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/token.ts",
    "content": "import { TokenMetadata } from \"./metadata\";\nimport { AccountId } from \"near-sdk-js\";\n\n/** Note that token IDs for NFTs are strings on NEAR. It's still fine to use auto incrementing numbers as unique IDs if desired, but they should be stringified. This is to make IDs more future-proof as chain-agnostic conventions and standards arise, and allows for more flexibility with considerations like bridging NFTs across chains, etc. */\nexport type TokenId = string;\n\n/** In this implementation, the Token struct takes two extensions standards (metadata and approval) as optional fields, as they are frequently used in modern NFTs. */\nexport class Token {\n  constructor(\n    public token_id: TokenId,\n    public owner_id: AccountId,\n    public metadata?: TokenMetadata,\n    public approved_account_ids?: {\n      [approved_account_id: AccountId]: bigint;\n    }\n  ) {}\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/non_fungible_token/utils.ts",
    "content": "import { near, assert, AccountId, bytes } from \"near-sdk-js\";\n\nexport function refund_storage_deposit(\n  account_id: AccountId,\n  storage_released: number\n): void {\n  const promise_id = near.promiseBatchCreate(account_id);\n  near.promiseBatchActionTransfer(\n    promise_id,\n    BigInt(storage_released) * near.storageByteCost()\n  );\n  near.promiseReturn(promise_id);\n}\n\nexport function refund_deposit_to_account(\n  storage_used: bigint,\n  account_id: AccountId\n): void {\n  const required_cost = near.storageByteCost() * storage_used;\n  const attached_deposit = near.attachedDeposit();\n\n  assert(\n    required_cost <= attached_deposit,\n    `Must attach ${required_cost} yoctoNEAR to cover storage`\n  );\n\n  const refund = attached_deposit - required_cost;\n  if (refund > 1n) {\n    const promise_id = near.promiseBatchCreate(account_id);\n    near.promiseBatchActionTransfer(promise_id, refund);\n    near.promiseReturn(promise_id);\n  }\n}\n\n/** Assumes that the predecessor will be refunded */\nexport function refund_deposit(storage_used: bigint): void {\n  refund_deposit_to_account(storage_used, near.predecessorAccountId());\n}\n\nexport function hash_account_id(account_id: AccountId): Uint8Array {\n  return near.sha256(bytes(account_id));\n}\n\n/** Assert that at least 1 yoctoNEAR was attached. */\nexport function assert_at_least_one_yocto(): void {\n  assert(\n    near.attachedDeposit() >= 1n,\n    \"Requires attached deposit of at least 1 yoctoNEAR\"\n  );\n}\n\n/** Assert that exactly 1 yoctoNEAR was attached */\nexport function assert_one_yocto(): void {\n  assert(\n    near.attachedDeposit() === 1n,\n    \"Requires attached deposit of 1 yoctoNEAR\"\n  );\n}\n\nexport type Option<T> = T | null;\n"
  },
  {
    "path": "packages/near-contract-standards/src/storage_management/index.ts",
    "content": "import { AccountId, Balance } from \"near-sdk-js\"\nimport { Option } from \"../non_fungible_token/utils\";\n\nexport class StorageBalance {\n    total: Balance;\n    available: Balance;\n\n    constructor(total: Balance, available: Balance) {\n        this.total = total;\n        this.available = available;\n    }\n}\n\nexport class StorageBalanceBounds {\n    constructor(min: Balance, max: Option<Balance>) {\n        this.min = min;\n        this.max = max;\n    }\n\n    min: Balance;\n    max: Option<Balance>;\n}\n\nexport interface StorageManagement {\n    /**\n     * @param registration_only if `true` MUST refund above the minimum balance if the account didn't exist and\n     *   refund full deposit if the account exists.\n     */\n    storage_deposit(\n        {\n            account_id,\n            registration_only\n        }: {\n            account_id: Option<AccountId>,\n            registration_only: Option<boolean>,\n        }\n    ): StorageBalance;\n\n    /** Withdraw specified amount of available Ⓝ for predecessor account.\n    *\n    * This method is safe to call. It MUST NOT remove data.\n    *\n    * @param amount is sent as a string representing an unsigned 128-bit integer. If\n    * omitted, contract MUST refund full `available` balance. If `amount` exceeds\n    * predecessor account's available balance, contract MUST panic.\n    *\n    * If predecessor account not registered, contract MUST panic.\n    *\n    * MUST require exactly 1 yoctoNEAR attached balance to prevent restricted\n    * function-call access-key call (UX wallet security)\n    *\n    * @returns the StorageBalance structure showing updated balances.\n    */\n    storage_withdraw({ amount }: { amount?: bigint }): StorageBalance;\n\n    /** Unregisters the predecessor account and returns the storage NEAR deposit back.\n    *\n    * If the predecessor account is not registered, the function MUST return `false` without panic.\n    *\n    * @param force If `force=true` the function SHOULD ignore account balances (burn them) and close the account.\n    * Otherwise, MUST panic if caller has a positive registered balance (eg token holdings) or\n    *     the contract doesn't support force unregistration.\n    * MUST require exactly 1 yoctoNEAR attached balance to prevent restricted function-call access-key call\n    * (UX wallet security)\n    * @returns `true` if the account was unregistered, `false` if account was not registered before.\n    */\n    storage_unregister({ force }: { force: Option<boolean> }): boolean;\n\n    storage_balance_bounds(): StorageBalanceBounds;\n\n    storage_balance_of({ account_id }: { account_id: AccountId }): Option<StorageBalance>;\n}\n"
  },
  {
    "path": "packages/near-contract-standards/src/util.ts",
    "content": "export const toSnakeCase = (str: string) => {\n  return str.replace(/[A-Z]/g, (letter, index) => { return index == 0 ? letter.toLowerCase() : '_'+ letter.toLowerCase();});\n}"
  },
  {
    "path": "packages/near-contract-standards/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"esModuleInterop\": true,\n    \"lib\": [\"es2015\", \"esnext\", \"dom\"],\n    \"module\": \"esnext\",\n    \"target\": \"es2020\",\n    \"moduleResolution\": \"node\",\n    \"alwaysStrict\": true,\n    \"outDir\": \"./lib\",\n    \"declaration\": true,\n    \"preserveSymlinks\": true,\n    \"preserveWatchOutput\": true,\n    \"pretty\": false,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noImplicitAny\": false,\n    \"noImplicitReturns\": true,\n    \"noUnusedLocals\": true,\n    \"experimentalDecorators\": true,\n    \"resolveJsonModule\": true,\n    \"allowJs\": true,\n    \"skipLibCheck\": true\n  },\n  \"files\": [\n    \"src/index.ts\",\n  ],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "packages/near-sdk-js/.eslintrc.cjs",
    "content": "/** @type {import('eslint').Linter.Config} */\nmodule.exports = {\n  root: true,\n  env: {\n    es2021: true,\n    node: true,\n  },\n  overrides: [\n    {\n      files: [\"./**/*.ts\", \"./**/*.js\"],\n      extends: [\n        \"eslint:recommended\",\n        \"plugin:@typescript-eslint/recommended\",\n        \"prettier\",\n      ],\n      parser: \"@typescript-eslint/parser\",\n      parserOptions: {\n        ecmaVersion: \"latest\",\n        sourceType: \"module\",\n        project: [\"./{t,j}sconfig.json\", \"./**/{t,j}sconfig.json\"],\n      },\n      plugins: [\"@typescript-eslint\"],\n      rules: {\n        \"@typescript-eslint/no-unused-vars\": [\n          \"warn\",\n          {\n            varsIgnorePattern: \"^_\",\n            argsIgnorePattern: \"^_\",\n            destructuredArrayIgnorePattern: \"^_\",\n            caughtErrorsIgnorePattern: \"^_\",\n          },\n        ],\n      },\n    },\n  ],\n  ignorePatterns: [\n    \"pnpm-lock.yaml\",\n    \"./**/node_modules\",\n    \"node_modules\",\n    \"./**/lib\",\n    \"lib\",\n    \"./**/build\",\n    \"build\",\n    \"./**/deps\",\n    \"deps\",\n  ],\n  rules: {},\n};\n"
  },
  {
    "path": "packages/near-sdk-js/.prettierignore",
    "content": "deps\nbuild\nnode_modules\nlib\ncli\npnpm-lock.yaml\n\n"
  },
  {
    "path": "packages/near-sdk-js/README.md",
    "content": "# NEAR JavaScript SDK\n\n## Quick Start\n\nUse [`create-near-app`](https://github.com/near/create-near-app) to quickly get started writing smart contracts in JavaScript on NEAR.\n\n    npx create-near-app\n\nThis will scaffold a basic template for you 😎\n\nLearn more in our [Quick Start guide](https://docs.near.org/develop/quickstart-guide).\n\n## Running Examples\n\nThere are a couple of contract examples in the project:\n\n- [Clean contract state](https://github.com/near/near-sdk-js/tree/develop/examples/src/clean-state.js)\n- [Counter using low level API](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter-lowlevel.js)\n- [Counter in JavaScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter.js)\n- [Counter in TypeScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter/counter.ts)\n- [Doing cross contract call](https://github.com/near/near-sdk-js/tree/develop/examples/src//cross-contract-calls/cross-contract-call.js)\n- [Fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token/fungible-token.js)\n- [Lockable fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token/fungible-token-lockable.js)\n- [Non fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token/non-fungible-token.js)\n- [Non fungible token receiver contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token/non-fungible-token-receiver.js)\n- [Status message board](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message/status-message.js)\n- [Status message board with unique messages](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message/status-message-collections.js)\n- [Programmatic Update After Locking The Contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/programmatic-updates/programmatic-update.js)\n\nTo build all examples, run `pnpm build` in `examples/`. To test all examples, run `pnpm test`. You can also build and test one specific example with `pnpm build:<example-name>` and `pnpm test:<example-name>`, see `examples/package.json`.\n\nTo deploy and call a contract on a NEAR node, use near-cli's `near deploy` and `near call`.\n\n## Test\n\nWe recommend to use near-workspaces to write tests for your smart contracts. See any of the examples for how tests are setup and written.\n\n## Error Handling in NEAR-SDK-JS\n\nIf you want to indicate an error happened and fail the transaction, just throw an error object in JavaScript. The compiled JavaScript contract includes error handling capability. It will catch throwed errors and automatically invoke `panic_utf8` with `\"{error.message}\\n:{error.stack}\"`. As a result, transaction will fail with `\"Smart contract panicked: {error.message}\\n{error.stack}\"` error message. You can also use an error utilities library to organize your errors, such as verror.\n\nWhen your JS code or library throws an error, uncaught, the transaction will also fail with GuestPanic error, with the error message and stacktrace.\n\nWhen call host function with inappropriate type, means incorrect number of arguments or arg is not expected type:\n\n- if arguments less than params, remaining argument are set as 'undefined'\n- if arguments more than params, remaining argument are ignored\n- if argument is different than the required type, it'll be coerced to required type\n- if argument is different than the required type but cannot be coerced, will throw runtime type error, also with message and stacktrace\n\n## Migrating from near-sdk-js 0.6.0\n\nIf you have a near-sdk-js 0.6.0 contract, you need to drop the `babel.config.json` because it is now inlined in near-sdk-js CLI.\n\nAlso `Bytes` type in 0.6.0 is replaced with `string` and `Uint8Array`. Because `Bytes` was an alias to `string`, this doesn't affect all collection APIs and most low level APIs. Some low level APIs below now also comes with a raw version, which ends with `Raw` and takes `Uint8Array` instead of `string`, for example, `storageRead` vs `storageReadRaw`. Some low level APIs have more sense to use `Uint8Array` instead of `string`, such as `sha256` and arguments for a function call type of promise, these are **BREAKING** changes. Please refer to next section for details: look for functions with `Uint8Array` argument and return types.\n\n## NEAR-SDK-JS API Reference\n\nAll NEAR blockchain provided functionality (host functions) are defined in `src/api.ts` and exported as `near`. You can use them by:\n\n```js\nimport { near } from \"near-sdk-js\";\n\n// near.<api documented below>. e.g.:\nlet signer = near.signerAccountId();\n```\n\n### About Type\n\nNEAR-SDK-JS is written in TypeScript, so every API function has a type specified by signature that looks familiar to JavaScript/TypeScript Developers. Two types in the signature need a special attention:\n\n- Most of the API take `bigint` instead of Number as type. This because JavaScript Number cannot hold 64 bit and 128 bit integer without losing precision.\n- For those API that takes or returns raw bytes, it is a JavaScript `Uint8Array`. You can use standard `Uint8Array` methods on it or decode it to string with `decode` or `str`. The difference between `decode` and `str` is: `decode` decode the array as UTF-8 sequence. `str` simply converts each Uint8 to one char with that char code.\n\n### Context API\n\n- `currentAccountId()` -- Returns the ID of the current contract - the contract that is being executed.\n\n- `signerAccountId()` -- Returns the ID of the account that signed the transaction.\n\n- `signerAccountPk()` -- Returns the public key of the account that signed the transaction.\n\n- `predecessorAccountId()` -- Returns the ID of the account that called the function.\n\n- `inputRaw()` -- Returns the arguments passed to the current smart contract call.\n\n- `input()` -- Returns the arguments passed to the current smart contract call as utf-8 string.\n\n- `blockIndex()` -- Returns the current block index. <span style=\"color:#d9534f;\">**Deprecated**</span>\n\n- `blockHeight()` -- Returns the current block height.\n\n- `blockTimestamp()` -- Returns the current block timestamp.\n\n- `epochHeight()` -- Returns the current epoch height.\n\n- `storageUsage()` -- Returns the current accounts NEAR storage usage.\n\n### Economics API\n\n- `accountBalance()` -- Returns the current account's account balance.\n\n- `accountLockedBalance()` -- Returns the current account's locked balance.\n\n- `attachedDeposit()` -- Returns the amount of NEAR attached to this function call. Can only be called in payable functions.\n\n- `prepaidGas()` -- Returns the amount of Gas that was attached to this function call.\n\n- `usedGas()` -- Returns the amount of Gas that has been used by this function call until now.\n\n### Math API\n\n- `altBn128G1Multiexp` -- Compute alt_bn128 g1 multiexp. `alt_bn128` is a specific curve from the Barreto-Naehrig(BN) family. It is particularly well-suited for ZK proofs.\n\n- `altBn128G1Sum` - Computes sum for signed g1 group elements on alt_bn128 curve.\n\n- `altBn128PairingCheck(value: Uint8Array)` -- Computes pairing check on alt_bn128 curve.\n\n- `randomSeed()` -- Returns a random string of bytes.\n\n- `sha256(value: Uint8Array)` - Returns sha256 hash of given value.\n\n- `keccak256(value: Uint8Array)` -- Returns keccak256 hash of given value.\n\n- `keccak512(value: Uint8Array)` -- Returns keccak512 hash of given value.\n\n- `ripemd160(value: Uint8Array)` -- Returns ripemd160 hash of given value.\n\n- `ecrecover(hash: Uint8Array, sign: Uint8Array, v: bigint, malleability_flag: bigint)` -- Recovers an ECDSA signer address from a 32-byte message hash and a corresponding signature along with v recovery byte. Takes in an additional flag to check for malleability of the signature which is generally only ideal for transactions.\n\n### Miscellaneous API\n\n- `valueReturnRaw(value: Uint8Array)` -- Returns the value from the NEAR WASM virtual machine.\n\n- `valueReturn(value: string)` -- Returns the utf-8 string value from the NEAR WASM virtual machine.\n\n- `panicUtf8(msg: Uint8Array)` -- Panic the transaction execution with given message.\n\n- `logUtf8(msg: Uint8Array)` -- Log the message in transaction logs.\n\n- `logUtf16(msg: Uint8Array)` -- Log the message in transaction logs.\n\n- `log(...params: unknown[])` -- Logs parameters in the NEAR WASM virtual machine.\n\n### Promises API\n\nAsynchronous cross-contract calls allow parallel execution of multiple contracts in parallel with subsequent aggregation on another contract. env exposes the following methods:\n\n- `promiseCreate(account_id: string, method_name: string, arguments: Uint8Array, amount: bigint, gas: bigint)` -- schedules an execution of a function on some contract;\n\n- `promiseThen(promise_index: bigint, account_id: string, method_name: string, arguments: Uint8Array, amount: bigint, gas: bigint)` -- attaches the callback back to the current contract once the function is executed;\n\n- `promiseAnd(...promise_idx: bigint)` -- combinator, allows waiting on several promises simultaneously, before executing the callback\n\n- `promiseBatchCreate(account_id: string)` -- create a NEAR promise which will have multiple promise actions inside\n\n- `promiseBatchThen(promise_index: bigint, account_id: string)` -- attach a callback NEAR promise to a batch of NEAR promise actions\n\n### Promise API actions\n\n- `promiseBatchActionCreateAccount(promiseIndex: PromiseIndex)` -- Attach a create account promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionDeployContract(promiseIndex: PromiseIndex, code: Uint8Array)` -- Attach a deploy contract promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionFunctionCall(promiseIndex: PromiseIndex, methodName: string, args: string, amount: NearAmount, gas: NearAmount)` -- Attach a function call promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionFunctionCallWeight(promiseIndex: PromiseIndex, methodName: string, args: string, amount: NearAmount, gas: NearAmount, weight: GasWeight)` -- Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionTransfer(promiseIndex: PromiseIndex, amount: NearAmount);` -- Attach a transfer promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionStake(promiseIndex: PromiseIndex, amount: NearAmount, publicKey: Uint8Array)` -- Attach a stake promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionAddKeyWithFullAccess(promiseIndex: PromiseIndex, publicKey: Uint8Array, nonce: number | bigint)` -- Attach a add full access key promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionAddKeyWithFunctionCall(promiseIndex: PromiseIndex, publicKey: Uint8Array, nonce: number | bigint, allowance: NearAmount, receiverId: string, methodNames: string)` -- Attach a add access key promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionDeleteKey(promiseIndex: PromiseIndex, publicKey: Uint8Array)` -- Attach a delete key promise action to the NEAR promise index with the provided promise index.\n\n- `promiseBatchActionDeleteAccount(promiseIndex: PromiseIndex, beneficiaryId: string)` -- Attach a delete account promise action to the NEAR promise index with the provided promise index.\n\n### Promise API results\n\n- `promiseResultsCount()` -- Returns the number of promise results available.\n\n- `promiseResultRaw(promiseIndex: PromiseIndex)` -- Returns the result of the NEAR promise for the passed promise index.\n\n- `promiseResult(promiseIndex: PromiseIndex)` -- Returns the result of the NEAR promise for the passed promise index as utf-8 string.\n\n- `promiseReturn(promiseIndex: PromiseIndex)` -- Executes the promise in the NEAR WASM virtual machine.\n\n### Storage API\n\n- `storageWriteRaw(key: Uint8Array, value: Uint8Array)` -- Writes the provided bytes to NEAR storage under the provided key.\n\n- `storageReadRaw(key: Uint8Array)` -- Reads the value from NEAR storage that is stored under the provided key.\n\n- `storageRemoveRaw(key: Uint8Array)` -- Removes the value of the provided key from NEAR storage.\n\n- `storageHasKeyRaw(key: Uint8Array)` -- Checks for the existence of a value under the provided key in NEAR storage.\n\n- `storageWrite(key: string, value: string)` -- Writes the provided utf-8 string to NEAR storage under the provided key.\n\n- `storageRead(key: string)` -- Reads the utf-8 string value from NEAR storage that is stored under the provided key.\n\n- `storageRemove(key: string)` -- Removes the value of the provided utf-8 string key from NEAR storage.\n\n- `storageHasKey(key: string)` -- Checks for the existence of a value under the provided utf-8 string key in NEAR storage.\n\n### Validator API\n\n- `validatorStake(account_id: string)` -- Returns the number of staked NEAR of given validator, in yoctoNEAR.\n\n- `validatorTotalStake()` -- Returns the number of staked NEAR of all validators, in yoctoNEAR\n\n### NearBindgen and other decorators\n\nYou can write a simple smart contract by only using low-level APIs, such as `near.input()`, `near.storageRead()`, etc. In this case, the API of your contract will consist of all the exported JS functions. You can find an example of such a contract [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/counter/counter-lowlevel.js).\n\nBut if you want to build a more complex contracts with ease, you can use decorators from this SDK that will handle serialization, deserialization, and other boilerplate operations for you.\n\nIn order to do that, your contract must be a class decorated with `@NearBindgen({})`. Each method in this class with `@call({})`, `@view({})`, and `@initialize({})` decorators will become functions of your smart contract. `call` functions can change state, and `view` functions can only read it.\n\nYour class must have a `constructor()`. You will not be able to call it, which is why it should not accept any parameters. You must declare all the parameters that you are planning to use in the constructor and set default values.\n\nThe simplest example of the contract that follows all these rules can be found [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message/status-message.js)\n\n`NearBindgen` decorator can accept `requireInit parameter`.\n\n```JS\n@NearBindgen({ requireInit: true })\nclass YourContract {\n    ...\n}\n```\n\nIt is `false` by default, but if you will set it to `true`, it will prevent all the `call` functions from being executed before you initialize the state of the contract.\n\nIn order to initialize the contract, you need to add functions flagged with `@initialize({})` decorator.\n\n`@call({})` decorator can accept two parameters: `privateFunction` and `payableFunction`. They are both `false` by default.\n\n`privateFunction: true` can restrict access to this function to the contract itself.\n\n`payableFunction: true` will allow the function to accept payments (deposit). Without this flag, it will panic if any deposit was provided.\n\n### Collections\n\nA few useful on-chain persistent collections are provided. All keys, values and elements are of type `string`.\n\n#### Vector\n\nVector is an iterable implementation of vector that stores its content on the trie. Usage:\n\n```js\nimport {Vector} from 'near-sdk-js'\n\n// in contract class constructor:\nconstructor() {\n    super()\n    this.v = new Vector('my_prefix_')\n}\n\n// Override the deserializer to load vector from chain\ndeserialize() {\n    super.deserialize()\n    this.v = Object.assign(new Vector, this.v)\n}\n\nsomeMethod() {\n    // insert\n    this.v.push('abc')\n    this.v.push('def')\n    this.v.push('ghi')\n\n    // batch insert, extend:\n    this.v.extend(['xyz', '123'])\n\n    // get\n    let first = this.v.get(0)\n\n    // remove, move the last element to the given index\n    this.v.swapRemove(0)\n\n    // replace\n    this.v.replace(1, 'jkl')\n\n    // remove the last\n    this.v.pop()\n\n    // len, isEmpty\n    let len = this.v.length\n    let isEmpty = this.v.isEmpty()\n\n    // iterate\n    for (let element of this.v) {\n        near.log(element)\n    }\n\n    // toArray, convert to JavaScript Array\n    let a = this.v.toArray()\n\n    // clear\n    ths.v.clear()\n}\n```\n\n#### LookupMap\n\nLookupMap is an non-iterable implementation of a map that stores its content directly on the trie. It's like a big hash map, but on trie. Usage:\n\n```js\nimport {LookupMap} from 'near-sdk-js'\n\n// in contract class constructor:\nconstructor() {\n    super()\n    this.m = new LookupMap('prefix_a')\n}\n\n// Override the deserializer to load vector from chain\ndeserialize() {\n    super.deserialize()\n    this.m = Object.assign(new LookupMap, this.m)\n}\n\nsomeMethod() {\n    // insert\n    this.m.set('abc', 'aaa')\n    this.m.set('def', 'bbb')\n    this.m.set('ghi', 'ccc')\n\n    // batch insert, extend:\n    this.m.extend([['xyz', '123'], ['key2', 'value2']])\n\n    // check exist\n    let exist = this.m.containsKey('abc')\n\n    // get\n    let value = this.m.get('abc')\n\n    // remove\n    this.m.remove('def')\n\n    // replace\n    this.m.set('ghi', 'ddd')\n}\n```\n\n#### LookupSet\n\nLookupSet is an non-iterable implementation of a set that stores its content directly on the trie. It's like LookupMap, but it only stores whether the value presents. Usage:\n\n```js\nimport {LookupSet} from 'near-sdk-js'\n\n// in contract class constructor:\nconstructor() {\n    super()\n    this.s = new LookupSet('prefix_b')\n}\n\n// Override the deserializer to load vector from chain\ndeserialize() {\n    super.deserialize()\n    this.s = Object.assign(new LookupSet, this.s)\n}\n\nsomeMethod() {\n    // insert\n    this.s.set('abc')\n    this.s.set('def')\n    this.s.set('ghi')\n\n    // batch insert, extend:\n    this.s.extend(['xyz', '123'])\n\n    // check exist\n    let exist = this.s.contains('abc')\n\n    // remove\n    this.s.remove('def')\n}\n```\n\n#### UnorderedMap\n\nUnorderedMap is an iterable implementation of a map that stores its content directly on the trie. Usage:\n\n```js\nimport {UnorderedMap} from 'near-sdk-js'\n\n// in contract class constructor:\nconstructor() {\n    super()\n    this.m = new UnorderedMap('prefix_c')\n}\n\n// Override the deserializer to load vector from chain\ndeserialize() {\n    super.deserialize()\n    this.m.keys = Object.assign(new Vector, this.m.keys)\n    this.m.values = Object.assign(new Vector, this.m.values)\n    this.m = Object.assign(new UnorderedMap, this.m)\n}\n\nsomeMethod() {\n    // insert\n    this.m.set('abc', 'aaa')\n    this.m.set('def', 'bbb')\n    this.m.set('ghi', 'ccc')\n\n    // batch insert, extend:\n    this.m.extend([['xyz', '123'], ['key2', 'value2']])\n\n    // get\n    let value = this.m.get('abc')\n\n    // remove\n    this.m.remove('def')\n\n    // replace\n    this.m.set('ghi', 'ddd')\n\n    // len, isEmpty\n    let len = this.m.length\n    let isEmpty = this.m.isEmpty()\n\n    // iterate\n    for (let [k, v] of this.m) {\n        near.log(k+v)\n    }\n\n    // toArray, convert to JavaScript Array\n    let a = this.m.toArray()\n\n    // clear\n    this.m.clear()\n}\n```\n\n#### UnorderedSet\n\nUnorderedSet is an iterable implementation of a set that stores its content directly on the trie. It's like UnorderedMap but it only stores whether the value presents. Usage:\n\n```js\nimport {UnorderedSet} from 'near-sdk-js'\n\n// in contract class constructor:\nconstructor() {\n    super()\n    this.s = new UnorderedSet('prefix_d')\n}\n\n// Override the deserializer to load vector from chain\ndeserialize() {\n    super.deserialize()\n    this.s.elements = Object.assign(new Vector, this.s.elements)\n    this.s = Object.assign(new UnorderedSet, this.s)\n}\n\nsomeMethod() {\n    // insert\n    this.s.set('abc')\n    this.s.set('def')\n    this.s.set('ghi')\n\n    // batch insert, extend:\n    this.s.extend(['xyz', '123'])\n\n    // check exist\n    let exist = this.s.contains('abc')\n\n    // remove\n    this.s.remove('def')\n\n    // len, isEmpty\n    let len = this.s.length\n    let isEmpty = this.s.isEmpty()\n\n    // iterate\n    for (let e of this.s) {\n        near.log(e)\n    }\n\n    // toArray, convert to JavaScript Array\n    let a = this.s.toArray()\n\n    // clear\n    this.s.clear()\n}\n```\n\n### High level Promise APIs\n\nWithin a contract class that decorated by `@Nearbindgen`, you can work a high level JavaScript class, called `NearPromise`. It's equivalently expressive as promise batch APIs but much shorter to write and can be chained like a JavaScript Promise.\n\nIn a `@call` method, you can return either a JavaScript value or a `NearPromise` object. In the later case, `@NearBindgen` will automatically `promiseReturn` it for you.\n\nUsage:\n\n```js\n// create new promise\nimport { NearPromise, near, includeBytes } from \"near-sdk-js\";\nimport { PublicKey } from \"near-sdk-js/lib/types\";\n\nlet promise = NearPromise.new(\"account-to-run-promise\");\n\n// possible promise actions, choose and chain what you need:\npromise\n  .createAccount()\n  .transfer(1_000_000_000_000_000_000_000_000_000_000_000_000n)\n  .addFullAccessKey(new PublicKey(near.signerAccountPk()))\n  .addAccessKey(\n    new PublicKey(near.signerAccountPk()),\n    250000000000000000000000n, // allowance\n    \"receiver_account_id\",\n    \"allowed_function_names\"\n  )\n  .stake(100000000000000000000000000000n, new PublicKey(near.signerAccountPk()))\n  .deployContract(includeBytes(\"path/to/contract.wasm\"))\n  .functionCall(\n    \"callee_contract_account_id\",\n    inputArgs,\n    0, // amount\n    2 * Math.pow(10, 13) // gas\n  )\n  .functionCallWeight(\n    \"callee_contract_account_id\",\n    inputArgs,\n    0, // amount\n    2 * Math.pow(10, 13), // gas\n    1 // weight\n  )\n  .deleteKey(new PublicKey(near.signerAccountPk()))\n  .deleteAccount(\"beneficial_account_id\");\n\nreturn promise;\n```\n\nIn the case of deploy contract, `includeBytes` is a helpful build-time util. You can include the content of a wasm contract, by using `includeBytes('path/to/contract.wasm')`.\n\nIn the case of `addFullAccessKey`, `addAccessKey` and `stake`, it takes a `PublicKey` object, you can find more details about it in the Types sections below.\n\nBesides above APIs to build something on top of an API, you can also chain promises with `.then` and `.and`, they're equivalent to promiseThen, promiseAnd:\n\n```js\n// assume promise, promise2 and promise3 are create with above APIs, with several actions added like above.\npromise.and(promise2).then(promise3); // promiseAnd of [promise_id, promise2_id], then promiseThen(promise_and_id, promise3_id)\n\nreturn promise;\n```\n\n### Types\n\nNEAR-SDK-JS also includes type definitions that are equivalent to that in Rust SDK / nearcore. You can browse them in near-sdk-js/src/types. Most of them are just type alias to string and bigint.\n\n#### Public Key\n\nPublic Key is representing a NEAR account's public key in a JavaScript class. You can either initiate a Public Key from binary data, or from a human readable string.\n\nThe binary data is in the same format as nearcore in `Uint8Array`. That's one byte to represent the curve type of the public key, either ed25519 (`0x0`), or secp256k1 (`0x1`), follows by the curve-specific public key data in bytes. Examples:\n\n```js\nnew PublicKey(near.signerAccountPk());\nlet pk = new PublicKey(\n  new Uint8Array([\n    // CurveType.ED25519 = 0\n    0,\n    // ED25519 PublicKey data\n    186, 44, 216, 49, 157, 48, 151, 47, 23, 244, 137, 69, 78, 150, 54, 42, 30, 248,\n    110, 26, 205, 18, 137, 154, 10, 208, 26, 183, 65, 166, 223, 18,\n  ])\n);\nlet pk = new PublicKey(\n  new Uint8Array([\n    // CurveType.SECP256K1 = 1\n    1,\n    // SECP256K1 PublicKey data\n    242, 86, 198, 230, 200, 11, 33, 63, 42, 160, 176, 23, 68, 35, 93, 81, 92, 89,\n    68, 53, 190, 101, 27, 21, 136, 58, 16, 221, 71, 47, 166, 70, 206, 98, 234, 243,\n    103, 13, 197, 203, 145, 0, 160, 202, 42, 85, 178, 193, 71, 193, 233, 163, 140,\n    228, 40, 135, 142, 125, 70, 225, 251, 113, 74, 153,\n  ])\n);\n```\n\nThe human readable form is `ed25519:` or `secp256k1:` following base58-encoded public key. And initialize the Public Key with `PublicKey.fromString`:\n\n```js\nPublicKey.fromString('ed25519:DXkVZkHd7WUUejCK7i74uAoZWy1w9AZqshhTHxhmqHuB`)\nPublicKey.fromString('secp256k1:5r22SrjrDvgY3wdQsnjgxkeAbU1VcM71FYvALEQWihjM3Xk4Be1CpETTqFccChQr4iJwDroSDVmgaWZv2AcXvYeL`)\n```\n\nOnce a PublicKey object is created, it can be used in high level promise APIs that takes a public key, such as `addFullAccessKey`, `addAccessKey` and `stake`.\n\n## How to use NEAR SDK JS on Windows\n\nYou can develop smart contracts on Windows using Windows Subsystem for Linux (WSL2).\nIn order to use WSL2, follow the next steps:\n\n- Run `PowerShell` as Administrator\n- Execute `wsl --install` to install Ubuntu and do additional setup automatically. Check more details [here](https://learn.microsoft.com/en-us/windows/wsl/install)\n- Restart your machine\n- `WSL2` will continue setup process on start. Setup your username and password when prompted.\n- Check [this](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) guide to setup `npm`, `node`, `npx`, `VSCode` and other tools of your choice in order to start developing.\n\nIn case of any issues of setting up WSL2 make sure that:\n\n- Your Windows OS is up to date\n- Virtualization is turned on in BIOS\n- `Windows Subsystem for Linux` and `Virtual Machine Platform` are turned on in `Windows Features` (Start -> Search -> Turn Windows Feature On or Off)\n"
  },
  {
    "path": "packages/near-sdk-js/builder/builder.c",
    "content": "#include <string.h>\r\n#include \"../node_modules/near-sdk-js/lib/cli/deps/quickjs/quickjs-libc-min.h\"\r\n#include \"../node_modules/near-sdk-js/lib/cli/deps/quickjs/libbf.h\"\r\n#include \"code.h\"\r\n\r\nstatic JSContext *JS_NewCustomContext(JSRuntime *rt)\r\n{\r\n  JSContext *ctx = JS_NewContextRaw(rt);\r\n  if (!ctx)\r\n    return NULL;\r\n  JS_AddIntrinsicBaseObjects(ctx);\r\n  JS_AddIntrinsicDate(ctx);\r\n  JS_AddIntrinsicEval(ctx);\r\n  JS_AddIntrinsicStringNormalize(ctx);\r\n  JS_AddIntrinsicRegExp(ctx);\r\n  JS_AddIntrinsicJSON(ctx);\r\n  JS_AddIntrinsicProxy(ctx);\r\n  JS_AddIntrinsicMapSet(ctx);\r\n  JS_AddIntrinsicTypedArrays(ctx);\r\n  JS_AddIntrinsicPromise(ctx);\r\n  JS_AddIntrinsicBigInt(ctx);\r\n  return ctx;\r\n}\r\n\r\n#define DEFINE_NEAR_METHOD(name) \\\r\n  void name () __attribute__((export_name(#name))) {\\\r\n    JSRuntime *rt;\\\r\n    JSContext *ctx;\\\r\n    JSValue mod_obj, fun_obj, result, error, error_message, error_stack;\\\r\n    const char *error_message_c, *error_stack_c;\\\r\n    char *error_c;\\\r\n    size_t msg_len, stack_len;\\\r\n    rt = JS_NewRuntime();\\\r\n    ctx = JS_NewCustomContext(rt);\\\r\n    js_add_near_host_functions(ctx);\\\r\n    mod_obj = js_load_module_binary(ctx, code, code_size);\\\r\n    fun_obj = JS_GetProperty(ctx, mod_obj, JS_NewAtom(ctx, #name));\\\r\n    result = JS_Call(ctx, fun_obj, mod_obj, 0, NULL);\\\r\n    if (JS_IsException(result)) {\\\r\n      error = JS_GetException(ctx);\\\r\n      error_message = JS_GetPropertyStr(ctx, error, \"message\");\\\r\n      error_stack = JS_GetPropertyStr(ctx, error, \"stack\");\\\r\n      error_message_c = JS_ToCStringLen(ctx, &msg_len, error_message);\\\r\n      error_stack_c = JS_ToCStringLen(ctx, &stack_len, error_stack);\\\r\n      error_c = malloc(msg_len+1+stack_len);\\\r\n      strncpy(error_c, error_message_c, msg_len);\\\r\n      error_c[msg_len] = '\\n';\\\r\n      strncpy(error_c+msg_len+1, error_stack_c, stack_len);\\\r\n      panic_utf8(msg_len+1+stack_len, (uint64_t)error_c);\\\r\n    }\\\r\n    js_std_loop(ctx);\\\r\n  }\r\n\r\n// #############\r\n// # Registers #\r\n// #############\r\nextern void read_register(uint64_t register_id, uint64_t ptr);\r\nextern uint64_t register_len(uint64_t register_id);\r\nextern void write_register(uint64_t register_id, uint64_t data_len, uint64_t data_ptr);\r\n// ###############\r\n// # Context API #\r\n// ###############\r\nextern void current_account_id(uint64_t register_id);\r\nextern void signer_account_id(uint64_t register_id);\r\nextern void signer_account_pk(uint64_t register_id);\r\nextern void predecessor_account_id(uint64_t register_id);\r\nextern void input(uint64_t register_id);\r\nextern uint64_t block_index();\r\nextern uint64_t block_timestamp();\r\nextern uint64_t epoch_height();\r\nextern uint64_t storage_usage();\r\n// #################\r\n// # Economics API #\r\n// #################\r\nextern void account_balance(uint64_t balance_ptr);\r\nextern void account_locked_balance(uint64_t balance_ptr);\r\nextern void attached_deposit(uint64_t balance_ptr);\r\nextern uint64_t prepaid_gas();\r\nextern uint64_t used_gas();\r\n// ############\r\n// # Math API #\r\n// ############\r\nextern void random_seed(uint64_t register_id);\r\nextern void sha256(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern void keccak256(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern void keccak512(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern void ripemd160(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern uint64_t ecrecover(uint64_t hash_len, uint64_t hash_ptr, uint64_t sign_len, uint64_t sig_ptr, uint64_t v, uint64_t malleability_flag, uint64_t register_id);\r\n// #####################\r\n// # Miscellaneous API #\r\n// #####################\r\nextern void value_return(uint64_t value_len, uint64_t value_ptr);\r\nextern void panic(void);\r\nextern void panic_utf8(uint64_t len, uint64_t ptr);\r\nextern void log_utf8(uint64_t len, uint64_t ptr);\r\nextern void log_utf16(uint64_t len, uint64_t ptr);\r\n// Name confliction with WASI. Can be re-exported with a different name on NEAR side with a protocol upgrade\r\n// Or, this is actually not a primitive, can be implement with log and panic host functions in C side or JS side. \r\n// extern void abort(uint32_t msg_ptr, uint32_t filename_ptr, uint32_t u32, uint32_t col);\r\n// ################\r\n// # Promises API #\r\n// ################\r\nextern uint64_t promise_create(uint64_t account_id_len, uint64_t account_id_ptr, uint64_t method_name_len, uint64_t method_name_ptr, uint64_t arguments_len, uint64_t arguments_ptr, uint64_t amount_ptr, uint64_t gas);\r\nextern uint64_t promise_then(uint64_t promise_index, uint64_t account_id_len, uint64_t account_id_ptr, uint64_t method_name_len, uint64_t method_name_ptr, uint64_t arguments_len, uint64_t arguments_ptr, uint64_t amount_ptr, uint64_t gas);\r\nextern uint64_t promise_and(uint64_t promise_idx_ptr, uint64_t promise_idx_count);\r\nextern uint64_t promise_batch_create(uint64_t account_id_len, uint64_t account_id_ptr);\r\nextern uint64_t promise_batch_then(uint64_t promise_index, uint64_t account_id_len, uint64_t account_id_ptr);\r\n// #######################\r\n// # Promise API actions #\r\n// #######################\r\nextern void promise_batch_action_create_account(uint64_t promise_index);\r\nextern void promise_batch_action_deploy_contract(uint64_t promise_index, uint64_t code_len, uint64_t code_ptr);\r\nextern void promise_batch_action_function_call(uint64_t promise_index, uint64_t method_name_len, uint64_t method_name_ptr, uint64_t arguments_len, uint64_t arguments_ptr, uint64_t amount_ptr, uint64_t gas);\r\nextern void promise_batch_action_transfer(uint64_t promise_index, uint64_t amount_ptr);\r\nextern void promise_batch_action_stake(uint64_t promise_index, uint64_t amount_ptr, uint64_t public_key_len, uint64_t public_key_ptr);\r\nextern void promise_batch_action_add_key_with_full_access(uint64_t promise_index, uint64_t public_key_len, uint64_t public_key_ptr, uint64_t nonce);\r\nextern void promise_batch_action_add_key_with_function_call(uint64_t promise_index, uint64_t public_key_len, uint64_t public_key_ptr, uint64_t nonce, uint64_t allowance_ptr, uint64_t receiver_id_len, uint64_t receiver_id_ptr, uint64_t method_names_len, uint64_t method_names_ptr);\r\nextern void promise_batch_action_delete_key(uint64_t promise_index, uint64_t public_key_len, uint64_t public_key_ptr);\r\nextern void promise_batch_action_delete_account(uint64_t promise_index, uint64_t beneficiary_id_len, uint64_t beneficiary_id_ptr);\r\nextern void promise_batch_action_function_call_weight(uint64_t promise_index, uint64_t function_name_len, uint64_t function_name_ptr, uint64_t arguments_len, uint64_t arguments_ptr, uint64_t amount_ptr, uint64_t gas, uint64_t weight);\r\n// #######################\r\n// # Promise API results #\r\n// #######################\r\nextern uint64_t promise_results_count(void);\r\nextern uint64_t promise_result(uint64_t result_idx, uint64_t register_id);\r\nextern void promise_return(uint64_t promise_idx);\r\n// ###############\r\n// # Storage API #\r\n// ###############\r\nextern uint64_t storage_write(uint64_t key_len, uint64_t key_ptr, uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern uint64_t storage_read(uint64_t key_len, uint64_t key_ptr, uint64_t register_id);\r\nextern uint64_t storage_remove(uint64_t key_len, uint64_t key_ptr, uint64_t register_id);\r\nextern uint64_t storage_has_key(uint64_t key_len, uint64_t key_ptr);\r\n// #################\r\n// # Validator API #\r\n// #################\r\nextern void validator_stake(uint64_t account_id_len, uint64_t account_id_ptr, uint64_t stake_ptr);\r\nextern void validator_total_stake(uint64_t stake_ptr);\r\n// #############\r\n// # Alt BN128 #\r\n// #############\r\nextern void alt_bn128_g1_multiexp(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern void alt_bn128_g1_sum(uint64_t value_len, uint64_t value_ptr, uint64_t register_id);\r\nextern uint64_t alt_bn128_pairing_check(uint64_t value_len, uint64_t value_ptr);\r\n\r\nstatic uint8_t* JS_Uint8Array_to_C(JSContext *ctx, JSValue array, size_t *len) {\r\n  uint8_t *ptr;\r\n  JSValue buffer;\r\n  size_t pbyte_offset, psize, pbytes_per_element = 0;\r\n\r\n  buffer = JS_GetTypedArrayBuffer(ctx, array, &pbyte_offset, len, &pbytes_per_element);\r\n  if (JS_IsException(buffer) || pbytes_per_element != 1) {\r\n    return NULL;\r\n  }\r\n  ptr = JS_GetArrayBuffer(ctx, &psize, buffer);\r\n  if (ptr == NULL) {\r\n    return NULL;\r\n  }\r\n  return ptr + pbyte_offset;\r\n}\r\n\r\nstatic JSValue near_read_register(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data;\r\n  uint64_t data_len;\r\n  JSValue arraybuffer, ret;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  data_len = register_len(register_id);\r\n  if (data_len != UINT64_MAX) {\r\n    data = malloc(data_len);\r\n    read_register(register_id, (uint64_t)data);\r\n    arraybuffer = JS_NewArrayBuffer(ctx, data, (size_t)data_len, NULL, NULL, TRUE);\r\n    return JS_CallConstructor(ctx, JS_GetPropertyStr(ctx, JS_GetGlobalObject(ctx), \"Uint8Array\"), 1, (JSValueConst *)&arraybuffer);\r\n  } else {\r\n    return JS_UNDEFINED;\r\n  }\r\n}\r\n\r\nstatic JSValue near_register_len(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id, len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  len = register_len(register_id);\r\n  return JS_NewBigUint64(ctx, len);\r\n}\r\n\r\nstatic JSValue near_write_register(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[1], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n\r\n  write_register(register_id, data_len, (uint64_t)data_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_current_account_id(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  current_account_id(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_signer_account_id(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  signer_account_id(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_signer_account_pk(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  signer_account_pk(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_predecessor_account_id(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  predecessor_account_id(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_input(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  input(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_block_index(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = block_index();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_block_timestamp(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = block_timestamp();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_epoch_height(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = epoch_height();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_storage_usage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = storage_usage();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\n// ptr[0] ptr[1] is little-endian u128.\r\nstatic JSValue u128_to_quickjs(JSContext *ctx, uint64_t* ptr) {\r\n  JSValue value;\r\n  bf_t* bn;\r\n  bf_t b;\r\n\r\n  value = JS_NewBigInt(ctx);\r\n  bn = JS_GetBigInt(value);\r\n  // from ptr[] to bn\r\n  // high 64 bits\r\n  bf_set_ui(bn, ptr[1]);\r\n  bf_mul_2exp(bn, 64, BF_PREC_INF, BF_RNDZ);\r\n  // low 64 bits\r\n  bf_init(bn->ctx, &b);\r\n  bf_set_ui(&b, ptr[0]);\r\n  bf_add(bn, bn, &b, BF_PREC_INF, BF_RNDZ);\r\n  bf_delete(&b);\r\n  \r\n  return value;\r\n}\r\n\r\nstatic int quickjs_bigint_to_u128(JSContext *ctx, JSValueConst val, uint64_t* ptr) {\r\n  bf_t* a;\r\n  bf_t q, r, b, one, u128max;\r\n  a = JS_GetBigInt(val);\r\n  bf_init(a->ctx, &u128max);\r\n  bf_set_ui(&u128max, 1);\r\n  bf_mul_2exp(&u128max, 128, BF_PREC_INF, BF_RNDZ);\r\n  if (bf_cmp_le(&u128max, a)) {\r\n    return 1;\r\n  }\r\n  bf_init(a->ctx, &q);\r\n  bf_init(a->ctx, &r);\r\n  bf_init(a->ctx, &b);\r\n  bf_init(a->ctx, &one);\r\n  bf_set_ui(&b, UINT64_MAX);\r\n  bf_set_ui(&one, 1);\r\n  bf_add(&b, &b, &one, BF_PREC_INF, BF_RNDZ);\r\n  bf_divrem(&q, &r, a, &b, BF_PREC_INF, BF_RNDZ, BF_RNDZ);\r\n  \r\n  bf_get_uint64(ptr, &r);\r\n  bf_get_uint64(ptr+1, &q);\r\n  return 0;\r\n}\r\n\r\nstatic int quickjs_int_to_u128(JSContext *ctx, JSValueConst val, uint64_t* ptr) {\r\n  if (JS_ToUint64Ext(ctx, ptr, val) < 0) {\r\n    return 1;\r\n  }\r\n  ptr[1] = 0;\r\n  return 0;\r\n}\r\n\r\nstatic int quickjs_to_u128(JSContext *ctx, JSValueConst val, uint64_t* ptr) {\r\n  if (JS_IsBigInt(ctx, val))\r\n    return quickjs_bigint_to_u128(ctx, val, ptr);\r\n  else {\r\n    return quickjs_int_to_u128(ctx, val, ptr);\r\n  }\r\n}\r\n\r\nstatic JSValue near_account_balance(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{  \r\n  uint64_t ptr[2];\r\n\r\n  account_balance((uint64_t)ptr); \r\n  return u128_to_quickjs(ctx, ptr);\r\n}\r\n\r\nstatic JSValue near_account_locked_balance(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t ptr[2];\r\n\r\n  account_locked_balance((uint64_t)ptr);\r\n  return u128_to_quickjs(ctx, ptr);\r\n}\r\n\r\nstatic JSValue near_attached_deposit(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t ptr[2];\r\n\r\n  attached_deposit((uint64_t)ptr);\r\n  return u128_to_quickjs(ctx, ptr);\r\n}\r\n\r\nstatic JSValue near_prepaid_gas(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = prepaid_gas();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_used_gas(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = used_gas();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_random_seed(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  random_seed(register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_sha256(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  \r\n  sha256(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_keccak256(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }  \r\n  keccak256(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_keccak512(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  \r\n  keccak512(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_ripemd160(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  \r\n  ripemd160(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_ecrecover(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t malleability_flag, v, register_id, result;\r\n  uint8_t *hash_ptr, *sig_ptr;\r\n  size_t hash_len, sign_len;\r\n\r\n  hash_ptr = JS_Uint8Array_to_C(ctx, argv[0], &hash_len);\r\n  if (hash_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for hash\"); \r\n  }\r\n  sig_ptr = JS_Uint8Array_to_C(ctx, argv[1], &sign_len);\r\n  if (sig_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for sig\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &malleability_flag, argv[2]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for malleability_flag\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &v, argv[3]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for v\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[4]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n \r\n  result = ecrecover(hash_len, (uint64_t)hash_ptr, sign_len, (uint64_t)sig_ptr, malleability_flag, v, register_id);\r\n  return JS_NewBigUint64(ctx, result);\r\n}\r\n\r\nstatic JSValue near_value_return(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) \r\n{\r\n  uint8_t *value_ptr;\r\n  size_t value_len;\r\n\r\n  value_ptr = JS_Uint8Array_to_C(ctx, argv[0], &value_len);\r\n  if (value_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for value\"); \r\n  }\r\n  value_return(value_len, (uint64_t)(value_ptr));\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_panic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *data_ptr;\r\n  size_t data_len;\r\n\r\n  if (argc == 1) {\r\n    data_ptr = JS_ToCStringLen(ctx, &data_len, argv[0]);\r\n    panic_utf8(data_len, (uint64_t)data_ptr);\r\n  } else {\r\n    panic();\r\n  }\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_panic_utf8(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for message\"); \r\n  }\r\n  \r\n  panic_utf8(data_len, (uint64_t)data_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_log(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_ToCStringLen(ctx, &data_len, argv[0]);\r\n  \r\n  log_utf8(data_len, (uint64_t)data_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_log_utf8(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for message\"); \r\n  }\r\n\r\n  log_utf8(data_len, (uint64_t)data_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_log_utf16(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for message\"); \r\n  }\r\n\r\n  log_utf16(data_len, (uint64_t)data_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_create(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *account_id_ptr, *method_name_ptr;\r\n  uint8_t *arguments_ptr;\r\n  size_t account_id_len, method_name_len, arguments_len;\r\n  uint64_t amount_ptr[2]; // amount is u128\r\n  uint64_t gas, ret;\r\n\r\n  account_id_ptr = JS_ToCStringLen(ctx, &account_id_len, argv[0]);\r\n  method_name_ptr = JS_ToCStringLen(ctx, &method_name_len, argv[1]);\r\n  arguments_ptr = JS_Uint8Array_to_C(ctx, argv[2], &arguments_len);\r\n  if (arguments_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for arguments\"); \r\n  }\r\n  if (quickjs_to_u128(ctx, argv[3], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &gas, argv[4]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for gas\");\r\n  }\r\n\r\n  ret = promise_create(account_id_len, (uint64_t)account_id_ptr, method_name_len, (uint64_t)method_name_ptr, arguments_len, (uint64_t)arguments_ptr, (uint64_t)amount_ptr, gas);\r\n  \r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_then(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *account_id_ptr, *method_name_ptr;\r\n  uint8_t *arguments_ptr;\r\n  size_t account_id_len, method_name_len, arguments_len;\r\n  uint64_t amount_ptr[2]; // amount is u128\r\n  uint64_t gas, ret;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  account_id_ptr = JS_ToCStringLen(ctx, &account_id_len, argv[1]);\r\n  method_name_ptr = JS_ToCStringLen(ctx, &method_name_len, argv[2]);\r\n  arguments_ptr = JS_Uint8Array_to_C(ctx, argv[3], &arguments_len);\r\n  if (arguments_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for arguments\"); \r\n  }  \r\n  if (quickjs_to_u128(ctx, argv[4], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &gas, argv[5]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for gas\");\r\n  }\r\n\r\n  ret = promise_then(promise_index, account_id_len, (uint64_t)account_id_ptr, method_name_len, (uint64_t)method_name_ptr, arguments_len, (uint64_t)arguments_ptr, (uint64_t)amount_ptr, gas);\r\n  \r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_and(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_idx_ptr[argc], ret;\r\n\r\n  for(int i = 0; i < argc; i++) {\r\n    if (JS_ToUint64Ext(ctx, &promise_idx_ptr[i], argv[i]) < 0) {\r\n      return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_id\");\r\n    }\r\n  }\r\n  ret = promise_and((uint64_t)promise_idx_ptr, argc);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_batch_create(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *account_id_ptr;\r\n  size_t account_id_len;\r\n  uint64_t ret;\r\n\r\n  account_id_ptr = JS_ToCStringLen(ctx, &account_id_len, argv[0]);\r\n  ret = promise_batch_create(account_id_len, (uint64_t)account_id_ptr);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_batch_then(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *account_id_ptr;\r\n  size_t account_id_len;\r\n  uint64_t ret;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  account_id_ptr = JS_ToCStringLen(ctx, &account_id_len, argv[1]);\r\n  ret = promise_batch_then(promise_index, account_id_len, (uint64_t)account_id_ptr);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_create_account(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  promise_batch_action_create_account(promise_index);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_deploy_contract(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  uint8_t *code_ptr;\r\n  size_t code_len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  code_ptr = JS_Uint8Array_to_C(ctx, argv[1], &code_len);\r\n  if (code_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for code\"); \r\n  }\r\n  promise_batch_action_deploy_contract(promise_index, code_len, (uint64_t)code_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_function_call(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *method_name_ptr;\r\n  uint8_t *arguments_ptr;\r\n  size_t method_name_len, arguments_len;\r\n  uint64_t amount_ptr[2]; // amount is u128\r\n  uint64_t gas;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  method_name_ptr = JS_ToCStringLen(ctx, &method_name_len, argv[1]);\r\n  arguments_ptr = JS_Uint8Array_to_C(ctx, argv[2], &arguments_len);\r\n  if (arguments_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for arguments\"); \r\n  }\r\n  if (quickjs_to_u128(ctx, argv[3], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &gas, argv[4]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for gas\");\r\n  }\r\n  promise_batch_action_function_call(promise_index, method_name_len, (uint64_t)method_name_ptr, arguments_len, (uint64_t)arguments_ptr, (uint64_t)amount_ptr, gas);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_transfer(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  uint64_t amount_ptr[2]; // amount is u128\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  if (quickjs_to_u128(ctx, argv[1], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  promise_batch_action_transfer(promise_index, (uint64_t)amount_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_stake(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  uint64_t amount_ptr[2];\r\n  uint8_t *public_key_ptr;\r\n  size_t public_key_len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  if (quickjs_to_u128(ctx, argv[1], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  public_key_ptr = JS_Uint8Array_to_C(ctx, argv[2], &public_key_len);\r\n  if (public_key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for public key\"); \r\n  }\r\n\r\n  promise_batch_action_stake(promise_index, (uint64_t)amount_ptr, public_key_len, (uint64_t)public_key_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_add_key_with_full_access(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  uint8_t *public_key_ptr;\r\n  size_t public_key_len;\r\n  uint64_t nonce;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  public_key_ptr = JS_Uint8Array_to_C(ctx, argv[1], &public_key_len);\r\n  if (public_key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for public key\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &nonce, argv[2]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for nonce\");\r\n  }\r\n  promise_batch_action_add_key_with_full_access(promise_index, public_key_len, (uint64_t)public_key_ptr, nonce);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_add_key_with_function_call(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *receiver_id_ptr, *method_names_ptr;\r\n  uint8_t *public_key_ptr;\r\n  size_t public_key_len, receiver_id_len, method_names_len;\r\n  uint64_t nonce, allowance_ptr[2];\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  public_key_ptr = JS_Uint8Array_to_C(ctx, argv[1], &public_key_len);\r\n  if (public_key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for public key\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &nonce, argv[2]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for nonce\");\r\n  }\r\n  if (quickjs_to_u128(ctx, argv[3], allowance_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for allowance\");\r\n  }\r\n  receiver_id_ptr = JS_ToCStringLen(ctx, &receiver_id_len, argv[4]);\r\n  method_names_ptr = JS_ToCStringLen(ctx, &method_names_len, argv[5]);\r\n\r\n  promise_batch_action_add_key_with_function_call(promise_index, public_key_len, (uint64_t)public_key_ptr, nonce, (uint64_t)allowance_ptr, receiver_id_len, (uint64_t)receiver_id_ptr, method_names_len, (uint64_t)method_names_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_delete_key(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  uint8_t *public_key_ptr;\r\n  size_t public_key_len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  public_key_ptr = JS_Uint8Array_to_C(ctx, argv[1], &public_key_len);\r\n  if (public_key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for public key\"); \r\n  }\r\n  promise_batch_action_delete_key(promise_index, public_key_len, (uint64_t)public_key_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_function_call_weight(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *method_name_ptr, *arguments_ptr;\r\n  size_t method_name_len, arguments_len;\r\n  uint64_t amount_ptr[2]; // amount is u128\r\n  uint64_t gas;\r\n  uint64_t weight;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  method_name_ptr = JS_ToCStringLen(ctx, &method_name_len, argv[1]);\r\n  arguments_ptr = JS_ToCStringLenRaw(ctx, &arguments_len, argv[2]);\r\n  if (quickjs_to_u128(ctx, argv[3], amount_ptr) != 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint128 for amount\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &gas, argv[4]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for gas\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &weight, argv[5]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for weight\");\r\n  }\r\n  promise_batch_action_function_call_weight(promise_index, method_name_len, (uint64_t)method_name_ptr, arguments_len, (uint64_t)arguments_ptr, (uint64_t)amount_ptr, gas, weight);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_batch_action_delete_account(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_index;\r\n  const char *beneficiary_id_ptr;\r\n  size_t beneficiary_id_len;\r\n\r\n  if (JS_ToUint64Ext(ctx, &promise_index, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_index\");\r\n  }\r\n  beneficiary_id_ptr = JS_ToCStringLen(ctx, &beneficiary_id_len, argv[1]);\r\n  promise_batch_action_delete_account(promise_index, beneficiary_id_len, (uint64_t)beneficiary_id_ptr);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_promise_results_count(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t value;\r\n\r\n  value = promise_results_count();\r\n  return JS_NewBigUint64(ctx, value);\r\n}\r\n\r\nstatic JSValue near_promise_result(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t result_idx, register_id;\r\n  uint64_t ret;\r\n\r\n  if (JS_ToUint64Ext(ctx, &result_idx, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for result_idx\");\r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  ret = promise_result(result_idx, register_id);\r\n\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_promise_return(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t promise_idx;\r\n  if (JS_ToUint64Ext(ctx, &promise_idx, argv[0]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for promise_idx\");\r\n  }\r\n  promise_return(promise_idx);\r\n  \r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_storage_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *key_ptr, *value_ptr;\r\n  size_t key_len, value_len;\r\n  uint64_t register_id, ret;\r\n\r\n  key_ptr = JS_Uint8Array_to_C(ctx, argv[0], &key_len);\r\n  if (key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for key\"); \r\n  }\r\n  value_ptr = JS_Uint8Array_to_C(ctx, argv[1], &value_len);\r\n  if (value_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for value\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[2]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  ret = storage_write(key_len, (uint64_t)key_ptr, value_len, (uint64_t)value_ptr, register_id);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_storage_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *key_ptr;\r\n  size_t key_len;\r\n  uint64_t register_id;\r\n  uint64_t ret;\r\n\r\n  key_ptr = JS_Uint8Array_to_C(ctx, argv[0], &key_len);\r\n  if (key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for key\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  ret = storage_read(key_len, (uint64_t)key_ptr, register_id);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_storage_remove(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *key_ptr;\r\n  size_t key_len;\r\n  uint64_t register_id;\r\n  uint64_t ret;\r\n\r\n  key_ptr = JS_Uint8Array_to_C(ctx, argv[0], &key_len);\r\n  if (key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for key\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n  ret = storage_remove(key_len, (uint64_t)key_ptr, register_id);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_storage_has_key(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *key_ptr;\r\n  size_t key_len;\r\n  uint64_t ret;\r\n\r\n  key_ptr = JS_Uint8Array_to_C(ctx, argv[0], &key_len);\r\n  if (key_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for key\"); \r\n  }\r\n  ret = storage_has_key(key_len, (uint64_t)key_ptr);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic JSValue near_validator_stake(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *account_id_ptr;\r\n  size_t account_id_len;\r\n  uint64_t stake_ptr[2];\r\n\r\n  account_id_ptr = JS_ToCStringLen(ctx, &account_id_len, argv[0]);\r\n  validator_stake(account_id_len, (uint64_t)account_id_ptr, (uint64_t)stake_ptr);\r\n\r\n  return u128_to_quickjs(ctx, stake_ptr);\r\n}\r\n\r\nstatic JSValue near_validator_total_stake(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t stake_ptr[2];\r\n\r\n  validator_total_stake((uint64_t)stake_ptr);\r\n  return u128_to_quickjs(ctx, stake_ptr);\r\n}\r\n\r\nstatic JSValue near_utf8_string_to_uint8array(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *data;\r\n  size_t len;\r\n  JSValue arraybuffer;\r\n\r\n  data = JS_ToCStringLen(ctx, &len, argv[0]);\r\n\r\n  arraybuffer = JS_NewArrayBuffer(ctx, (uint8_t *)data, len, NULL, NULL, TRUE);\r\n  return JS_CallConstructor(ctx, JS_GetPropertyStr(ctx, JS_GetGlobalObject(ctx), \"Uint8Array\"), 1, (JSValueConst *)&arraybuffer);\r\n}\r\n\r\nstatic JSValue near_latin1_string_to_uint8array(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  const char *data;\r\n  size_t len;\r\n  JSValue arraybuffer;\r\n\r\n  data = JS_ToCStringLenRaw(ctx, &len, argv[0]);\r\n\r\n  arraybuffer = JS_NewArrayBuffer(ctx, (uint8_t *)data, len, NULL, NULL, TRUE);\r\n  return JS_CallConstructor(ctx, JS_GetPropertyStr(ctx, JS_GetGlobalObject(ctx), \"Uint8Array\"), 1, (JSValueConst *)&arraybuffer);\r\n}\r\n\r\nstatic JSValue near_uint8array_to_latin1_string(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array\");\r\n  }\r\n\r\n  return JS_NewStringLenRaw(ctx, (const char *)data_ptr, data_len);\r\n}\r\n\r\nstatic JSValue near_uint8array_to_utf8_string(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array\");\r\n  }\r\n  \r\n  return JS_NewStringLen(ctx, (const char *)data_ptr, data_len);\r\n}\r\n\r\nstatic JSValue near_alt_bn128_g1_multiexp(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n\r\n  alt_bn128_g1_multiexp(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_alt_bn128_g1_sum(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint64_t register_id;\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }\r\n  if (JS_ToUint64Ext(ctx, &register_id, argv[1]) < 0) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint64 for register_id\");\r\n  }\r\n\r\n  alt_bn128_g1_sum(data_len, (uint64_t)data_ptr, register_id);\r\n  return JS_UNDEFINED;\r\n}\r\n\r\nstatic JSValue near_alt_bn128_pairing_check(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\r\n{\r\n  uint8_t *data_ptr;\r\n  size_t data_len;\r\n  uint64_t ret;\r\n\r\n  data_ptr = JS_Uint8Array_to_C(ctx, argv[0], &data_len);\r\n  if (data_ptr == NULL) {\r\n    return JS_ThrowTypeError(ctx, \"Expect Uint8Array for data\"); \r\n  }  \r\n  ret = alt_bn128_pairing_check(data_len, (uint64_t)data_ptr);\r\n  return JS_NewBigUint64(ctx, ret);\r\n}\r\n\r\nstatic void js_add_near_host_functions(JSContext* ctx) {\r\n  JSValue global_obj, env;\r\n\r\n  global_obj = JS_GetGlobalObject(ctx);\r\n  env = JS_NewObject(ctx);\r\n\r\n  JS_SetPropertyStr(ctx, env, \"read_register\", JS_NewCFunction(ctx, near_read_register, \"read_register\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"register_len\", JS_NewCFunction(ctx, near_register_len, \"register_len\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"write_register\", JS_NewCFunction(ctx, near_write_register, \"write_register\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"current_account_id\", JS_NewCFunction(ctx, near_current_account_id, \"current_account_id\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"signer_account_id\", JS_NewCFunction(ctx, near_signer_account_id, \"signer_account_id\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"signer_account_pk\", JS_NewCFunction(ctx, near_signer_account_pk, \"signer_account_pk\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"predecessor_account_id\", JS_NewCFunction(ctx, near_predecessor_account_id, \"predecessor_account_id\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"input\", JS_NewCFunction(ctx, near_input, \"input\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"block_index\", JS_NewCFunction(ctx, near_block_index, \"block_index\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"block_timestamp\", JS_NewCFunction(ctx, near_block_timestamp, \"block_timestamp\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"epoch_height\", JS_NewCFunction(ctx, near_epoch_height, \"epoch_height\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"storage_usage\", JS_NewCFunction(ctx, near_storage_usage, \"storage_usage\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"account_balance\", JS_NewCFunction(ctx, near_account_balance, \"account_balance\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"account_locked_balance\", JS_NewCFunction(ctx, near_account_locked_balance, \"account_locked_balance\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"attached_deposit\", JS_NewCFunction(ctx, near_attached_deposit, \"attached_deposit\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"prepaid_gas\", JS_NewCFunction(ctx, near_prepaid_gas, \"prepaid_gas\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"used_gas\", JS_NewCFunction(ctx, near_used_gas, \"used_gas\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"random_seed\", JS_NewCFunction(ctx, near_random_seed, \"random_seed\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"sha256\", JS_NewCFunction(ctx, near_sha256, \"sha256\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"keccak256\", JS_NewCFunction(ctx, near_keccak256, \"keccak256\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"keccak512\", JS_NewCFunction(ctx, near_keccak512, \"keccak512\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"ripemd160\", JS_NewCFunction(ctx, near_ripemd160, \"ripemd160\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"ecrecover\", JS_NewCFunction(ctx, near_ecrecover, \"ecrecover\", 5));\r\n  JS_SetPropertyStr(ctx, env, \"value_return\", JS_NewCFunction(ctx, near_value_return, \"value_return\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"panic\", JS_NewCFunction(ctx, near_panic, \"panic\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"panic_utf8\", JS_NewCFunction(ctx, near_panic_utf8, \"panic_utf8\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"log\", JS_NewCFunction(ctx, near_log, \"log\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"log_utf8\", JS_NewCFunction(ctx, near_log_utf8, \"log_utf8\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"log_utf16\", JS_NewCFunction(ctx, near_log_utf16, \"log_utf16\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"promise_create\", JS_NewCFunction(ctx, near_promise_create, \"promise_create\", 5));\r\n  JS_SetPropertyStr(ctx, env, \"promise_then\", JS_NewCFunction(ctx, near_promise_then, \"promise_then\", 6));\r\n  JS_SetPropertyStr(ctx, env, \"promise_and\", JS_NewCFunction(ctx, near_promise_and, \"promise_and\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_create\", JS_NewCFunction(ctx, near_promise_batch_create, \"promise_batch_create\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_then\", JS_NewCFunction(ctx, near_promise_batch_then, \"promise_batch_then\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_create_account\", JS_NewCFunction(ctx, near_promise_batch_action_create_account, \"promise_batch_action_create_account\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_deploy_contract\", JS_NewCFunction(ctx, near_promise_batch_action_deploy_contract, \"promise_batch_action_deploy_contract\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_function_call\", JS_NewCFunction(ctx, near_promise_batch_action_function_call, \"promise_batch_action_function_call\", 5));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_transfer\", JS_NewCFunction(ctx, near_promise_batch_action_transfer, \"promise_batch_action_transfer\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_stake\", JS_NewCFunction(ctx, near_promise_batch_action_stake, \"promise_batch_action_stake\", 3));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_add_key_with_full_access\", JS_NewCFunction(ctx, near_promise_batch_action_add_key_with_full_access, \"promise_batch_action_add_key_with_full_access\", 3));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_add_key_with_function_call\", JS_NewCFunction(ctx, near_promise_batch_action_add_key_with_function_call, \"promise_batch_action_add_key_with_function_call\", 6));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_delete_key\", JS_NewCFunction(ctx, near_promise_batch_action_delete_key, \"promise_batch_action_delete_key\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_delete_account\", JS_NewCFunction(ctx, near_promise_batch_action_delete_account, \"promise_batch_action_delete_account\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_batch_action_function_call_weight\", JS_NewCFunction(ctx, near_promise_batch_action_function_call_weight, \"promise_batch_action_function_call_weight\", 6));\r\n  JS_SetPropertyStr(ctx, env, \"promise_results_count\", JS_NewCFunction(ctx, near_promise_results_count, \"promise_results_count\", 0));\r\n  JS_SetPropertyStr(ctx, env, \"promise_result\", JS_NewCFunction(ctx, near_promise_result, \"promise_result\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"promise_return\", JS_NewCFunction(ctx, near_promise_return, \"promise_return\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"storage_write\", JS_NewCFunction(ctx, near_storage_write, \"storage_write\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"storage_read\", JS_NewCFunction(ctx, near_storage_read, \"storage_read\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"storage_remove\", JS_NewCFunction(ctx, near_storage_remove, \"storage_remove\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"storage_has_key\", JS_NewCFunction(ctx, near_storage_has_key, \"storage_has_key\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"validator_stake\", JS_NewCFunction(ctx, near_validator_stake, \"validator_stake\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"validator_total_stake\", JS_NewCFunction(ctx, near_validator_total_stake, \"validator_total_stake\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"alt_bn128_g1_multiexp\", JS_NewCFunction(ctx, near_alt_bn128_g1_multiexp, \"alt_bn128_g1_multiexp\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"alt_bn128_g1_sum\", JS_NewCFunction(ctx, near_alt_bn128_g1_sum, \"alt_bn128_g1_sum\", 2));\r\n  JS_SetPropertyStr(ctx, env, \"alt_bn128_pairing_check\", JS_NewCFunction(ctx, near_alt_bn128_pairing_check, \"alt_bn128_pairing_check\", 1));\r\n\r\n  JS_SetPropertyStr(ctx, env, \"latin1_string_to_uint8array\", JS_NewCFunction(ctx, near_latin1_string_to_uint8array, \"latin1_string_to_uint8array\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"utf8_string_to_uint8array\", JS_NewCFunction(ctx, near_utf8_string_to_uint8array, \"utf8_string_to_uint8array\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"uint8array_to_latin1_string\", JS_NewCFunction(ctx, near_uint8array_to_latin1_string, \"uint8array_to_latin1_string\", 1));\r\n  JS_SetPropertyStr(ctx, env, \"uint8array_to_utf8_string\", JS_NewCFunction(ctx, near_uint8array_to_utf8_string, \"uint8array_to_utf8_string\", 1));\r\n\r\n  JS_SetPropertyStr(ctx, global_obj, \"env\", env);\r\n}\r\n\r\nJSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,\r\n                int argc, JSValueConst *argv);\r\n\r\nvoid _start() {}\r\n\r\n#include \"methods.h\"\r\n"
  },
  {
    "path": "packages/near-sdk-js/lib/api.d.ts",
    "content": "import { NearAmount, PromiseIndex } from \"./utils\";\nimport { GasWeight } from \"./types\";\n/**\n * Logs parameters in the NEAR WASM virtual machine.\n *\n * @param params - Parameters to log.\n */\nexport declare function log(...params: unknown[]): void;\n/**\n * Returns the account ID of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport declare function signerAccountId(): string;\n/**\n * Returns the public key of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport declare function signerAccountPk(): Uint8Array;\n/**\n * Returns the account ID of the account that called the function.\n * Can only be called in a call or initialize function.\n */\nexport declare function predecessorAccountId(): string;\n/**\n * Returns the account ID of the current contract - the contract that is being executed.\n */\nexport declare function currentAccountId(): string;\n/**\n * Returns the current block index.\n */\nexport declare function blockIndex(): bigint;\n/**\n * Returns the current block height.\n */\nexport declare function blockHeight(): bigint;\n/**\n * Returns the current block timestamp.\n */\nexport declare function blockTimestamp(): bigint;\n/**\n * Returns the current epoch height.\n */\nexport declare function epochHeight(): bigint;\n/**\n * Returns the amount of NEAR attached to this function call.\n * Can only be called in payable functions.\n */\nexport declare function attachedDeposit(): bigint;\n/**\n * Returns the amount of Gas that was attached to this function call.\n */\nexport declare function prepaidGas(): bigint;\n/**\n * Returns the amount of Gas that has been used by this function call until now.\n */\nexport declare function usedGas(): bigint;\n/**\n * Returns the current account's account balance.\n */\nexport declare function accountBalance(): bigint;\n/**\n * Returns the current account's locked balance.\n */\nexport declare function accountLockedBalance(): bigint;\n/**\n * Reads the value from NEAR storage that is stored under the provided key.\n *\n * @param key - The key to read from storage.\n */\nexport declare function storageReadRaw(key: Uint8Array): Uint8Array | null;\n/**\n * Reads the utf-8 string value from NEAR storage that is stored under the provided key.\n *\n * @param key - The utf-8 string key to read from storage.\n */\nexport declare function storageRead(key: string): string | null;\n/**\n * Checks for the existence of a value under the provided key in NEAR storage.\n *\n * @param key - The key to check for in storage.\n */\nexport declare function storageHasKeyRaw(key: Uint8Array): boolean;\n/**\n * Checks for the existence of a value under the provided utf-8 string key in NEAR storage.\n *\n * @param key - The utf-8 string key to check for in storage.\n */\nexport declare function storageHasKey(key: string): boolean;\n/**\n * Get the last written or removed value from NEAR storage.\n */\nexport declare function storageGetEvictedRaw(): Uint8Array;\n/**\n * Get the last written or removed value from NEAR storage as utf-8 string.\n */\nexport declare function storageGetEvicted(): string;\n/**\n * Returns the current accounts NEAR storage usage.\n */\nexport declare function storageUsage(): bigint;\n/**\n * Writes the provided bytes to NEAR storage under the provided key.\n *\n * @param key - The key under which to store the value.\n * @param value - The value to store.\n */\nexport declare function storageWriteRaw(key: Uint8Array, value: Uint8Array): boolean;\n/**\n * Writes the provided utf-8 string to NEAR storage under the provided key.\n *\n * @param key - The utf-8 string key under which to store the value.\n * @param value - The utf-8 string value to store.\n */\nexport declare function storageWrite(key: string, value: string): boolean;\n/**\n * Removes the value of the provided key from NEAR storage.\n *\n * @param key - The key to be removed.\n */\nexport declare function storageRemoveRaw(key: Uint8Array): boolean;\n/**\n * Removes the value of the provided utf-8 string key from NEAR storage.\n *\n * @param key - The utf-8 string key to be removed.\n */\nexport declare function storageRemove(key: string): boolean;\n/**\n * Returns the cost of storing 0 Byte on NEAR storage.\n */\nexport declare function storageByteCost(): bigint;\n/**\n * Returns the arguments passed to the current smart contract call.\n */\nexport declare function inputRaw(): Uint8Array;\n/**\n * Returns the arguments passed to the current smart contract call as utf-8 string.\n */\nexport declare function input(): string;\n/**\n * Returns the value from the NEAR WASM virtual machine.\n *\n * @param value - The value to return.\n */\nexport declare function valueReturnRaw(value: Uint8Array): void;\n/**\n * Returns the utf-8 string value from the NEAR WASM virtual machine.\n *\n * @param value - The utf-8 string value to return.\n */\nexport declare function valueReturn(value: string): void;\n/**\n * Returns a random string of bytes.\n */\nexport declare function randomSeed(): Uint8Array;\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport declare function promiseCreateRaw(accountId: string, methodName: string, args: Uint8Array, amount: NearAmount, gas: NearAmount): PromiseIndex;\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport declare function promiseCreate(accountId: string, methodName: string, args: string, amount: NearAmount, gas: NearAmount): PromiseIndex;\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport declare function promiseThenRaw(promiseIndex: PromiseIndex, accountId: string, methodName: string, args: Uint8Array, amount: NearAmount, gas: NearAmount): PromiseIndex;\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport declare function promiseThen(promiseIndex: PromiseIndex, accountId: string, methodName: string, args: string, amount: NearAmount, gas: NearAmount): PromiseIndex;\n/**\n * Join an arbitrary array of NEAR promises.\n *\n * @param promiseIndexes - An arbitrary array of NEAR promise indexes to join.\n */\nexport declare function promiseAnd(...promiseIndexes: PromiseIndex[]): PromiseIndex;\n/**\n * Create a NEAR promise which will have multiple promise actions inside.\n *\n * @param accountId - The account ID of the target contract.\n */\nexport declare function promiseBatchCreate(accountId: string): PromiseIndex;\n/**\n * Attach a callback NEAR promise to a batch of NEAR promise actions.\n *\n * @param promiseIndex - The NEAR promise index of the batch.\n * @param accountId - The account ID of the target contract.\n */\nexport declare function promiseBatchThen(promiseIndex: PromiseIndex, accountId: string): PromiseIndex;\n/**\n * Attach a create account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a create account action to.\n */\nexport declare function promiseBatchActionCreateAccount(promiseIndex: PromiseIndex): void;\n/**\n * Attach a deploy contract promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a deploy contract action to.\n * @param code - The WASM byte code of the contract to be deployed.\n */\nexport declare function promiseBatchActionDeployContract(promiseIndex: PromiseIndex, code: Uint8Array): void;\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport declare function promiseBatchActionFunctionCallRaw(promiseIndex: PromiseIndex, methodName: string, args: Uint8Array, amount: NearAmount, gas: NearAmount): void;\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport declare function promiseBatchActionFunctionCall(promiseIndex: PromiseIndex, methodName: string, args: string, amount: NearAmount, gas: NearAmount): void;\n/**\n * Attach a transfer promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a transfer action to.\n * @param amount - The amount of NEAR to transfer.\n */\nexport declare function promiseBatchActionTransfer(promiseIndex: PromiseIndex, amount: NearAmount): void;\n/**\n * Attach a stake promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a stake action to.\n * @param amount - The amount of NEAR to stake.\n * @param publicKey - The public key with which to stake.\n */\nexport declare function promiseBatchActionStake(promiseIndex: PromiseIndex, amount: NearAmount, publicKey: Uint8Array): void;\n/**\n * Attach a add full access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add full access key action to.\n * @param publicKey - The public key to add as a full access key.\n * @param nonce - The nonce to use.\n */\nexport declare function promiseBatchActionAddKeyWithFullAccess(promiseIndex: PromiseIndex, publicKey: Uint8Array, nonce: number | bigint): void;\n/**\n * Attach a add access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add access key action to.\n * @param publicKey - The public key to add.\n * @param nonce - The nonce to use.\n * @param allowance - The allowance of the access key.\n * @param receiverId - The account ID of the receiver.\n * @param methodNames - The names of the method to allow the key for.\n */\nexport declare function promiseBatchActionAddKeyWithFunctionCall(promiseIndex: PromiseIndex, publicKey: Uint8Array, nonce: number | bigint, allowance: NearAmount, receiverId: string, methodNames: string): void;\n/**\n * Attach a delete key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete key action to.\n * @param publicKey - The public key to delete.\n */\nexport declare function promiseBatchActionDeleteKey(promiseIndex: PromiseIndex, publicKey: Uint8Array): void;\n/**\n * Attach a delete account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete account action to.\n * @param beneficiaryId - The account ID of the beneficiary - the account that receives the remaining amount of NEAR.\n */\nexport declare function promiseBatchActionDeleteAccount(promiseIndex: PromiseIndex, beneficiaryId: string): void;\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport declare function promiseBatchActionFunctionCallWeightRaw(promiseIndex: PromiseIndex, methodName: string, args: Uint8Array, amount: NearAmount, gas: NearAmount, weight: GasWeight): void;\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport declare function promiseBatchActionFunctionCallWeight(promiseIndex: PromiseIndex, methodName: string, args: string, amount: NearAmount, gas: NearAmount, weight: GasWeight): void;\n/**\n * The number of promise results available.\n */\nexport declare function promiseResultsCount(): bigint;\n/**\n * Returns the result of the NEAR promise for the passed promise index.\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport declare function promiseResultRaw(promiseIndex: PromiseIndex): Uint8Array;\n/**\n * Returns the result of the NEAR promise for the passed promise index as utf-8 string\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport declare function promiseResult(promiseIndex: PromiseIndex): string;\n/**\n * Executes the promise in the NEAR WASM virtual machine.\n *\n * @param promiseIndex - The index of the promise to execute.\n */\nexport declare function promiseReturn(promiseIndex: PromiseIndex): void;\n/**\n * Returns sha256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport declare function sha256(value: Uint8Array): Uint8Array;\n/**\n * Returns keccak256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport declare function keccak256(value: Uint8Array): Uint8Array;\n/**\n * Returns keccak512 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport declare function keccak512(value: Uint8Array): Uint8Array;\n/**\n * Returns ripemd160 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport declare function ripemd160(value: Uint8Array): Uint8Array;\n/**\n * Recovers an ECDSA signer address from a 32-byte message hash and a corresponding\n * signature along with v recovery byte. Takes in an additional flag to check for\n * malleability of the signature which is generally only ideal for transactions.\n *\n * @param hash - 32-byte message hash\n * @param sig - signature\n * @param v - number of recovery byte\n * @param malleabilityFlag - whether to check malleability\n * @returns 64 bytes representing the public key if the recovery was successful.\n */\nexport declare function ecrecover(hash: Uint8Array, sig: Uint8Array, v: number, malleabilityFlag: number): Uint8Array | null;\n/**\n * Panic the transaction execution with given message\n * @param msg - panic message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport declare function panicUtf8(msg: Uint8Array): never;\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport declare function logUtf8(msg: Uint8Array): void;\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-16 sequence\n */\nexport declare function logUtf16(msg: Uint8Array): void;\n/**\n * Returns the number of staked NEAR of given validator, in yoctoNEAR\n * @param accountId - validator's AccountID\n * @returns - staked amount\n */\nexport declare function validatorStake(accountId: string): bigint;\n/**\n * Returns the number of staked NEAR of all validators, in yoctoNEAR\n * @returns total staked amount\n */\nexport declare function validatorTotalStake(): bigint;\n/**\n * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \\sum_i\n * mul_i g_{1 i} should be equal result.\n *\n * @param value - sequence of (g1:G1, fr:Fr), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * `value` is encoded as packed, little-endian\n * `[((u256, u256), u256)]` slice.\n *\n * @returns multi exp sum\n */\nexport declare function altBn128G1Multiexp(value: Uint8Array): Uint8Array;\n/**\n * Computes sum for signed g1 group elements on alt_bn128 curve \\sum_i\n * (-1)^{sign_i} g_{1 i} should be equal result.\n *\n * @param value - sequence of (sign:bool, g1:G1), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns sum over Fq.\n */\nexport declare function altBn128G1Sum(value: Uint8Array): Uint8Array;\n/**\n * Computes pairing check on alt_bn128 curve.\n * \\sum_i e(g_{1 i}, g_{2 i}) should be equal one (in additive notation), e(g1, g2) is Ate pairing\n *\n * @param value - sequence of (g1:G1, g2:G2), where\n * G2 is Fr-ordered subgroup point (x:Fq2, y:Fq2) on alt_bn128 twist,\n * alt_bn128 twist is Y^2 = X^3 + 3/(i+9) curve over Fq2\n * Fq2 is complex field element (re: Fq, im: Fq)\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq\n * `value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns whether pairing check pass\n */\nexport declare function altBn128PairingCheck(value: Uint8Array): boolean;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/api.js",
    "content": "import { assert, str, encode, decode, } from \"./utils\";\nimport { PromiseResult } from \"./types\";\nconst U64_MAX = 2n ** 64n - 1n;\nconst EVICTED_REGISTER = U64_MAX - 1n;\n/**\n * Logs parameters in the NEAR WASM virtual machine.\n *\n * @param params - Parameters to log.\n */\nexport function log(...params) {\n    env.log(params.reduce((accumulated, parameter, index) => {\n        // Stringify undefined\n        const param = parameter === undefined ? \"undefined\" : parameter;\n        // Convert Objects to strings and convert to string\n        const stringified = typeof param === \"object\" ? JSON.stringify(param) : `${param}`;\n        if (index === 0) {\n            return stringified;\n        }\n        return `${accumulated} ${stringified}`;\n    }, \"\"));\n}\n/**\n * Returns the account ID of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport function signerAccountId() {\n    env.signer_account_id(0);\n    return str(env.read_register(0));\n}\n/**\n * Returns the public key of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport function signerAccountPk() {\n    env.signer_account_pk(0);\n    return env.read_register(0);\n}\n/**\n * Returns the account ID of the account that called the function.\n * Can only be called in a call or initialize function.\n */\nexport function predecessorAccountId() {\n    env.predecessor_account_id(0);\n    return str(env.read_register(0));\n}\n/**\n * Returns the account ID of the current contract - the contract that is being executed.\n */\nexport function currentAccountId() {\n    env.current_account_id(0);\n    return str(env.read_register(0));\n}\n/**\n * Returns the current block index.\n */\nexport function blockIndex() {\n    return env.block_index();\n}\n/**\n * Returns the current block height.\n */\nexport function blockHeight() {\n    return blockIndex();\n}\n/**\n * Returns the current block timestamp.\n */\nexport function blockTimestamp() {\n    return env.block_timestamp();\n}\n/**\n * Returns the current epoch height.\n */\nexport function epochHeight() {\n    return env.epoch_height();\n}\n/**\n * Returns the amount of NEAR attached to this function call.\n * Can only be called in payable functions.\n */\nexport function attachedDeposit() {\n    return env.attached_deposit();\n}\n/**\n * Returns the amount of Gas that was attached to this function call.\n */\nexport function prepaidGas() {\n    return env.prepaid_gas();\n}\n/**\n * Returns the amount of Gas that has been used by this function call until now.\n */\nexport function usedGas() {\n    return env.used_gas();\n}\n/**\n * Returns the current account's account balance.\n */\nexport function accountBalance() {\n    return env.account_balance();\n}\n/**\n * Returns the current account's locked balance.\n */\nexport function accountLockedBalance() {\n    return env.account_locked_balance();\n}\n/**\n * Reads the value from NEAR storage that is stored under the provided key.\n *\n * @param key - The key to read from storage.\n */\nexport function storageReadRaw(key) {\n    const returnValue = env.storage_read(key, 0);\n    if (returnValue !== 1n) {\n        return null;\n    }\n    return env.read_register(0);\n}\n/**\n * Reads the utf-8 string value from NEAR storage that is stored under the provided key.\n *\n * @param key - The utf-8 string key to read from storage.\n */\nexport function storageRead(key) {\n    const ret = storageReadRaw(encode(key));\n    if (ret !== null) {\n        return decode(ret);\n    }\n    return null;\n}\n/**\n * Checks for the existence of a value under the provided key in NEAR storage.\n *\n * @param key - The key to check for in storage.\n */\nexport function storageHasKeyRaw(key) {\n    return env.storage_has_key(key) === 1n;\n}\n/**\n * Checks for the existence of a value under the provided utf-8 string key in NEAR storage.\n *\n * @param key - The utf-8 string key to check for in storage.\n */\nexport function storageHasKey(key) {\n    return storageHasKeyRaw(encode(key));\n}\n/**\n * Get the last written or removed value from NEAR storage.\n */\nexport function storageGetEvictedRaw() {\n    return env.read_register(EVICTED_REGISTER);\n}\n/**\n * Get the last written or removed value from NEAR storage as utf-8 string.\n */\nexport function storageGetEvicted() {\n    return decode(storageGetEvictedRaw());\n}\n/**\n * Returns the current accounts NEAR storage usage.\n */\nexport function storageUsage() {\n    return env.storage_usage();\n}\n/**\n * Writes the provided bytes to NEAR storage under the provided key.\n *\n * @param key - The key under which to store the value.\n * @param value - The value to store.\n */\nexport function storageWriteRaw(key, value) {\n    return env.storage_write(key, value, EVICTED_REGISTER) === 1n;\n}\n/**\n * Writes the provided utf-8 string to NEAR storage under the provided key.\n *\n * @param key - The utf-8 string key under which to store the value.\n * @param value - The utf-8 string value to store.\n */\nexport function storageWrite(key, value) {\n    return storageWriteRaw(encode(key), encode(value));\n}\n/**\n * Removes the value of the provided key from NEAR storage.\n *\n * @param key - The key to be removed.\n */\nexport function storageRemoveRaw(key) {\n    return env.storage_remove(key, EVICTED_REGISTER) === 1n;\n}\n/**\n * Removes the value of the provided utf-8 string key from NEAR storage.\n *\n * @param key - The utf-8 string key to be removed.\n */\nexport function storageRemove(key) {\n    return storageRemoveRaw(encode(key));\n}\n/**\n * Returns the cost of storing 0 Byte on NEAR storage.\n */\nexport function storageByteCost() {\n    return 10000000000000000000n;\n}\n/**\n * Returns the arguments passed to the current smart contract call.\n */\nexport function inputRaw() {\n    env.input(0);\n    return env.read_register(0);\n}\n/**\n * Returns the arguments passed to the current smart contract call as utf-8 string.\n */\nexport function input() {\n    return decode(inputRaw());\n}\n/**\n * Returns the value from the NEAR WASM virtual machine.\n *\n * @param value - The value to return.\n */\nexport function valueReturnRaw(value) {\n    env.value_return(value);\n}\n/**\n * Returns the utf-8 string value from the NEAR WASM virtual machine.\n *\n * @param value - The utf-8 string value to return.\n */\nexport function valueReturn(value) {\n    valueReturnRaw(encode(value));\n}\n/**\n * Returns a random string of bytes.\n */\nexport function randomSeed() {\n    env.random_seed(0);\n    return env.read_register(0);\n}\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport function promiseCreateRaw(accountId, methodName, args, amount, gas) {\n    return env.promise_create(accountId, methodName, args, amount, gas);\n}\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport function promiseCreate(accountId, methodName, args, amount, gas) {\n    return promiseCreateRaw(accountId, methodName, encode(args), amount, gas);\n}\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseThenRaw(promiseIndex, accountId, methodName, args, amount, gas) {\n    return env.promise_then(promiseIndex, accountId, methodName, args, amount, gas);\n}\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseThen(promiseIndex, accountId, methodName, args, amount, gas) {\n    return promiseThenRaw(promiseIndex, accountId, methodName, encode(args), amount, gas);\n}\n/**\n * Join an arbitrary array of NEAR promises.\n *\n * @param promiseIndexes - An arbitrary array of NEAR promise indexes to join.\n */\nexport function promiseAnd(...promiseIndexes) {\n    return env.promise_and(...promiseIndexes);\n}\n/**\n * Create a NEAR promise which will have multiple promise actions inside.\n *\n * @param accountId - The account ID of the target contract.\n */\nexport function promiseBatchCreate(accountId) {\n    return env.promise_batch_create(accountId);\n}\n/**\n * Attach a callback NEAR promise to a batch of NEAR promise actions.\n *\n * @param promiseIndex - The NEAR promise index of the batch.\n * @param accountId - The account ID of the target contract.\n */\nexport function promiseBatchThen(promiseIndex, accountId) {\n    return env.promise_batch_then(promiseIndex, accountId);\n}\n/**\n * Attach a create account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a create account action to.\n */\nexport function promiseBatchActionCreateAccount(promiseIndex) {\n    env.promise_batch_action_create_account(promiseIndex);\n}\n/**\n * Attach a deploy contract promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a deploy contract action to.\n * @param code - The WASM byte code of the contract to be deployed.\n */\nexport function promiseBatchActionDeployContract(promiseIndex, code) {\n    env.promise_batch_action_deploy_contract(promiseIndex, code);\n}\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseBatchActionFunctionCallRaw(promiseIndex, methodName, args, amount, gas) {\n    env.promise_batch_action_function_call(promiseIndex, methodName, args, amount, gas);\n}\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseBatchActionFunctionCall(promiseIndex, methodName, args, amount, gas) {\n    promiseBatchActionFunctionCallRaw(promiseIndex, methodName, encode(args), amount, gas);\n}\n/**\n * Attach a transfer promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a transfer action to.\n * @param amount - The amount of NEAR to transfer.\n */\nexport function promiseBatchActionTransfer(promiseIndex, amount) {\n    env.promise_batch_action_transfer(promiseIndex, amount);\n}\n/**\n * Attach a stake promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a stake action to.\n * @param amount - The amount of NEAR to stake.\n * @param publicKey - The public key with which to stake.\n */\nexport function promiseBatchActionStake(promiseIndex, amount, publicKey) {\n    env.promise_batch_action_stake(promiseIndex, amount, publicKey);\n}\n/**\n * Attach a add full access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add full access key action to.\n * @param publicKey - The public key to add as a full access key.\n * @param nonce - The nonce to use.\n */\nexport function promiseBatchActionAddKeyWithFullAccess(promiseIndex, publicKey, nonce) {\n    env.promise_batch_action_add_key_with_full_access(promiseIndex, publicKey, nonce);\n}\n/**\n * Attach a add access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add access key action to.\n * @param publicKey - The public key to add.\n * @param nonce - The nonce to use.\n * @param allowance - The allowance of the access key.\n * @param receiverId - The account ID of the receiver.\n * @param methodNames - The names of the method to allow the key for.\n */\nexport function promiseBatchActionAddKeyWithFunctionCall(promiseIndex, publicKey, nonce, allowance, receiverId, methodNames) {\n    env.promise_batch_action_add_key_with_function_call(promiseIndex, publicKey, nonce, allowance, receiverId, methodNames);\n}\n/**\n * Attach a delete key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete key action to.\n * @param publicKey - The public key to delete.\n */\nexport function promiseBatchActionDeleteKey(promiseIndex, publicKey) {\n    env.promise_batch_action_delete_key(promiseIndex, publicKey);\n}\n/**\n * Attach a delete account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete account action to.\n * @param beneficiaryId - The account ID of the beneficiary - the account that receives the remaining amount of NEAR.\n */\nexport function promiseBatchActionDeleteAccount(promiseIndex, beneficiaryId) {\n    env.promise_batch_action_delete_account(promiseIndex, beneficiaryId);\n}\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport function promiseBatchActionFunctionCallWeightRaw(promiseIndex, methodName, args, amount, gas, weight) {\n    env.promise_batch_action_function_call_weight(promiseIndex, methodName, args, amount, gas, weight);\n}\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport function promiseBatchActionFunctionCallWeight(promiseIndex, methodName, args, amount, gas, weight) {\n    promiseBatchActionFunctionCallWeightRaw(promiseIndex, methodName, encode(args), amount, gas, weight);\n}\n/**\n * The number of promise results available.\n */\nexport function promiseResultsCount() {\n    return env.promise_results_count();\n}\n/**\n * Returns the result of the NEAR promise for the passed promise index.\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport function promiseResultRaw(promiseIndex) {\n    const status = env.promise_result(promiseIndex, 0);\n    assert(Number(status) === PromiseResult.Successful, `Promise result ${status == PromiseResult.Failed\n        ? \"Failed\"\n        : status == PromiseResult.NotReady\n            ? \"NotReady\"\n            : status}`);\n    return env.read_register(0);\n}\n/**\n * Returns the result of the NEAR promise for the passed promise index as utf-8 string\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport function promiseResult(promiseIndex) {\n    return decode(promiseResultRaw(promiseIndex));\n}\n/**\n * Executes the promise in the NEAR WASM virtual machine.\n *\n * @param promiseIndex - The index of the promise to execute.\n */\nexport function promiseReturn(promiseIndex) {\n    env.promise_return(promiseIndex);\n}\n/**\n * Returns sha256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function sha256(value) {\n    env.sha256(value, 0);\n    return env.read_register(0);\n}\n/**\n * Returns keccak256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function keccak256(value) {\n    env.keccak256(value, 0);\n    return env.read_register(0);\n}\n/**\n * Returns keccak512 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function keccak512(value) {\n    env.keccak512(value, 0);\n    return env.read_register(0);\n}\n/**\n * Returns ripemd160 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function ripemd160(value) {\n    env.ripemd160(value, 0);\n    return env.read_register(0);\n}\n/**\n * Recovers an ECDSA signer address from a 32-byte message hash and a corresponding\n * signature along with v recovery byte. Takes in an additional flag to check for\n * malleability of the signature which is generally only ideal for transactions.\n *\n * @param hash - 32-byte message hash\n * @param sig - signature\n * @param v - number of recovery byte\n * @param malleabilityFlag - whether to check malleability\n * @returns 64 bytes representing the public key if the recovery was successful.\n */\nexport function ecrecover(hash, sig, v, malleabilityFlag) {\n    const returnValue = env.ecrecover(hash, sig, v, malleabilityFlag, 0);\n    if (returnValue === 0n) {\n        return null;\n    }\n    return env.read_register(0);\n}\n// NOTE: \"env.panic(msg)\" is not exported, use \"throw Error(msg)\" instead\n/**\n * Panic the transaction execution with given message\n * @param msg - panic message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport function panicUtf8(msg) {\n    env.panic_utf8(msg);\n}\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport function logUtf8(msg) {\n    env.log_utf8(msg);\n}\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-16 sequence\n */\nexport function logUtf16(msg) {\n    env.log_utf16(msg);\n}\n/**\n * Returns the number of staked NEAR of given validator, in yoctoNEAR\n * @param accountId - validator's AccountID\n * @returns - staked amount\n */\nexport function validatorStake(accountId) {\n    return env.validator_stake(accountId);\n}\n/**\n * Returns the number of staked NEAR of all validators, in yoctoNEAR\n * @returns total staked amount\n */\nexport function validatorTotalStake() {\n    return env.validator_total_stake();\n}\n/**\n * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \\sum_i\n * mul_i g_{1 i} should be equal result.\n *\n * @param value - sequence of (g1:G1, fr:Fr), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * `value` is encoded as packed, little-endian\n * `[((u256, u256), u256)]` slice.\n *\n * @returns multi exp sum\n */\nexport function altBn128G1Multiexp(value) {\n    env.alt_bn128_g1_multiexp(value, 0);\n    return env.read_register(0);\n}\n/**\n * Computes sum for signed g1 group elements on alt_bn128 curve \\sum_i\n * (-1)^{sign_i} g_{1 i} should be equal result.\n *\n * @param value - sequence of (sign:bool, g1:G1), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns sum over Fq.\n */\nexport function altBn128G1Sum(value) {\n    env.alt_bn128_g1_sum(value, 0);\n    return env.read_register(0);\n}\n/**\n * Computes pairing check on alt_bn128 curve.\n * \\sum_i e(g_{1 i}, g_{2 i}) should be equal one (in additive notation), e(g1, g2) is Ate pairing\n *\n * @param value - sequence of (g1:G1, g2:G2), where\n * G2 is Fr-ordered subgroup point (x:Fq2, y:Fq2) on alt_bn128 twist,\n * alt_bn128 twist is Y^2 = X^3 + 3/(i+9) curve over Fq2\n * Fq2 is complex field element (re: Fq, im: Fq)\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq\n * `value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns whether pairing check pass\n */\nexport function altBn128PairingCheck(value) {\n    return env.alt_bn128_pairing_check(value) === 1n;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/abi.d.ts",
    "content": "import * as abi from \"near-abi\";\nexport declare function runAbiCompilerPlugin(tsFile: string, packageJsonPath: string, tsConfigJsonPath: string): abi.AbiRoot;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/abi.js",
    "content": "import ts from \"typescript\";\nimport JSON5 from 'json5';\nimport * as abi from \"near-abi\";\nimport * as TJS from \"near-typescript-json-schema\";\nimport * as fs from \"fs\";\nimport { LIB_VERSION } from \"../version.js\";\nfunction parseMetadata(packageJsonPath) {\n    const packageJson = JSON5.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n    let authors = [];\n    if (packageJson[\"author\"])\n        authors.push(packageJson[\"author\"]);\n    authors = authors.concat(packageJson[\"contributors\"] || []);\n    return {\n        name: packageJson[\"name\"],\n        version: packageJson[\"version\"],\n        authors,\n        build: {\n            compiler: \"tsc \" + ts.version,\n            builder: \"near-sdk-js \" + LIB_VERSION,\n        },\n    };\n}\nfunction getProgramFromFiles(files, jsonCompilerOptions, basePath = \"./\") {\n    const { options, errors } = ts.convertCompilerOptionsFromJson(jsonCompilerOptions, basePath);\n    if (errors.length > 0) {\n        errors.forEach((error) => {\n            console.log(error.messageText);\n        });\n        throw Error(\"Invalid compiler options\");\n    }\n    return ts.createProgram(files, options);\n}\nfunction validateNearClass(node) {\n    if (node.kind !== ts.SyntaxKind.ClassDeclaration) {\n        throw Error(\"Expected NEAR function to be inside of a class\");\n    }\n    const classDeclaration = node;\n    const decorators = classDeclaration.decorators || [];\n    const containsNearBindgen = decorators.some((decorator) => {\n        if (decorator.expression.kind !== ts.SyntaxKind.CallExpression)\n            return false;\n        const decoratorExpression = decorator.expression;\n        if (decoratorExpression.expression.kind !== ts.SyntaxKind.Identifier)\n            return false;\n        const decoratorIdentifier = decoratorExpression.expression;\n        const decoratorName = decoratorIdentifier.text;\n        return decoratorName === \"NearBindgen\";\n    });\n    if (!containsNearBindgen) {\n        throw Error(\"Expected NEAR function to be inside of a class decorated with @NearBindgen\");\n    }\n}\nexport function runAbiCompilerPlugin(tsFile, packageJsonPath, tsConfigJsonPath) {\n    const tsConfig = JSON5.parse(fs.readFileSync(tsConfigJsonPath, \"utf8\"));\n    const program = getProgramFromFiles([tsFile], tsConfig[\"compilerOptions\"]);\n    const typeChecker = program.getTypeChecker();\n    const diagnostics = ts.getPreEmitDiagnostics(program);\n    if (diagnostics.length > 0) {\n        diagnostics.forEach((diagnostic) => {\n            const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\");\n            if (diagnostic.file && diagnostic.start) {\n                const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n                console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);\n            }\n            else {\n                console.error(message);\n            }\n        });\n        throw Error(\"Failed to compile the contract\");\n    }\n    const generator = TJS.buildGenerator(program);\n    if (!generator) {\n        throw Error(\"Failed to generate ABI due to an unexpected typescript-json-schema error. Please report this.\");\n    }\n    const abiFunctions = [];\n    program.getSourceFiles().forEach((sourceFile, _sourceFileIdx) => {\n        function inspect(node, tc) {\n            if (node.kind === ts.SyntaxKind.MethodDeclaration) {\n                const methodDeclaration = node;\n                const decorators = methodDeclaration.decorators ||\n                    [];\n                let isCall = false;\n                let isView = false;\n                let isInit = false;\n                const abiModifiers = [];\n                decorators.forEach((decorator) => {\n                    if (decorator.expression.kind !== ts.SyntaxKind.CallExpression)\n                        return;\n                    const decoratorExpression = decorator.expression;\n                    if (decoratorExpression.expression.kind !== ts.SyntaxKind.Identifier)\n                        return;\n                    const decoratorIdentifier = decoratorExpression.expression;\n                    const decoratorName = decoratorIdentifier.text;\n                    if (decoratorName === \"call\") {\n                        isCall = true;\n                        decoratorExpression.arguments.forEach((arg) => {\n                            if (arg.kind !== ts.SyntaxKind.ObjectLiteralExpression)\n                                return;\n                            const objLiteral = arg;\n                            objLiteral.properties.forEach((prop) => {\n                                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                                const propName = prop.name.text;\n                                if (propName === \"privateFunction\") {\n                                    if (prop.kind !== ts.SyntaxKind.PropertyAssignment)\n                                        return;\n                                    const propAssignment = prop;\n                                    const init = propAssignment.initializer;\n                                    if (init.kind === ts.SyntaxKind.TrueKeyword) {\n                                        abiModifiers.push(abi.AbiFunctionModifier.Private);\n                                    }\n                                    else if (init.kind === ts.SyntaxKind.FalseKeyword) {\n                                        // Do nothing\n                                    }\n                                    else {\n                                        throw Error(\"Unexpected initializer for `privateFunction`: kind \" +\n                                            init.kind);\n                                    }\n                                }\n                                if (propName === \"payableFunction\") {\n                                    if (prop.kind !== ts.SyntaxKind.PropertyAssignment)\n                                        return;\n                                    const propAssignment = prop;\n                                    const init = propAssignment.initializer;\n                                    if (init.kind === ts.SyntaxKind.TrueKeyword) {\n                                        abiModifiers.push(abi.AbiFunctionModifier.Payable);\n                                    }\n                                    else if (init.kind === ts.SyntaxKind.FalseKeyword) {\n                                        // Do nothing\n                                    }\n                                    else {\n                                        throw Error(\"Unexpected initializer for `publicFunction`: kind \" +\n                                            init.kind);\n                                    }\n                                }\n                            });\n                        });\n                    }\n                    if (decoratorName === \"view\")\n                        isView = true;\n                    if (decoratorName === \"initialize\") {\n                        isInit = true;\n                        abiModifiers.push(abi.AbiFunctionModifier.Init);\n                    }\n                });\n                const nearDecoratorsCount = [isCall, isView, isInit].filter((b) => b).length;\n                if (nearDecoratorsCount > 1) {\n                    throw Error(\"NEAR function cannot be init, call and view at the same time\");\n                }\n                if (nearDecoratorsCount === 0) {\n                    return;\n                }\n                validateNearClass(node.parent);\n                let abiParams = [];\n                if (methodDeclaration.parameters.length > 1) {\n                    throw Error(\"Expected NEAR function to have a single object parameter, but got \" +\n                        methodDeclaration.parameters.length);\n                }\n                else if (methodDeclaration.parameters.length === 1) {\n                    const jsonObjectParameter = methodDeclaration.parameters[0];\n                    if (!jsonObjectParameter.type) {\n                        throw Error(\"Expected NEAR function to have explicit types, e.g. `{ id }: {id : string }`\");\n                    }\n                    if (jsonObjectParameter.type.kind !== ts.SyntaxKind.TypeLiteral) {\n                        throw Error(\"Expected NEAR function to have a single object binding parameter, e.g. `{ id }: { id: string }`\");\n                    }\n                    const typeLiteral = jsonObjectParameter.type;\n                    abiParams = typeLiteral.members.map((member) => {\n                        if (member.kind !== ts.SyntaxKind.PropertySignature) {\n                            throw Error(\"Expected NEAR function to have a single object binding parameter, e.g. `{ id }: { id: string }`\");\n                        }\n                        const propertySignature = member;\n                        const nodeType = tc.getTypeAtLocation(propertySignature.type);\n                        const schema = generator.getTypeDefinition(nodeType, true);\n                        const abiParameter = {\n                            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                            name: propertySignature.name.text,\n                            type_schema: schema,\n                        };\n                        return abiParameter;\n                    });\n                }\n                let abiResult = undefined;\n                const returnType = methodDeclaration.type;\n                if (returnType) {\n                    const nodeType = tc.getTypeAtLocation(returnType);\n                    const schema = generator.getTypeDefinition(nodeType, true);\n                    abiResult = {\n                        serialization_type: abi.AbiSerializationType.Json,\n                        type_schema: schema,\n                    };\n                }\n                const abiFunction = {\n                    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                    name: methodDeclaration.name.text,\n                    kind: isView ? abi.AbiFunctionKind.View : abi.AbiFunctionKind.Call,\n                };\n                if (abiModifiers.length > 0) {\n                    abiFunction.modifiers = abiModifiers;\n                }\n                if (abiParams.length > 0) {\n                    abiFunction.params = {\n                        serialization_type: abi.AbiSerializationType.Json,\n                        args: abiParams,\n                    };\n                }\n                if (abiResult) {\n                    abiFunction.result = abiResult;\n                }\n                abiFunctions.push(abiFunction);\n            }\n            else {\n                ts.forEachChild(node, (n) => inspect(n, tc));\n            }\n        }\n        inspect(sourceFile, typeChecker);\n    });\n    const abiRoot = {\n        schema_version: abi.SCHEMA_VERSION,\n        metadata: parseMetadata(packageJsonPath),\n        body: {\n            functions: abiFunctions,\n            root_schema: generator.getSchemaForSymbol(\"String\", true, false),\n        },\n    };\n    return abiRoot;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/build-tools/include-bytes.d.ts",
    "content": "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",
    "content": "import * as t from \"@babel/types\";\nimport { readFileSync } from \"fs\";\nimport { join, dirname } from \"path\";\nconst assertStringLiteral = t.assertStringLiteral;\nexport default function () {\n    return {\n        visitor: {\n            CallExpression(path, { opts, file }) {\n                if (!(\"name\" in path.node.callee)) {\n                    return;\n                }\n                // Extract the called method name.\n                const name = path.node.callee.name;\n                // If the method name is not \"includeBytes\" do nothing.\n                if (name === \"includeBytes\") {\n                    // Extract the called method arguments.\n                    const args = path.node.arguments;\n                    // Get the path of file\n                    const filename = file.opts.filename;\n                    // User settings\n                    const root = opts.root || dirname(filename);\n                    // Read binary file into bytes, so encoding is 'latin1' (each byte is 0-255, become one character)\n                    const encoding = \"latin1\";\n                    const [firstArg] = args;\n                    // Require first arg to be a string literal\n                    assertStringLiteral(firstArg);\n                    // Error if filename is not found\n                    if (filename === undefined || filename === \"unknown\") {\n                        throw new Error(\"`includeBytes` function called outside of file\");\n                    }\n                    if (!(\"value\" in firstArg && typeof firstArg.value === \"string\")) {\n                        throw new Error(`\\`includeBytes\\` function called with invalid argument: ${args[0]}`);\n                    }\n                    // Generate and locate the file\n                    const fileRelPath = firstArg.value; // Get literal string value\n                    const filePath = join(root, fileRelPath);\n                    const fileSrc = readFileSync(filePath, { encoding }).toString();\n                    path.replaceWith(t.callExpression(t.memberExpression(t.identifier(\"env\"), t.identifier(\"latin1_string_to_uint8array\")), [t.stringLiteral(fileSrc)]));\n                }\n            },\n        },\n    };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.d.ts",
    "content": "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",
    "content": "import * as t from \"@babel/types\";\nimport signal from \"signale\";\nconst { Signale } = signal;\n/**\n * A list of supported method types/decorators.\n */\nconst methodTypes = [\"call\", \"view\", \"initialize\", \"migrate\"];\n/**\n * A helper function that inserts a new throw Error statement with\n * the passed message.\n *\n * @param message - The message to throw inside the error\n */\nfunction throwError(message) {\n    return t.blockStatement([\n        t.throwStatement(t.newExpression(t.identifier(\"Error\"), [t.stringLiteral(message)])),\n    ]);\n}\n/**\n * A helper function that inserts a new state reading expression.\n * It reads state into _\\_state_ via _\\_getState_.\n *\n * ```typescript\n * const _state = Contract._getState();\n * ```\n *\n * @param classId - The class ID of the class which we are extending.\n */\nfunction readState(classId, methodType) {\n    if (methodType === \"migrate\") {\n        return t.variableDeclaration(\"const\", [\n            t.variableDeclarator(t.identifier(\"_state\"), t.nullLiteral()),\n        ]);\n    }\n    return t.variableDeclaration(\"const\", [\n        t.variableDeclarator(t.identifier(\"_state\"), t.callExpression(t.memberExpression(classId, t.identifier(\"_getState\")), [])),\n    ]);\n}\n/**\n * A helper function that inserts a double initialization check.\n *\n * ```typescript\n * if (_state) {\n *   throw new Error('Contract already initialized');\n * }\n * ```\n *\n * @param methodType - The type of the method being called.\n */\nfunction preventDoubleInit(methodType) {\n    if (methodType !== \"initialize\") {\n        return t.emptyStatement();\n    }\n    return t.ifStatement(t.identifier(\"_state\"), throwError(\"Contract already initialized\"));\n}\n/**\n * A helper function that inserts a initialization check.\n *\n * ```typescript\n * if (!_state) {\n *   throw new Error('Contract must be initialized');\n * }\n * ```\n *\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n *\n * @returns {t.EmptyStatement | t.IfStatement}\n */\nfunction ensureInitBeforeCall(classId, methodType) {\n    if (![\"call\", \"view\"].includes(methodType)) {\n        return t.emptyStatement();\n    }\n    return t.ifStatement(t.logicalExpression(\"&&\", t.unaryExpression(\"!\", t.identifier(\"_state\")), t.callExpression(t.memberExpression(classId, t.identifier(\"_requireInit\")), [])), throwError(\"Contract must be initialized\"));\n}\n/**\n * A helper function that inserts a contract creation expression.\n * It creates a new instance of the class by calling the _\\_create_ method\n * on the contract class.\n *\n * ```typescript\n * let _contract = Contract._create();\n * ```\n *\n * @param classId - The class ID of the class being extended.\n */\nfunction initializeContractClass(classId) {\n    return t.variableDeclaration(\"const\", [\n        t.variableDeclarator(t.identifier(\"_contract\"), t.callExpression(t.memberExpression(classId, t.identifier(\"_create\")), [])),\n    ]);\n}\n/**\n * A helper function that inserts a state reconstruction statement.\n * It calls the _\\_reconstruct_ method on the _\\_contract_ object.\n *\n * ```typescript\n * if (_state) {\n *   Contract._reconstruct(_contract, _state);\n * }\n * ```\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n */\nfunction reconstructState(classId, methodType) {\n    if (![\"call\", \"view\"].includes(methodType)) {\n        return t.emptyStatement();\n    }\n    return t.ifStatement(t.identifier(\"_state\"), t.blockStatement([\n        t.expressionStatement(t.callExpression(t.memberExpression(classId, t.identifier(\"_reconstruct\")), [t.identifier(\"_contract\"), t.identifier(\"_state\")])),\n    ]));\n}\n/**\n * A helper function that inserts a argument collection expression.\n * It calls the _\\_getArgs_ function on the class object.\n *\n * ```typescript\n * const _args = Contract._getArgs();\n * ```\n * @param classId - The class ID of the class being extended.\n */\nfunction collectArguments(classId) {\n    return t.variableDeclaration(\"const\", [\n        t.variableDeclarator(t.identifier(\"_args\"), t.callExpression(t.memberExpression(classId, t.identifier(\"_getArgs\")), [])),\n    ]);\n}\n/**\n * A helper function that inserts a contract method call expression.\n * It calls the appropriate contract method and passes the collected _\\_args_.\n *\n * ```typescript\n * const _result = _contract.method(args);\n * ```\n *\n * @param methodName - The name of the method being called.\n */\nfunction callContractMethod(methodName) {\n    return t.variableDeclaration(\"const\", [\n        t.variableDeclarator(t.identifier(\"_result\"), t.callExpression(t.memberExpression(t.identifier(\"_contract\"), t.identifier(methodName)), [t.identifier(\"_args\")])),\n    ]);\n}\n/**\n * A helper function that inserts a save to storage expression.\n * It calls the _\\_saveToStorage_ method if a initialize or call method is called.\n *\n * ```typescript\n * Contract._saveToStorage(_contract);\n * ```\n *\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n */\nfunction saveToStorage(classId, methodType) {\n    if (![\"initialize\", \"call\", \"migrate\"].includes(methodType)) {\n        return t.emptyStatement();\n    }\n    return t.expressionStatement(t.callExpression(t.memberExpression(classId, t.identifier(\"_saveToStorage\")), [t.identifier(\"_contract\")]));\n}\n/**\n * A helper function that inserts a NearPromise execution call or a valuer return call.\n * It checks for the return type of the called function and either performs a NearPromise\n * _onReturn_ call or a _value\\_return_ environment function to return the value to the callee.\n *\n * ```typescript\n * if (_result !== undefined) {\n *   if (_result && _result.constructor && _result.constructor.name === 'NearPromise') {\n *     _result.onReturn();\n *   } else {\n *     near.valueReturnRaw(_contract._serialize(result));\n *   }\n * }\n * ```\n *\n * @param classId - The class ID of the class being extended.\n */\nfunction executePromise(classId) {\n    return t.ifStatement(t.binaryExpression(\"!==\", t.identifier(\"_result\"), t.identifier(\"undefined\")), t.ifStatement(t.logicalExpression(\"&&\", t.logicalExpression(\"&&\", t.identifier(\"_result\"), t.memberExpression(t.identifier(\"_result\"), t.identifier(\"constructor\"))), t.binaryExpression(\"===\", t.memberExpression(t.memberExpression(t.identifier(\"_result\"), t.identifier(\"constructor\")), t.identifier(\"name\")), t.stringLiteral(\"NearPromise\"))), t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(\"_result\"), t.identifier(\"onReturn\")), [])), t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(\"env\"), t.identifier(\"value_return\")), [\n        t.callExpression(t.memberExpression(classId, t.identifier(\"_serialize\")), [t.identifier(\"_result\"), t.booleanLiteral(true)]),\n    ]))));\n}\n/**\n * A helper function that inserts the overridden function declaration into the class.\n *\n * @param classId - The class ID of the class being extended.\n * @param methodName - The name of the method being called.\n * @param methodType - The type of the method being called.\n */\nfunction createDeclaration(classId, methodName, methodType) {\n    return t.exportNamedDeclaration(t.functionDeclaration(t.identifier(methodName), [], t.blockStatement([\n        // Read the state of the contract from storage.\n        // const _state = Contract._getState();\n        readState(classId, methodType),\n        // Throw if initialized on any subsequent init function calls.\n        // if (_state) { throw new Error('Contract already initialized'); }\n        preventDoubleInit(methodType),\n        // Throw if NOT initialized on any non init function calls.\n        // if (!_state) { throw new Error('Contract must be initialized'); }\n        ensureInitBeforeCall(classId, methodType),\n        // Create instance of contract by calling _create function.\n        // let _contract = Contract._create();\n        initializeContractClass(classId),\n        // Reconstruct the contract with the state if the state is valid.\n        // if (_state) { Contract._reconstruct(_contract, _state); }\n        reconstructState(classId, methodType),\n        // Collect the arguments sent to the function.\n        // const _args = Contract._getArgs();\n        collectArguments(classId),\n        // Perform the actual function call to the appropriate contract method.\n        // const _result = _contract.method(args);\n        callContractMethod(methodName),\n        // If the method called is either an initialize or call method type, save the changes to storage.\n        // Contract._saveToStorage(_contract);\n        saveToStorage(classId, methodType),\n        // If a NearPromise is returned from the function call the onReturn method to execute the promise.\n        // if (_result !== undefined)\n        //   if (_result && _result.constructor && _result.constructor.name === 'NearPromise')\n        //     _result.onReturn();\n        //   else\n        //     near.valueReturnRaw(_contract._serialize(result));\n        executePromise(classId),\n    ])));\n}\nexport default function () {\n    return {\n        visitor: {\n            ClassDeclaration(path, { opts: { verbose } }) {\n                // Capture the node of the current path.\n                const classNode = path.node;\n                // Check that the class is decorated with NearBindgen otherwise do nothing.\n                if (classNode.decorators &&\n                    \"callee\" in classNode.decorators[0].expression &&\n                    \"name\" in classNode.decorators[0].expression.callee &&\n                    classNode.decorators[0].expression.callee.name === \"NearBindgen\") {\n                    // Iterate over the children of the class node.\n                    classNode.body.body.forEach((child) => {\n                        // Check that the child is a class method and has decorators.\n                        if (child.type === \"ClassMethod\" &&\n                            child.kind === \"method\" &&\n                            child.decorators &&\n                            \"callee\" in child.decorators[0].expression &&\n                            \"name\" in child.decorators[0].expression.callee) {\n                            // Capture the decorator name.\n                            const methodType = child.decorators[0].expression.callee.name;\n                            // Check that the decorator is one of the supported method types.\n                            if (methodTypes.includes(methodType) && \"name\" in child.key) {\n                                // Insert the method override into the class declaration.\n                                path.insertAfter(createDeclaration(classNode.id, child.key.name, methodType));\n                                if (verbose) {\n                                    new Signale({\n                                        scope: \"near-bindgen-exporter\",\n                                    }).info(`Babel ${child.key.name} method export done.`);\n                                }\n                            }\n                        }\n                    });\n                }\n            },\n        },\n    };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/cli.d.ts",
    "content": "#!/usr/bin/env node\nexport declare function validateCom(source: string, { verbose }: {\n    verbose: boolean;\n}): Promise<void>;\nexport declare function checkTypescriptCom(source: string, { verbose }: {\n    verbose: boolean;\n}): Promise<void>;\nexport declare function generateAbi(source: string, target: string, packageJson: string, tsConfig: string, { verbose }: {\n    verbose: boolean;\n}): Promise<void>;\nexport declare function createJsFileWithRollupCom(source: string, target: string, { verbose }: {\n    verbose: boolean;\n}): Promise<void>;\nexport declare function transpileJsAndBuildWasmCom(target: string, { verbose }: {\n    verbose: boolean;\n}): Promise<void>;\nexport declare function buildCom(source: string, target: string, packageJson: string, tsConfig: string, { verbose, generateABI }: {\n    verbose: boolean;\n    generateABI: boolean;\n}): Promise<void>;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/cli.js",
    "content": "#!/usr/bin/env node\nimport fs from \"fs\";\nimport path, { basename, dirname } from \"path\";\nimport { nodeResolve } from \"@rollup/plugin-node-resolve\";\nimport sourcemaps from \"rollup-plugin-sourcemaps\";\nimport { babel } from \"@rollup/plugin-babel\";\nimport { rollup } from \"rollup\";\nimport { Command } from \"commander\";\nimport signal from \"signale\";\nimport { executeCommand, validateContract } from \"./utils.js\";\nimport { runAbiCompilerPlugin } from \"./abi.js\";\nconst { Signale } = signal;\nconst PROJECT_DIR = process.cwd();\nconst NEAR_SDK_JS = \"node_modules/near-sdk-js\";\nconst TSC = \"node_modules/.bin/tsc\";\nconst QJSC_DIR = `${NEAR_SDK_JS}/lib/cli/deps/quickjs`;\nconst QJSC = `${NEAR_SDK_JS}/lib/cli/deps/qjsc`;\nconst program = new Command();\nprogram\n    .name(\"near-sdk-js\")\n    .addCommand(new Command(\"build\")\n    .usage(\"[source] [target]\")\n    .description(\"Build NEAR JS Smart-contract\")\n    .argument(\"[source]\", \"Contract to build.\", \"src/index.js\")\n    .argument(\"[target]\", \"Target file path and name.\", \"build/contract.wasm\")\n    .argument(\"[packageJson]\", \"Target file path and name.\", \"package.json\")\n    .argument(\"[tsConfig]\", \"Target file path and name.\", \"tsconfig.json\")\n    .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n    .option(\"--generateABI\", \"Whether to generate ABI.\", false)\n    .action(buildCom))\n    .addCommand(new Command(\"validateContract\")\n    .usage(\"[source]\")\n    .description(\"Validate a NEAR JS Smart-contract. Validates the contract by checking that all parameters are initialized in the constructor. Works only for typescript.\")\n    .argument(\"[source]\", \"Contract to validate.\", \"src/index.ts\")\n    .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n    .action(validateCom))\n    .addCommand(new Command(\"checkTypescript\")\n    .usage(\"[source]\")\n    .description(\"Run TSC with some cli flags - warning - ignores tsconfig.json.\")\n    .argument(\"[source]\", \"Typescript file to validate\", \"src/index.ts\")\n    .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n    .action(checkTypescriptCom))\n    .addCommand(new Command(\"createJsFileWithRollup\")\n    .usage(\"[source] [target]\")\n    .description(\"Create intermediate javascript file for later processing with QJSC\")\n    .argument(\"[source]\", \"Contract to build.\", \"src/index.js\")\n    .argument(\"[target]\", \"Target file path and name. The default corresponds to contract.js\", \"build/contract.wasm\")\n    .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n    .action(createJsFileWithRollupCom))\n    .addCommand(new Command(\"transpileJsAndBuildWasm\")\n    .usage(\"[source] [target]\")\n    .description(\"Transpiles the target javascript file into .c and .h using QJSC then compiles that into wasm using clang\")\n    .argument(\"[target]\", \"Target file path and name. The js file must correspond to the same path with the js extension.\", \"build/contract.wasm\")\n    .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n    .action(transpileJsAndBuildWasmCom))\n    .parse();\nfunction getTargetDir(target) {\n    return dirname(target);\n}\nfunction getTargetExt(target) {\n    return target.split(\".\").pop();\n}\nfunction getTargetFileName(target) {\n    return basename(target, `.${getTargetExt(target)}`);\n}\nfunction getRollupTarget(target) {\n    return `${getTargetDir(target)}/${getTargetFileName(target)}.js`;\n}\nfunction getQjscTarget(target) {\n    return `${getTargetDir(target)}/${getTargetFileName(target)}.h`;\n}\nfunction getContractTarget(target) {\n    return `${getTargetDir(target)}/${getTargetFileName(target)}.wasm`;\n}\nfunction getContractAbi(target) {\n    return `${getTargetDir(target)}/${getTargetFileName(target)}-abi.json`;\n}\nfunction requireTargetExt(target) {\n    if (getTargetExt(target) === \"wasm\") {\n        return;\n    }\n    signal.error(`Unsupported target ${getTargetExt(target)}, make sure target ends with .wasm!`);\n    process.exit(1);\n}\nfunction ensureTargetDirExists(target) {\n    const targetDir = getTargetDir(target);\n    if (fs.existsSync(targetDir)) {\n        return;\n    }\n    signal.await(`Creating ${targetDir} directory...`);\n    fs.mkdirSync(targetDir, {});\n}\nexport async function validateCom(source, { verbose = false }) {\n    const signale = new Signale({ scope: \"validate\", interactive: !verbose });\n    signale.await(`Validating ${source} contract...`);\n    if (!(await validateContract(source, verbose))) {\n        process.exit(1);\n    }\n}\nexport async function checkTypescriptCom(source, { verbose = false }) {\n    const signale = new Signale({\n        scope: \"checkTypescript\",\n        interactive: !verbose,\n    });\n    const sourceExt = source.split(\".\").pop();\n    if (sourceExt !== \"ts\") {\n        signale.info(`Source file is not a typescript file ${source}`);\n        return;\n    }\n    signale.await(`Typechecking ${source} with tsc...`);\n    await checkTsBuildWithTsc(source, verbose);\n}\nexport async function generateAbi(source, target, packageJson, tsConfig, { verbose = false }) {\n    const signale = new Signale({ scope: \"generateAbi\", interactive: !verbose });\n    const sourceExt = source.split(\".\").pop();\n    if (sourceExt !== \"ts\") {\n        signale.info(`Skipping ABI generation as source file is not a typescript file ${source}`);\n        return;\n    }\n    signale.await(\"Generating ABI...\");\n    const abi = runAbiCompilerPlugin(source, packageJson, tsConfig);\n    fs.writeFileSync(getContractAbi(target), JSON.stringify(abi, null, 2));\n    signale.success(`Generated ${getContractAbi(target)} ABI successfully!`);\n}\nexport async function createJsFileWithRollupCom(source, target, { verbose = false }) {\n    const signale = new Signale({\n        scope: \"createJsFileWithRollup\",\n        interactive: !verbose,\n    });\n    requireTargetExt(target);\n    ensureTargetDirExists(target);\n    signale.await(`Creating ${source} file with Rollup...`);\n    await createJsFileWithRullup(source, getRollupTarget(target), verbose);\n}\nexport async function transpileJsAndBuildWasmCom(target, { verbose = false }) {\n    const signale = new Signale({\n        scope: \"transpileJsAndBuildWasm\",\n        interactive: !verbose,\n    });\n    requireTargetExt(target);\n    ensureTargetDirExists(target);\n    signale.await(`Creating ${getQjscTarget(target)} file with QJSC...`);\n    await createHeaderFileWithQjsc(getRollupTarget(target), getQjscTarget(target), verbose);\n    signale.await(\"Generating methods.h file...\");\n    await createMethodsHeaderFile(getRollupTarget(target), verbose);\n    signale.await(`Creating ${getContractTarget(target)} contract...`);\n    await createWasmContract(getQjscTarget(target), getContractTarget(target), verbose);\n    signale.await(\"Executing wasi-stub...\");\n    await wasiStubContract(getContractTarget(target), verbose);\n    signale.success(`Generated ${getContractTarget(target)} contract successfully!`);\n}\nexport async function buildCom(source, target, packageJson, tsConfig, { verbose = false, generateABI = false }) {\n    const signale = new Signale({ scope: \"build\", interactive: !verbose });\n    requireTargetExt(target);\n    signale.await(`Building ${source} contract...`);\n    await checkTypescriptCom(source, { verbose });\n    ensureTargetDirExists(target);\n    if (generateABI) {\n        await generateAbi(source, target, packageJson, tsConfig, { verbose });\n    }\n    await validateCom(source, { verbose });\n    await createJsFileWithRollupCom(source, target, { verbose });\n    await transpileJsAndBuildWasmCom(target, { verbose });\n}\nasync function checkTsBuildWithTsc(sourceFileWithPath, verbose = false) {\n    await executeCommand(`${TSC} --noEmit --skipLibCheck --experimentalDecorators --target es2020 --moduleResolution node ${sourceFileWithPath}`, verbose);\n}\n// Common build function\nasync function createJsFileWithRullup(sourceFileWithPath, rollupTarget, verbose = false) {\n    const bundle = await rollup({\n        input: sourceFileWithPath,\n        plugins: [\n            nodeResolve({\n                extensions: [\".js\", \".ts\"],\n            }),\n            sourcemaps(),\n            // commonjs(),\n            babel({\n                babelHelpers: \"bundled\",\n                extensions: [\".ts\", \".js\", \".jsx\", \".es6\", \".es\", \".mjs\"],\n                presets: [\"@babel/preset-typescript\"],\n                plugins: [\n                    \"near-sdk-js/lib/cli/build-tools/include-bytes.js\",\n                    [\n                        \"near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js\",\n                        { verbose },\n                    ],\n                    [\"@babel/plugin-proposal-decorators\", { version: \"legacy\" }],\n                ],\n            }),\n        ],\n    });\n    await bundle.write({\n        sourcemap: true,\n        file: rollupTarget,\n        format: \"es\",\n    });\n}\nasync function createHeaderFileWithQjsc(rollupTarget, qjscTarget, verbose = false) {\n    await executeCommand(`${QJSC} -c -m -o ${qjscTarget} -N code ${rollupTarget}`, verbose);\n}\nasync function createMethodsHeaderFile(rollupTarget, verbose = false) {\n    const buildPath = path.dirname(rollupTarget);\n    if (verbose) {\n        new Signale({ scope: \"method-header\" }).info(rollupTarget);\n    }\n    const mod = await import(`${PROJECT_DIR}/${rollupTarget}`);\n    const exportNames = Object.keys(mod);\n    if (exportNames.includes('panic')) {\n        signal.error(\"'panic' is a reserved word, please use another name for contract method\");\n        process.exit(1);\n    }\n    const methods = exportNames.reduce((result, key) => `${result}DEFINE_NEAR_METHOD(${key})\\n`, \"\");\n    fs.writeFileSync(`${buildPath}/methods.h`, methods);\n}\nasync function createWasmContract(qjscTarget, contractTarget, verbose = false) {\n    const WASI_SDK_PATH = `${NEAR_SDK_JS}/lib/cli/deps/wasi-sdk`;\n    const CC = `${WASI_SDK_PATH}/bin/clang --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot`;\n    const DEFS = `-D_GNU_SOURCE '-DCONFIG_VERSION=\"2021-03-27\"' -DCONFIG_BIGNUM`;\n    const INCLUDES = `-I${QJSC_DIR} -I.`;\n    const ORIGINAL_BUILDER_PATH = `${NEAR_SDK_JS}/builder/builder.c`;\n    const NEW_BUILDER_PATH = `${path.dirname(contractTarget)}/builder.c`;\n    const SOURCES = `${NEW_BUILDER_PATH} ${QJSC_DIR}/quickjs.c ${QJSC_DIR}/libregexp.c ${QJSC_DIR}/libunicode.c ${QJSC_DIR}/cutils.c ${QJSC_DIR}/quickjs-libc-min.c ${QJSC_DIR}/libbf.c`;\n    const LIBS = `-lm`;\n    // copying builder.c file to the build folder\n    fs.cpSync(ORIGINAL_BUILDER_PATH, NEW_BUILDER_PATH);\n    fs.renameSync(qjscTarget, \"build/code.h\");\n    await executeCommand(`${CC} --target=wasm32-wasi -nostartfiles -Oz -flto ${DEFS} ${INCLUDES} ${SOURCES} ${LIBS} -Wl,--no-entry -Wl,--allow-undefined -Wl,-z,stack-size=${256 * 1024} -Wl,--lto-O3 -o ${contractTarget}`, verbose);\n}\nasync function wasiStubContract(contractTarget, verbose = false) {\n    const WASI_STUB = `${NEAR_SDK_JS}/lib/cli/deps/binaryen/wasi-stub/run.sh`;\n    await executeCommand(`${WASI_STUB} ${contractTarget}`, verbose);\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/post-install.d.ts",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/post-install.js",
    "content": "import { executeCommand, download } from \"./utils.js\";\nimport signal from \"signale\";\nimport os from \"os\";\nimport fs from \"fs\";\nconst { Signale } = signal;\nconst signale = new Signale({ scope: \"postinstall\", interactive: true });\n// Clean existing deps folder\nprocess.chdir(\"lib/cli\");\nconst DEPS = \"deps\";\nfs.rmSync(DEPS, { recursive: true, force: true });\nfs.mkdirSync(DEPS);\nprocess.chdir(DEPS);\nconst PLATFORM = os.platform();\nconst ARCH = os.arch();\nconsole.log(`Current platform: ${PLATFORM}, current architecture: ${ARCH}`);\nconst SUPPORTED_PLATFORMS = [\"linux\", \"darwin\"]; // Unsupported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android'\nconst SUPPORTED_ARCH = [\"x64\", \"arm64\"]; // Unsupported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32'\nif (!SUPPORTED_PLATFORMS.includes(PLATFORM)) {\n    console.error(`Platform ${PLATFORM} is not supported at the moment`);\n    process.exit(1);\n}\nif (!SUPPORTED_ARCH.includes(ARCH)) {\n    console.error(`Architecture ${ARCH} is not supported at the moment`);\n    process.exit(1);\n}\nsignale.await(\"Installing wasi-stub...\");\nconst BINARYEN_VERSION = `0.1.16`;\nconst BINARYEN_VERSION_TAG = `v${BINARYEN_VERSION}`;\nconst BINARYEN_SYSTEM_NAME = PLATFORM === \"linux\"\n    ? \"Linux\"\n    : PLATFORM === \"darwin\"\n        ? \"macOS\"\n        : PLATFORM === \"win32\"\n            ? \"windows\"\n            : \"other\";\nconst BINARYEN_ARCH_NAME = (ARCH == 'aarch64') ? 'ARM64' : ARCH.toUpperCase();\nconst BINARYEN_TAR_NAME = `binaryen-${BINARYEN_SYSTEM_NAME}-${BINARYEN_ARCH_NAME}.tar.gz`;\nawait download(`https://github.com/ailisp/binaryen/releases/download/${BINARYEN_VERSION_TAG}/${BINARYEN_TAR_NAME}`);\nfs.mkdirSync(\"binaryen\");\nawait executeCommand(`tar xvf ${BINARYEN_TAR_NAME} --directory binaryen`);\nfs.rmSync(BINARYEN_TAR_NAME);\nsignale.await(\"Installing QuickJS...\");\nconst QUICK_JS_VERSION = `0.1.3`;\nconst QUICK_JS_VERSION_TAG = `v${QUICK_JS_VERSION}`;\nconst QUICK_JS_SYSTEM_NAME = PLATFORM === \"linux\"\n    ? \"Linux\"\n    : PLATFORM === \"darwin\"\n        ? \"macOS\"\n        : PLATFORM === \"win32\"\n            ? \"windows\"\n            : \"other\";\nconst QUICK_JS_ARCH_NAME = ARCH === \"x64\" ? \"X64\" : ARCH === \"arm64\" ? \"arm64\" : \"other\";\nconst QUICK_JS_TAR_NAME = `${QUICK_JS_VERSION_TAG}.tar.gz`;\nconst QUICK_JS_DOWNLOADED_FOLDER_NAME = `quickjs-${QUICK_JS_VERSION}`;\nconst QUICK_JS_TARGET_FOLDER_NAME = \"quickjs\";\nconst QUICK_JS_DOWNLOADED_NAME = `qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_JS_ARCH_NAME}`;\nconst QUICK_JS_TARGET_NAME = \"qjsc\";\n// Download QuickJS\nawait download(`https://github.com/near/quickjs/releases/download/${QUICK_JS_VERSION_TAG}/qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_JS_ARCH_NAME}`);\nawait download(`https://github.com/near/quickjs/archive/refs/tags/${QUICK_JS_VERSION_TAG}.tar.gz`);\n// Extract QuickJS\nawait executeCommand(`tar xvf ${QUICK_JS_TAR_NAME}`);\n// Delete .tar file\nfs.rmSync(QUICK_JS_TAR_NAME);\n// Delete version from folder name\nfs.renameSync(QUICK_JS_DOWNLOADED_FOLDER_NAME, QUICK_JS_TARGET_FOLDER_NAME);\n// Rename qjsc file\nfs.renameSync(QUICK_JS_DOWNLOADED_NAME, QUICK_JS_TARGET_NAME);\n// chmod qjsc\nfs.chmodSync(QUICK_JS_TARGET_NAME, 0o755);\nsignale.await(\"Installing wasi-sdk...\");\nconst WASI_SDK_MAJOR_VER = 11;\nconst WASI_SDK_MINOR_VER = 0;\nconst WASI_SDK_DOWNLOADED_FOLDER_NAME = `wasi-sdk-${WASI_SDK_MAJOR_VER}.${WASI_SDK_MINOR_VER}`;\nconst WASI_SDK_SYSTEM_NAME = PLATFORM === \"linux\"\n    ? \"linux\"\n    : PLATFORM === \"darwin\"\n        ? \"macos\"\n        : PLATFORM === \"win32\"\n            ? \"windows\"\n            : \"other\";\nconst WASI_SDK_TAR_NAME = `${WASI_SDK_DOWNLOADED_FOLDER_NAME}-${WASI_SDK_SYSTEM_NAME}.tar.gz`;\n// Download WASI SDK\nawait download(`https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_MAJOR_VER}/${WASI_SDK_TAR_NAME}`);\n// Extract WASI SDK\nawait executeCommand(`tar xvf ${WASI_SDK_TAR_NAME}`);\n// Delete .tar file\nfs.rmSync(WASI_SDK_TAR_NAME);\n// Delete version from folder name\nfs.renameSync(WASI_SDK_DOWNLOADED_FOLDER_NAME, \"wasi-sdk\");\nsignale.success(\"Successfully finished postinstall script!\");\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/utils.d.ts",
    "content": "export declare function executeCommand(command: string, verbose?: boolean): Promise<string>;\nexport declare function download(url: string, verbose?: boolean): Promise<void>;\n/**\n * Validates the contract by checking that all parameters are initialized in the constructor. Works only for contracts written in TypeScript.\n *\n * @param contractPath - Path to the contract.\n * @param verbose - Whether to print verbose output.\n **/\nexport declare function validateContract(contractPath: string, verbose?: boolean): Promise<boolean>;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/cli/utils.js",
    "content": "import childProcess from \"child_process\";\nimport { promisify } from \"util\";\nimport signal from \"signale\";\nimport { Project } from \"ts-morph\";\nimport chalk from \"chalk\";\nconst { Signale } = signal;\nconst exec = promisify(childProcess.exec);\nexport async function executeCommand(command, verbose = false) {\n    const signale = new Signale({ scope: \"exec\", interactive: !verbose });\n    if (verbose) {\n        signale.info(`Running command: ${command}`);\n    }\n    let stdout, stderr, code = 0;\n    try {\n        ({ stdout, stderr } = await exec(command));\n    }\n    catch (error) {\n        ({ stdout, stderr, code } = error);\n    }\n    if (code != 0) {\n        signale.error(`Command failed: ${command}`);\n        const failDueToNameConflict = stderr.match(/conflicting types for '([a-zA-Z0-9_]+)'/);\n        if (failDueToNameConflict && failDueToNameConflict.length > 1) {\n            signale.error(`'${failDueToNameConflict[1]}' is a reserved word, please use another name for contract method\"`);\n        }\n    }\n    if (stderr && verbose) {\n        signale.error(`Command stderr: ${stderr}`);\n    }\n    if (verbose) {\n        signale.info(`Command stdout: ${stdout}`);\n    }\n    if (code != 0) {\n        process.exit(1);\n    }\n    return stdout.trim();\n}\nexport async function download(url, verbose = false) {\n    await executeCommand(`curl -LOf ${url}`, verbose);\n}\nconst UNINITIALIZED_PARAMETERS_ERROR = \"All parameters must be initialized in the constructor. Uninitialized parameters:\";\n/**\n * Validates the contract by checking that all parameters are initialized in the constructor. Works only for contracts written in TypeScript.\n *\n * @param contractPath - Path to the contract.\n * @param verbose - Whether to print verbose output.\n **/\nexport async function validateContract(contractPath, verbose = false) {\n    const signale = new Signale({ scope: \"validate-contract\" });\n    const project = new Project();\n    project.addSourceFilesAtPaths(contractPath);\n    const sourceFile = project.getSourceFile(contractPath);\n    const classDeclarations = sourceFile.getClasses();\n    for (const classDeclaration of classDeclarations) {\n        const classStructure = classDeclaration.getStructure();\n        const { decorators, properties, name } = classStructure;\n        const hasNearBindgen = decorators.some(({ name }) => name === \"NearBindgen\");\n        if (hasNearBindgen) {\n            if (verbose) {\n                signale.info(`Validating ${name} class...`);\n            }\n            const constructors = classDeclaration.getConstructors();\n            const hasConstructor = constructors.length > 0;\n            const propertiesToBeInited = properties.filter(({ initializer }) => !initializer);\n            if (!hasConstructor && propertiesToBeInited.length === 0) {\n                return true;\n            }\n            if (!hasConstructor && propertiesToBeInited.length > 0) {\n                signale.error(chalk.redBright(`${UNINITIALIZED_PARAMETERS_ERROR} ${propertiesToBeInited\n                    .map(({ name }) => name)\n                    .join(\", \")}`));\n                return false;\n            }\n            const [constructor] = constructors;\n            const constructorContent = constructor.getText();\n            if (verbose) {\n                signale.info(\"Checking for non initialized properties...\");\n            }\n            const nonInitedProperties = propertiesToBeInited.reduce((properties, { name }) => {\n                if (constructorContent.includes(`this.${name}`)) {\n                    return properties;\n                }\n                return [...properties, name];\n            }, []);\n            if (nonInitedProperties.length > 0) {\n                signale.error(chalk.redBright(`${UNINITIALIZED_PARAMETERS_ERROR} ${nonInitedProperties.join(\", \")}`));\n                return false;\n            }\n        }\n    }\n    return true;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/index.d.ts",
    "content": "export * from \"./lookup-map\";\nexport * from \"./lookup-set\";\nexport * from \"./unordered-map\";\nexport * from \"./unordered-set\";\nexport * from \"./vector\";\nexport * from \"./subtype\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/index.js",
    "content": "export * from \"./lookup-map\";\nexport * from \"./lookup-set\";\nexport * from \"./unordered-map\";\nexport * from \"./unordered-set\";\nexport * from \"./vector\";\nexport * from \"./subtype\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/lookup-map.d.ts",
    "content": "import { GetOptions } from \"../types/collections\";\nimport { SubType } from \"./subtype\";\n/**\n * A lookup map that stores data in NEAR storage.\n */\nexport declare class LookupMap<DataType> extends SubType<DataType> {\n    readonly keyPrefix: string;\n    /**\n     * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(keyPrefix: string);\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param key - The value for which to check the presence.\n     */\n    containsKey(key: string): boolean;\n    /**\n     * Get the data stored at the provided key.\n     *\n     * @param key - The key at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(key: string, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Removes and retrieves the element with the provided key.\n     *\n     * @param key - The key at which to remove data.\n     * @param options - Options for retrieving the data.\n     */\n    remove(key: string, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Store a new value at the provided key.\n     *\n     * @param key - The key at which to store in the collection.\n     * @param newValue - The value to store in the collection.\n     * @param options - Options for retrieving and storing the data.\n     */\n    set(key: string, newValue: DataType, options?: GetOptions<DataType>): DataType | null;\n    /**\n     * Extends the current collection with the passed in array of key-value pairs.\n     *\n     * @param keyValuePairs - The key-value pairs to extend the collection with.\n     * @param options - Options for storing the data.\n     */\n    extend(keyValuePairs: [string, DataType][], options?: GetOptions<DataType>): void;\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct<DataType>(data: LookupMap<unknown>): LookupMap<DataType>;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/lookup-map.js",
    "content": "import * as near from \"../api\";\nimport { getValueWithOptions, serializeValueWithOptions, encode, } from \"../utils\";\nimport { SubType } from \"./subtype\";\n/**\n * A lookup map that stores data in NEAR storage.\n */\nexport class LookupMap extends SubType {\n    /**\n     * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(keyPrefix) {\n        super();\n        this.keyPrefix = keyPrefix;\n    }\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param key - The value for which to check the presence.\n     */\n    containsKey(key) {\n        const storageKey = this.keyPrefix + key;\n        return near.storageHasKey(storageKey);\n    }\n    /**\n     * Get the data stored at the provided key.\n     *\n     * @param key - The key at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(key, options) {\n        const storageKey = this.keyPrefix + key;\n        const value = near.storageReadRaw(encode(storageKey));\n        if (options == undefined) {\n            options = {};\n        }\n        options = this.set_reconstructor(options);\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Removes and retrieves the element with the provided key.\n     *\n     * @param key - The key at which to remove data.\n     * @param options - Options for retrieving the data.\n     */\n    remove(key, options) {\n        const storageKey = this.keyPrefix + key;\n        if (!near.storageRemove(storageKey)) {\n            return options?.defaultValue ?? null;\n        }\n        const value = near.storageGetEvictedRaw();\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Store a new value at the provided key.\n     *\n     * @param key - The key at which to store in the collection.\n     * @param newValue - The value to store in the collection.\n     * @param options - Options for retrieving and storing the data.\n     */\n    set(key, newValue, options) {\n        const storageKey = this.keyPrefix + key;\n        const storageValue = serializeValueWithOptions(newValue, options);\n        if (!near.storageWriteRaw(encode(storageKey), storageValue)) {\n            return options?.defaultValue ?? null;\n        }\n        const value = near.storageGetEvictedRaw();\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Extends the current collection with the passed in array of key-value pairs.\n     *\n     * @param keyValuePairs - The key-value pairs to extend the collection with.\n     * @param options - Options for storing the data.\n     */\n    extend(keyValuePairs, options) {\n        for (const [key, value] of keyValuePairs) {\n            this.set(key, value, options);\n        }\n    }\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options) {\n        return serializeValueWithOptions(this, options);\n    }\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct(data) {\n        return new LookupMap(data.keyPrefix);\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/lookup-set.d.ts",
    "content": "import { GetOptions } from \"../types/collections\";\n/**\n * A lookup set collection that stores entries in NEAR storage.\n */\nexport declare class LookupSet<DataType> {\n    readonly keyPrefix: string;\n    /**\n     * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(keyPrefix: string);\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param key - The value for which to check the presence.\n     * @param options - Options for storing data.\n     */\n    contains(key: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): boolean;\n    /**\n     * Returns true if the element was present in the set.\n     *\n     * @param key - The entry to remove.\n     * @param options - Options for storing data.\n     */\n    remove(key: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): boolean;\n    /**\n     * If the set did not have this value present, `true` is returned.\n     * If the set did have this value present, `false` is returned.\n     *\n     * @param key - The value to store in the collection.\n     * @param options - Options for storing the data.\n     */\n    set(key: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): boolean;\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param keys - The elements to extend the collection with.\n     * @param options - Options for storing the data.\n     */\n    extend(keys: DataType[], options?: Pick<GetOptions<DataType>, \"serializer\">): void;\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct<DataType>(data: LookupSet<unknown>): LookupSet<DataType>;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/lookup-set.js",
    "content": "import * as near from \"../api\";\nimport { serializeValueWithOptions } from \"../utils\";\n/**\n * A lookup set collection that stores entries in NEAR storage.\n */\nexport class LookupSet {\n    /**\n     * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(keyPrefix) {\n        this.keyPrefix = keyPrefix;\n    }\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param key - The value for which to check the presence.\n     * @param options - Options for storing data.\n     */\n    contains(key, options) {\n        const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n        return near.storageHasKey(storageKey);\n    }\n    /**\n     * Returns true if the element was present in the set.\n     *\n     * @param key - The entry to remove.\n     * @param options - Options for storing data.\n     */\n    remove(key, options) {\n        const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n        return near.storageRemove(storageKey);\n    }\n    /**\n     * If the set did not have this value present, `true` is returned.\n     * If the set did have this value present, `false` is returned.\n     *\n     * @param key - The value to store in the collection.\n     * @param options - Options for storing the data.\n     */\n    set(key, options) {\n        const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n        return !near.storageWrite(storageKey, \"\");\n    }\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param keys - The elements to extend the collection with.\n     * @param options - Options for storing the data.\n     */\n    extend(keys, options) {\n        keys.forEach((key) => this.set(key, options));\n    }\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options) {\n        return serializeValueWithOptions(this, options);\n    }\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct(data) {\n        return new LookupSet(data.keyPrefix);\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/subtype.d.ts",
    "content": "import { GetOptions } from \"../types/collections\";\nexport declare abstract class SubType<DataType> {\n    subtype(): any;\n    set_reconstructor(options?: Omit<GetOptions<DataType>, \"serializer\">): Omit<GetOptions<DataType>, \"serializer\">;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/subtype.js",
    "content": "export class SubType {\n    /* eslint-disable @typescript-eslint/no-explicit-any */\n    /* eslint-disable @typescript-eslint/no-empty-function */\n    subtype() { }\n    set_reconstructor(options) {\n        if (options == undefined) {\n            options = {};\n        }\n        const subtype = this.subtype();\n        if (options.reconstructor == undefined && subtype != undefined) {\n            if (\n            // eslint-disable-next-line no-prototype-builtins\n            subtype.hasOwnProperty(\"class\") &&\n                typeof subtype.class.reconstruct === \"function\") {\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore\n                options.reconstructor = subtype.class.reconstruct;\n            }\n            else if (typeof subtype.reconstruct === \"function\") {\n                options.reconstructor = subtype.reconstruct;\n            }\n        }\n        return options;\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/unordered-map.d.ts",
    "content": "import { Vector } from \"./vector\";\nimport { LookupMap } from \"./lookup-map\";\nimport { GetOptions } from \"../types/collections\";\nimport { SubType } from \"./subtype\";\ndeclare type ValueAndIndex = [value: string, index: number];\n/**\n * An unordered map that stores data in NEAR storage.\n */\nexport declare class UnorderedMap<DataType> extends SubType<DataType> {\n    readonly prefix: string;\n    readonly _keys: Vector<string>;\n    readonly values: LookupMap<ValueAndIndex>;\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(prefix: string);\n    /**\n     * The number of elements stored in the collection.\n     */\n    get length(): number;\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty(): boolean;\n    /**\n     * Get the data stored at the provided key.\n     *\n     * @param key - The key at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(key: string, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Store a new value at the provided key.\n     *\n     * @param key - The key at which to store in the collection.\n     * @param value - The value to store in the collection.\n     * @param options - Options for retrieving and storing the data.\n     */\n    set(key: string, value: DataType, options?: GetOptions<DataType>): DataType | null;\n    /**\n     * Removes and retrieves the element with the provided key.\n     *\n     * @param key - The key at which to remove data.\n     * @param options - Options for retrieving the data.\n     */\n    remove(key: string, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear(): void;\n    [Symbol.iterator](): UnorderedMapIterator<DataType>;\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    private createIteratorWithOptions;\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options?: GetOptions<DataType>): [string, DataType][];\n    /**\n     * Extends the current collection with the passed in array of key-value pairs.\n     *\n     * @param keyValuePairs - The key-value pairs to extend the collection with.\n     */\n    extend(keyValuePairs: [string, DataType][]): void;\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct<DataType>(data: UnorderedMap<DataType>): UnorderedMap<DataType>;\n    keys({ start, limit }: {\n        start: any;\n        limit: any;\n    }): string[];\n}\n/**\n * An iterator for the UnorderedMap collection.\n */\ndeclare class UnorderedMapIterator<DataType> {\n    private options?;\n    private keys;\n    private map;\n    /**\n     * @param unorderedMap - The unordered map collection to create an iterator for.\n     * @param options - Options for retrieving and storing data.\n     */\n    constructor(unorderedMap: UnorderedMap<DataType>, options?: GetOptions<DataType>);\n    subtype(): any;\n    next(): {\n        value: [string | null, DataType | null];\n        done: boolean;\n    };\n}\nexport {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/unordered-map.js",
    "content": "import { assert, ERR_INCONSISTENT_STATE, getValueWithOptions, serializeValueWithOptions, encode, decode, } from \"../utils\";\nimport { Vector, VectorIterator } from \"./vector\";\nimport { LookupMap } from \"./lookup-map\";\nimport { SubType } from \"./subtype\";\n/**\n * An unordered map that stores data in NEAR storage.\n */\nexport class UnorderedMap extends SubType {\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(prefix) {\n        super();\n        this.prefix = prefix;\n        this._keys = new Vector(`${prefix}u`); // intentional different prefix with old UnorderedMap\n        this.values = new LookupMap(`${prefix}m`);\n    }\n    /**\n     * The number of elements stored in the collection.\n     */\n    get length() {\n        return this._keys.length;\n    }\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty() {\n        return this._keys.isEmpty();\n    }\n    /**\n     * Get the data stored at the provided key.\n     *\n     * @param key - The key at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(key, options) {\n        const valueAndIndex = this.values.get(key);\n        if (valueAndIndex === null) {\n            return options?.defaultValue ?? null;\n        }\n        options = this.set_reconstructor(options);\n        const [value] = valueAndIndex;\n        return getValueWithOptions(this.subtype(), encode(value), options);\n    }\n    /**\n     * Store a new value at the provided key.\n     *\n     * @param key - The key at which to store in the collection.\n     * @param value - The value to store in the collection.\n     * @param options - Options for retrieving and storing the data.\n     */\n    set(key, value, options) {\n        const valueAndIndex = this.values.get(key);\n        const serialized = serializeValueWithOptions(value, options);\n        if (valueAndIndex === null) {\n            const newElementIndex = this.length;\n            this._keys.push(key);\n            this.values.set(key, [decode(serialized), newElementIndex]);\n            return null;\n        }\n        const [oldValue, oldIndex] = valueAndIndex;\n        this.values.set(key, [decode(serialized), oldIndex]);\n        return getValueWithOptions(this.subtype(), encode(oldValue), options);\n    }\n    /**\n     * Removes and retrieves the element with the provided key.\n     *\n     * @param key - The key at which to remove data.\n     * @param options - Options for retrieving the data.\n     */\n    remove(key, options) {\n        const oldValueAndIndex = this.values.remove(key);\n        if (oldValueAndIndex === null) {\n            return options?.defaultValue ?? null;\n        }\n        const [value, index] = oldValueAndIndex;\n        assert(this._keys.swapRemove(index) !== null, ERR_INCONSISTENT_STATE);\n        // the last key is swapped to key[index], the corresponding [value, index] need update\n        if (!this._keys.isEmpty() && index !== this._keys.length) {\n            // if there is still elements and it was not the last element\n            const swappedKey = this._keys.get(index);\n            const swappedValueAndIndex = this.values.get(swappedKey);\n            assert(swappedValueAndIndex !== null, ERR_INCONSISTENT_STATE);\n            this.values.set(swappedKey, [swappedValueAndIndex[0], index]);\n        }\n        return getValueWithOptions(this.subtype(), encode(value), options);\n    }\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear() {\n        for (const key of this._keys) {\n            // Set instead of remove to avoid loading the value from storage.\n            this.values.set(key, null);\n        }\n        this._keys.clear();\n    }\n    [Symbol.iterator]() {\n        return new UnorderedMapIterator(this);\n    }\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    createIteratorWithOptions(options) {\n        return {\n            [Symbol.iterator]: () => new UnorderedMapIterator(this, options),\n        };\n    }\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options) {\n        const array = [];\n        const iterator = options ? this.createIteratorWithOptions(options) : this;\n        for (const value of iterator) {\n            array.push(value);\n        }\n        return array;\n    }\n    /**\n     * Extends the current collection with the passed in array of key-value pairs.\n     *\n     * @param keyValuePairs - The key-value pairs to extend the collection with.\n     */\n    extend(keyValuePairs) {\n        for (const [key, value] of keyValuePairs) {\n            this.set(key, value);\n        }\n    }\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options) {\n        return serializeValueWithOptions(this, options);\n    }\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct(data) {\n        const map = new UnorderedMap(data.prefix);\n        // reconstruct keys Vector\n        map._keys = new Vector(`${data.prefix}u`);\n        map._keys.length = data._keys.length;\n        // reconstruct values LookupMap\n        map.values = new LookupMap(`${data.prefix}m`);\n        return map;\n    }\n    keys({ start, limit }) {\n        const ret = [];\n        if (start === undefined) {\n            start = 0;\n        }\n        if (limit == undefined) {\n            limit = this.length - start;\n        }\n        for (let i = start; i < start + limit; i++) {\n            ret.push(this._keys.get(i));\n        }\n        return ret;\n    }\n}\n/**\n * An iterator for the UnorderedMap collection.\n */\nclass UnorderedMapIterator {\n    /**\n     * @param unorderedMap - The unordered map collection to create an iterator for.\n     * @param options - Options for retrieving and storing data.\n     */\n    constructor(unorderedMap, options) {\n        this.options = options;\n        this.keys = new VectorIterator(unorderedMap._keys);\n        this.map = unorderedMap.values;\n        this.subtype = unorderedMap.subtype;\n    }\n    /* eslint-disable @typescript-eslint/no-explicit-any */\n    /* eslint-disable @typescript-eslint/no-empty-function */\n    subtype() { }\n    next() {\n        const key = this.keys.next();\n        if (key.done) {\n            return { value: [key.value, null], done: key.done };\n        }\n        const valueAndIndex = this.map.get(key.value);\n        assert(valueAndIndex !== null, ERR_INCONSISTENT_STATE);\n        return {\n            done: key.done,\n            value: [\n                key.value,\n                getValueWithOptions(this.subtype(), encode(valueAndIndex[0]), this.options),\n            ],\n        };\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/unordered-set.d.ts",
    "content": "import { Vector, VectorIterator } from \"./vector\";\nimport { GetOptions } from \"../types/collections\";\n/**\n * An unordered set that stores data in NEAR storage.\n */\nexport declare class UnorderedSet<DataType> {\n    readonly prefix: string;\n    readonly elementIndexPrefix: string;\n    readonly _elements: Vector<DataType>;\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(prefix: string);\n    /**\n     * The number of elements stored in the collection.\n     */\n    get length(): number;\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty(): boolean;\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param element - The value for which to check the presence.\n     * @param options - Options for storing data.\n     */\n    contains(element: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): boolean;\n    /**\n     * If the set did not have this value present, `true` is returned.\n     * If the set did have this value present, `false` is returned.\n     *\n     * @param element - The value to store in the collection.\n     * @param options - Options for storing the data.\n     */\n    set(element: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): boolean;\n    /**\n     * Returns true if the element was present in the set.\n     *\n     * @param element - The entry to remove.\n     * @param options - Options for retrieving and storing data.\n     */\n    remove(element: DataType, options?: GetOptions<DataType>): boolean;\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear(options?: Pick<GetOptions<DataType>, \"serializer\">): void;\n    [Symbol.iterator](): VectorIterator<DataType>;\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    private createIteratorWithOptions;\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options?: GetOptions<DataType>): DataType[];\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param elements - The elements to extend the collection with.\n     */\n    extend(elements: DataType[]): void;\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct<DataType>(data: UnorderedSet<DataType>): UnorderedSet<DataType>;\n    elements({ options, start, limit, }: {\n        options?: GetOptions<DataType>;\n        start?: number;\n        limit?: number;\n    }): DataType[];\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/unordered-set.js",
    "content": "import * as near from \"../api\";\nimport { assert, serializeValueWithOptions, ERR_INCONSISTENT_STATE, encode, } from \"../utils\";\nimport { Vector, VectorIterator } from \"./vector\";\nfunction serializeIndex(index) {\n    const data = new Uint32Array([index]);\n    const array = new Uint8Array(data.buffer);\n    return array;\n}\nfunction deserializeIndex(rawIndex) {\n    const [data] = new Uint32Array(rawIndex.buffer);\n    return data;\n}\n/**\n * An unordered set that stores data in NEAR storage.\n */\nexport class UnorderedSet {\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     */\n    constructor(prefix) {\n        this.prefix = prefix;\n        this.elementIndexPrefix = `${prefix}i`;\n        this._elements = new Vector(`${prefix}e`);\n    }\n    /**\n     * The number of elements stored in the collection.\n     */\n    get length() {\n        return this._elements.length;\n    }\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty() {\n        return this._elements.isEmpty();\n    }\n    /**\n     * Checks whether the collection contains the value.\n     *\n     * @param element - The value for which to check the presence.\n     * @param options - Options for storing data.\n     */\n    contains(element, options) {\n        const indexLookup = this.elementIndexPrefix + serializeValueWithOptions(element, options);\n        return near.storageHasKey(indexLookup);\n    }\n    /**\n     * If the set did not have this value present, `true` is returned.\n     * If the set did have this value present, `false` is returned.\n     *\n     * @param element - The value to store in the collection.\n     * @param options - Options for storing the data.\n     */\n    set(element, options) {\n        const indexLookup = this.elementIndexPrefix + serializeValueWithOptions(element, options);\n        if (near.storageRead(indexLookup)) {\n            return false;\n        }\n        const nextIndex = this.length;\n        const nextIndexRaw = serializeIndex(nextIndex);\n        near.storageWriteRaw(encode(indexLookup), nextIndexRaw);\n        this._elements.push(element, options);\n        return true;\n    }\n    /**\n     * Returns true if the element was present in the set.\n     *\n     * @param element - The entry to remove.\n     * @param options - Options for retrieving and storing data.\n     */\n    remove(element, options) {\n        const indexLookup = this.elementIndexPrefix + serializeValueWithOptions(element, options);\n        const indexRaw = near.storageReadRaw(encode(indexLookup));\n        if (!indexRaw) {\n            return false;\n        }\n        // If there is only one element then swap remove simply removes it without\n        // swapping with the last element.\n        if (this.length === 1) {\n            near.storageRemove(indexLookup);\n            const index = deserializeIndex(indexRaw);\n            this._elements.swapRemove(index);\n            return true;\n        }\n        // If there is more than one element then swap remove swaps it with the last\n        // element.\n        const lastElement = this._elements.get(this.length - 1, options);\n        assert(!!lastElement, ERR_INCONSISTENT_STATE);\n        near.storageRemove(indexLookup);\n        // If the removed element was the last element from keys, then we don't need to\n        // reinsert the lookup back.\n        if (lastElement !== element) {\n            const lastLookupElement = this.elementIndexPrefix +\n                serializeValueWithOptions(lastElement, options);\n            near.storageWriteRaw(encode(lastLookupElement), indexRaw);\n        }\n        const index = deserializeIndex(indexRaw);\n        this._elements.swapRemove(index);\n        return true;\n    }\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear(options) {\n        for (const element of this._elements) {\n            const indexLookup = this.elementIndexPrefix + serializeValueWithOptions(element, options);\n            near.storageRemove(indexLookup);\n        }\n        this._elements.clear();\n    }\n    [Symbol.iterator]() {\n        return this._elements[Symbol.iterator]();\n    }\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    createIteratorWithOptions(options) {\n        return {\n            [Symbol.iterator]: () => new VectorIterator(this._elements, options),\n        };\n    }\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options) {\n        const array = [];\n        const iterator = options ? this.createIteratorWithOptions(options) : this;\n        for (const value of iterator) {\n            array.push(value);\n        }\n        return array;\n    }\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param elements - The elements to extend the collection with.\n     */\n    extend(elements) {\n        for (const element of elements) {\n            this.set(element);\n        }\n    }\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options) {\n        return serializeValueWithOptions(this, options);\n    }\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct(data) {\n        const set = new UnorderedSet(data.prefix);\n        // reconstruct Vector\n        const elementsPrefix = data.prefix + \"e\";\n        set._elements = new Vector(elementsPrefix);\n        set._elements.length = data._elements.length;\n        return set;\n    }\n    elements({ options, start, limit, }) {\n        const ret = [];\n        if (start === undefined) {\n            start = 0;\n        }\n        if (limit == undefined) {\n            limit = this.length - start;\n        }\n        for (let i = start; i < start + limit; i++) {\n            ret.push(this._elements.get(i, options));\n        }\n        return ret;\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/vector.d.ts",
    "content": "import { GetOptions } from \"../types/collections\";\nimport { SubType } from \"./subtype\";\n/**\n * An iterable implementation of vector that stores its content on the trie.\n * Uses the following map: index -> element\n */\nexport declare class Vector<DataType> extends SubType<DataType> {\n    readonly prefix: string;\n    length: number;\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     * @param length - The initial length of the collection. By default 0.\n     */\n    constructor(prefix: string, length?: number);\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty(): boolean;\n    /**\n     * Get the data stored at the provided index.\n     *\n     * @param index - The index at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(index: number, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Removes an element from the vector and returns it in serialized form.\n     * The removed element is replaced by the last element of the vector.\n     * Does not preserve ordering, but is `O(1)`.\n     *\n     * @param index - The index at which to remove the element.\n     * @param options - Options for retrieving and storing the data.\n     */\n    swapRemove(index: number, options?: GetOptions<DataType>): DataType | null;\n    /**\n     * Adds data to the collection.\n     *\n     * @param element - The data to store.\n     * @param options - Options for storing the data.\n     */\n    push(element: DataType, options?: Pick<GetOptions<DataType>, \"serializer\">): void;\n    /**\n     * Removes and retrieves the element with the highest index.\n     *\n     * @param options - Options for retrieving the data.\n     */\n    pop(options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\n    /**\n     * Replaces the data stored at the provided index with the provided data and returns the previously stored data.\n     *\n     * @param index - The index at which to replace the data.\n     * @param element - The data to replace with.\n     * @param options - Options for retrieving and storing the data.\n     */\n    replace(index: number, element: DataType, options?: GetOptions<DataType>): DataType;\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param elements - The elements to extend the collection with.\n     */\n    extend(elements: DataType[]): void;\n    [Symbol.iterator](): VectorIterator<DataType>;\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    private createIteratorWithOptions;\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options?: GetOptions<DataType>): DataType[];\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear(): void;\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct<DataType>(data: Vector<DataType>): Vector<DataType>;\n}\n/**\n * An iterator for the Vector collection.\n */\nexport declare class VectorIterator<DataType> {\n    private vector;\n    private readonly options?;\n    private current;\n    /**\n     * @param vector - The vector collection to create an iterator for.\n     * @param options - Options for retrieving and storing data.\n     */\n    constructor(vector: Vector<DataType>, options?: GetOptions<DataType>);\n    next(): {\n        value: DataType | null;\n        done: boolean;\n    };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/collections/vector.js",
    "content": "import * as near from \"../api\";\nimport { assert, getValueWithOptions, serializeValueWithOptions, ERR_INCONSISTENT_STATE, ERR_INDEX_OUT_OF_BOUNDS, str, bytes, } from \"../utils\";\nimport { SubType } from \"./subtype\";\nfunction indexToKey(prefix, index) {\n    const data = new Uint32Array([index]);\n    const array = new Uint8Array(data.buffer);\n    const key = str(array);\n    return prefix + key;\n}\n/**\n * An iterable implementation of vector that stores its content on the trie.\n * Uses the following map: index -> element\n */\nexport class Vector extends SubType {\n    /**\n     * @param prefix - The byte prefix to use when storing elements inside this collection.\n     * @param length - The initial length of the collection. By default 0.\n     */\n    constructor(prefix, length = 0) {\n        super();\n        this.prefix = prefix;\n        this.length = length;\n    }\n    /**\n     * Checks whether the collection is empty.\n     */\n    isEmpty() {\n        return this.length === 0;\n    }\n    /**\n     * Get the data stored at the provided index.\n     *\n     * @param index - The index at which to look for the data.\n     * @param options - Options for retrieving the data.\n     */\n    get(index, options) {\n        if (index >= this.length) {\n            return options?.defaultValue ?? null;\n        }\n        const storageKey = indexToKey(this.prefix, index);\n        const value = near.storageReadRaw(bytes(storageKey));\n        options = this.set_reconstructor(options);\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Removes an element from the vector and returns it in serialized form.\n     * The removed element is replaced by the last element of the vector.\n     * Does not preserve ordering, but is `O(1)`.\n     *\n     * @param index - The index at which to remove the element.\n     * @param options - Options for retrieving and storing the data.\n     */\n    swapRemove(index, options) {\n        assert(index < this.length, ERR_INDEX_OUT_OF_BOUNDS);\n        if (index + 1 === this.length) {\n            return this.pop(options);\n        }\n        const key = indexToKey(this.prefix, index);\n        const last = this.pop(options);\n        assert(near.storageWriteRaw(bytes(key), serializeValueWithOptions(last, options)), ERR_INCONSISTENT_STATE);\n        const value = near.storageGetEvictedRaw();\n        options = this.set_reconstructor(options);\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Adds data to the collection.\n     *\n     * @param element - The data to store.\n     * @param options - Options for storing the data.\n     */\n    push(element, options) {\n        const key = indexToKey(this.prefix, this.length);\n        this.length += 1;\n        near.storageWriteRaw(bytes(key), serializeValueWithOptions(element, options));\n    }\n    /**\n     * Removes and retrieves the element with the highest index.\n     *\n     * @param options - Options for retrieving the data.\n     */\n    pop(options) {\n        if (this.isEmpty()) {\n            return options?.defaultValue ?? null;\n        }\n        const lastIndex = this.length - 1;\n        const lastKey = indexToKey(this.prefix, lastIndex);\n        this.length -= 1;\n        assert(near.storageRemoveRaw(bytes(lastKey)), ERR_INCONSISTENT_STATE);\n        const value = near.storageGetEvictedRaw();\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Replaces the data stored at the provided index with the provided data and returns the previously stored data.\n     *\n     * @param index - The index at which to replace the data.\n     * @param element - The data to replace with.\n     * @param options - Options for retrieving and storing the data.\n     */\n    replace(index, element, options) {\n        assert(index < this.length, ERR_INDEX_OUT_OF_BOUNDS);\n        const key = indexToKey(this.prefix, index);\n        assert(near.storageWriteRaw(bytes(key), serializeValueWithOptions(element, options)), ERR_INCONSISTENT_STATE);\n        const value = near.storageGetEvictedRaw();\n        options = this.set_reconstructor(options);\n        return getValueWithOptions(this.subtype(), value, options);\n    }\n    /**\n     * Extends the current collection with the passed in array of elements.\n     *\n     * @param elements - The elements to extend the collection with.\n     */\n    extend(elements) {\n        for (const element of elements) {\n            this.push(element);\n        }\n    }\n    [Symbol.iterator]() {\n        return new VectorIterator(this);\n    }\n    /**\n     * Create a iterator on top of the default collection iterator using custom options.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    createIteratorWithOptions(options) {\n        return {\n            [Symbol.iterator]: () => new VectorIterator(this, options),\n        };\n    }\n    /**\n     * Return a JavaScript array of the data stored within the collection.\n     *\n     * @param options - Options for retrieving and storing the data.\n     */\n    toArray(options) {\n        const array = [];\n        const iterator = options ? this.createIteratorWithOptions(options) : this;\n        for (const value of iterator) {\n            array.push(value);\n        }\n        return array;\n    }\n    /**\n     * Remove all of the elements stored within the collection.\n     */\n    clear() {\n        for (let index = 0; index < this.length; index++) {\n            const key = indexToKey(this.prefix, index);\n            near.storageRemoveRaw(bytes(key));\n        }\n        this.length = 0;\n    }\n    /**\n     * Serialize the collection.\n     *\n     * @param options - Options for storing the data.\n     */\n    serialize(options) {\n        return serializeValueWithOptions(this, options);\n    }\n    /**\n     * Converts the deserialized data from storage to a JavaScript instance of the collection.\n     *\n     * @param data - The deserialized data to create an instance from.\n     */\n    static reconstruct(data) {\n        const vector = new Vector(data.prefix, data.length);\n        return vector;\n    }\n}\n/**\n * An iterator for the Vector collection.\n */\nexport class VectorIterator {\n    /**\n     * @param vector - The vector collection to create an iterator for.\n     * @param options - Options for retrieving and storing data.\n     */\n    constructor(vector, options) {\n        this.vector = vector;\n        this.options = options;\n        this.current = 0;\n    }\n    next() {\n        if (this.current >= this.vector.length) {\n            return { value: null, done: true };\n        }\n        const value = this.vector.get(this.current, this.options);\n        this.current += 1;\n        return { value, done: false };\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/index.d.ts",
    "content": "export * from \"./collections\";\nexport * from \"./types\";\nexport * as near from \"./api\";\nexport * from \"./near-bindgen\";\nexport * from \"./promise\";\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/index.js",
    "content": "export * from \"./collections\";\nexport * from \"./types\";\nexport * as near from \"./api\";\nexport * from \"./near-bindgen\";\nexport * from \"./promise\";\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/near-bindgen.d.ts",
    "content": "declare type EmptyParameterObject = Record<never, never>;\ndeclare type DecoratorFunction = <AnyFunction extends (...args: any) => any>(target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<AnyFunction>) => void;\n/**\n * Tells the SDK to use this function as the migration function of the contract.\n * The migration function will ignore te existing state.\n * @param _empty - An empty object.\n */\nexport declare function migrate(_empty: EmptyParameterObject): DecoratorFunction;\n/**\n * Tells the SDK to use this function as the initialization function of the contract.\n *\n * @param _empty - An empty object.\n */\nexport declare function initialize(_empty: EmptyParameterObject): DecoratorFunction;\n/**\n * Tells the SDK to expose this function as a view function.\n *\n * @param _empty - An empty object.\n */\nexport declare function view(_empty: EmptyParameterObject): DecoratorFunction;\n/**\n * Tells the SDK to expose this function as a call function.\n * Adds the necessary checks if the function is private or payable.\n *\n * @param options - Options to configure the function behaviour.\n * @param options.privateFunction - Whether the function can be called by other contracts.\n * @param options.payableFunction - Whether the function can accept an attached deposit.\n * @returns\n */\nexport declare function call(options: {\n    privateFunction?: boolean;\n    payableFunction?: boolean;\n}): DecoratorFunction;\n/**\n * The interface that a middleware has to implement in order to be used as a middleware function/class.\n */\ninterface Middleware<Arguments extends Array<any>> {\n    /**\n     * The method that gets called with the same arguments that are passed to the function it is wrapping.\n     *\n     * @param args - Arguments that will be passed to the function - immutable.\n     */\n    (...args: Arguments): void;\n}\n/**\n * Tells the SDK to apply an array of passed in middleware to the function execution.\n *\n * @param middlewares - The middlewares to be executed.\n */\nexport declare function middleware<Arguments extends Array<any>>(...middlewares: Middleware<Arguments>[]): DecoratorFunction;\n/**\n * Extends this class with the methods needed to make the contract storable/serializable and readable/deserializable to and from the blockchain.\n * Also tells the SDK to capture and expose all view, call and initialize functions.\n * Tells the SDK whether the contract requires initialization and whether to use a custom serialization/deserialization function when storing/reading the state.\n *\n * @param options - Options to configure the contract behaviour.\n * @param options.requireInit - Whether the contract requires initialization.\n * @param options.serializer - Custom serializer function to use for storing the contract state.\n * @param options.deserializer - Custom deserializer function to use for reading the contract state.\n */\nexport declare function NearBindgen(options: {\n    requireInit?: boolean;\n    serializer?(value: unknown): Uint8Array;\n    deserializer?(value: Uint8Array): unknown;\n}): any;\ndeclare module \"./\" {\n    /**\n     * A macro that reads the WASM code from the specified path at compile time.\n     *\n     * @param pathToWasm - The path to the WASM file to read code from.\n     */\n    function includeBytes(pathToWasm: string): Uint8Array;\n}\nexport {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/near-bindgen.js",
    "content": "import * as near from \"./api\";\nimport { deserialize, serialize, bytes, encode, decodeObj2class, } from \"./utils\";\n/**\n * Tells the SDK to use this function as the migration function of the contract.\n * The migration function will ignore te existing state.\n * @param _empty - An empty object.\n */\nexport function migrate(_empty) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return function (_target, _key, _descriptor\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n    ) { };\n}\n/**\n * Tells the SDK to use this function as the initialization function of the contract.\n *\n * @param _empty - An empty object.\n */\nexport function initialize(_empty) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return function (_target, _key, _descriptor\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n    ) { };\n}\n/**\n * Tells the SDK to expose this function as a view function.\n *\n * @param _empty - An empty object.\n */\nexport function view(_empty) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return function (_target, _key, _descriptor\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n    ) { };\n}\nexport function call({ privateFunction = false, payableFunction = false, }) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return function (_target, _key, descriptor) {\n        const originalMethod = descriptor.value;\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        descriptor.value = function (...args) {\n            if (privateFunction &&\n                near.predecessorAccountId() !== near.currentAccountId()) {\n                throw new Error(\"Function is private\");\n            }\n            if (!payableFunction && near.attachedDeposit() > 0n) {\n                throw new Error(\"Function is not payable\");\n            }\n            return originalMethod.apply(this, args);\n        };\n    };\n}\n/**\n * Tells the SDK to apply an array of passed in middleware to the function execution.\n *\n * @param middlewares - The middlewares to be executed.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function middleware(...middlewares) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return function (_target, _key, descriptor) {\n        const originalMethod = descriptor.value;\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        descriptor.value = function (...args) {\n            try {\n                middlewares.forEach((middleware) => middleware(...args));\n            }\n            catch (error) {\n                throw new Error(error);\n            }\n            return originalMethod.apply(this, args);\n        };\n    };\n}\nexport function NearBindgen({ requireInit = false, serializer = serialize, deserializer = deserialize, }) {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    return (target) => {\n        return class extends target {\n            static _create() {\n                return new target();\n            }\n            static _getState() {\n                const rawState = near.storageReadRaw(bytes(\"STATE\"));\n                return rawState ? this._deserialize(rawState) : null;\n            }\n            static _saveToStorage(objectToSave) {\n                near.storageWriteRaw(bytes(\"STATE\"), this._serialize(objectToSave));\n            }\n            static _getArgs() {\n                return JSON.parse(near.input() || \"{}\");\n            }\n            static _serialize(value, forReturn = false) {\n                if (forReturn) {\n                    return encode(JSON.stringify(value, (_, value) => typeof value === \"bigint\" ? `${value}` : value));\n                }\n                return serializer(value);\n            }\n            static _deserialize(value) {\n                return deserializer(value);\n            }\n            static _reconstruct(classObject, plainObject) {\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore\n                if (classObject.constructor.schema === undefined) {\n                    for (const item in classObject) {\n                        const reconstructor = classObject[item].constructor?.reconstruct;\n                        classObject[item] = reconstructor\n                            ? reconstructor(plainObject[item])\n                            : plainObject[item];\n                    }\n                    return classObject;\n                }\n                return decodeObj2class(classObject, plainObject);\n            }\n            static _requireInit() {\n                return requireInit;\n            }\n        };\n    };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/promise.d.ts",
    "content": "import { PromiseIndex } from \"./utils\";\nimport { Balance, PublicKey, AccountId, Gas, GasWeight } from \"./types\";\nimport { Nonce } from \"./types/primitives\";\n/**\n * A promise action which can be executed on the NEAR blockchain.\n */\nexport declare abstract class PromiseAction {\n    /**\n     * The method that describes how a promise action adds it's _action_ to the promise batch with the provided index.\n     *\n     * @param promiseIndex - The index of the promise batch to attach the action to.\n     */\n    abstract add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A create account promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class CreateAccount extends PromiseAction {\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A deploy contract promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class DeployContract extends PromiseAction {\n    code: Uint8Array;\n    /**\n     * @param code - The code of the contract to be deployed.\n     */\n    constructor(code: Uint8Array);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A function call promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class FunctionCall extends PromiseAction {\n    functionName: string;\n    args: string;\n    amount: Balance;\n    gas: Gas;\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    constructor(functionName: string, args: string, amount: Balance, gas: Gas);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A function call raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class FunctionCallRaw extends PromiseAction {\n    functionName: string;\n    args: Uint8Array;\n    amount: Balance;\n    gas: Gas;\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    constructor(functionName: string, args: Uint8Array, amount: Balance, gas: Gas);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A function call weight promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class FunctionCallWeight extends PromiseAction {\n    functionName: string;\n    args: string;\n    amount: Balance;\n    gas: Gas;\n    weight: GasWeight;\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    constructor(functionName: string, args: string, amount: Balance, gas: Gas, weight: GasWeight);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A function call weight raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class FunctionCallWeightRaw extends PromiseAction {\n    functionName: string;\n    args: Uint8Array;\n    amount: Balance;\n    gas: Gas;\n    weight: GasWeight;\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    constructor(functionName: string, args: Uint8Array, amount: Balance, gas: Gas, weight: GasWeight);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A transfer promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class Transfer extends PromiseAction {\n    amount: Balance;\n    /**\n     * @param amount - The amount of NEAR to transfer.\n     */\n    constructor(amount: Balance);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A stake promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class Stake extends PromiseAction {\n    amount: Balance;\n    publicKey: PublicKey;\n    /**\n     * @param amount - The amount of NEAR to transfer.\n     * @param publicKey - The public key to use for staking.\n     */\n    constructor(amount: Balance, publicKey: PublicKey);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A add full access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class AddFullAccessKey extends PromiseAction {\n    publicKey: PublicKey;\n    nonce: Nonce;\n    /**\n     * @param publicKey - The public key to add as a full access key.\n     * @param nonce - The nonce to use.\n     */\n    constructor(publicKey: PublicKey, nonce: Nonce);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A add access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class AddAccessKey extends PromiseAction {\n    publicKey: PublicKey;\n    allowance: Balance;\n    receiverId: AccountId;\n    functionNames: string;\n    nonce: Nonce;\n    /**\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     * @param nonce - The nonce to use.\n     */\n    constructor(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string, nonce: Nonce);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A delete key promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class DeleteKey extends PromiseAction {\n    publicKey: PublicKey;\n    /**\n     * @param publicKey - The public key to delete from the account.\n     */\n    constructor(publicKey: PublicKey);\n    add(promiseIndex: PromiseIndex): void;\n}\n/**\n * A delete account promise action.\n *\n * @extends {PromiseAction}\n */\nexport declare class DeleteAccount extends PromiseAction {\n    beneficiaryId: AccountId;\n    /**\n     * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n     */\n    constructor(beneficiaryId: AccountId);\n    add(promiseIndex: PromiseIndex): void;\n}\ndeclare class PromiseSingle {\n    accountId: AccountId;\n    actions: PromiseAction[];\n    after: NearPromise | null;\n    promiseIndex: PromiseIndex | null;\n    constructor(accountId: AccountId, actions: PromiseAction[], after: NearPromise | null, promiseIndex: PromiseIndex | null);\n    constructRecursively(): PromiseIndex;\n}\nexport declare class PromiseJoint {\n    promiseA: NearPromise;\n    promiseB: NearPromise;\n    promiseIndex: PromiseIndex | null;\n    constructor(promiseA: NearPromise, promiseB: NearPromise, promiseIndex: PromiseIndex | null);\n    constructRecursively(): PromiseIndex;\n}\ndeclare type PromiseSubtype = PromiseSingle | PromiseJoint;\n/**\n * A high level class to construct and work with NEAR promises.\n */\nexport declare class NearPromise {\n    private subtype;\n    private shouldReturn;\n    /**\n     * @param subtype - The subtype of the promise.\n     * @param shouldReturn - Whether the promise should return.\n     */\n    constructor(subtype: PromiseSubtype, shouldReturn: boolean);\n    /**\n     * Creates a new promise to the provided account ID.\n     *\n     * @param accountId - The account ID on which to call the promise.\n     */\n    static new(accountId: AccountId): NearPromise;\n    private addAction;\n    /**\n     * Creates a create account promise action and adds it to the current promise.\n     */\n    createAccount(): NearPromise;\n    /**\n     * Creates a deploy contract promise action and adds it to the current promise.\n     *\n     * @param code - The code of the contract to be deployed.\n     */\n    deployContract(code: Uint8Array): NearPromise;\n    /**\n     * Creates a function call promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    functionCall(functionName: string, args: string, amount: Balance, gas: Gas): NearPromise;\n    /**\n     * Creates a function call raw promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    functionCallRaw(functionName: string, args: Uint8Array, amount: Balance, gas: Gas): NearPromise;\n    /**\n     * Creates a function call weight promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    functionCallWeight(functionName: string, args: string, amount: Balance, gas: Gas, weight: GasWeight): NearPromise;\n    /**\n     * Creates a function call weight raw promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    functionCallWeightRaw(functionName: string, args: Uint8Array, amount: Balance, gas: Gas, weight: GasWeight): NearPromise;\n    /**\n     * Creates a transfer promise action and adds it to the current promise.\n     *\n     * @param amount - The amount of NEAR to transfer.\n     */\n    transfer(amount: Balance): NearPromise;\n    /**\n     * Creates a stake promise action and adds it to the current promise.\n     *\n     * @param amount - The amount of NEAR to transfer.\n     * @param publicKey - The public key to use for staking.\n     */\n    stake(amount: Balance, publicKey: PublicKey): NearPromise;\n    /**\n     * Creates a add full access key promise action and adds it to the current promise.\n     * Uses 0n as the nonce.\n     *\n     * @param publicKey - The public key to add as a full access key.\n     */\n    addFullAccessKey(publicKey: PublicKey): NearPromise;\n    /**\n     * Creates a add full access key promise action and adds it to the current promise.\n     * Allows you to specify the nonce.\n     *\n     * @param publicKey - The public key to add as a full access key.\n     * @param nonce - The nonce to use.\n     */\n    addFullAccessKeyWithNonce(publicKey: PublicKey, nonce: Nonce): NearPromise;\n    /**\n     * Creates a add access key promise action and adds it to the current promise.\n     * Uses 0n as the nonce.\n     *\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     */\n    addAccessKey(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string): NearPromise;\n    /**\n     * Creates a add access key promise action and adds it to the current promise.\n     * Allows you to specify the nonce.\n     *\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     * @param nonce - The nonce to use.\n     */\n    addAccessKeyWithNonce(publicKey: PublicKey, allowance: Balance, receiverId: AccountId, functionNames: string, nonce: Nonce): NearPromise;\n    /**\n     * Creates a delete key promise action and adds it to the current promise.\n     *\n     * @param publicKey - The public key to delete from the account.\n     */\n    deleteKey(publicKey: PublicKey): NearPromise;\n    /**\n     * Creates a delete account promise action and adds it to the current promise.\n     *\n     * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n     */\n    deleteAccount(beneficiaryId: AccountId): NearPromise;\n    /**\n     * Joins the provided promise with the current promise, making the current promise a joint promise subtype.\n     *\n     * @param other - The promise to join with the current promise.\n     */\n    and(other: NearPromise): NearPromise;\n    /**\n     * Adds a callback to the current promise.\n     *\n     * @param other - The promise to be executed as the promise.\n     */\n    then(other: NearPromise): NearPromise;\n    /**\n     * Sets the shouldReturn field to true.\n     */\n    asReturn(): NearPromise;\n    /**\n     * Recursively goes through the current promise to get the promise index.\n     */\n    constructRecursively(): PromiseIndex;\n    /**\n     * Called by NearBindgen, when return object is a NearPromise instance.\n     */\n    onReturn(): void;\n    /**\n     * Attach the promise to transaction but does not return it. The promise will be executed, but\n     * whether it success or not will not affect the transaction result. If you want the promise fail\n     * also makes the transaction fail, you can simply return the promise from a @call method.\n     */\n    build(): PromiseIndex;\n}\nexport declare type PromiseOrValue<T> = NearPromise | T;\nexport {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/promise.js",
    "content": "import { assert } from \"./utils\";\nimport * as near from \"./api\";\n/**\n * A promise action which can be executed on the NEAR blockchain.\n */\nexport class PromiseAction {\n}\n/**\n * A create account promise action.\n *\n * @extends {PromiseAction}\n */\nexport class CreateAccount extends PromiseAction {\n    add(promiseIndex) {\n        near.promiseBatchActionCreateAccount(promiseIndex);\n    }\n}\n/**\n * A deploy contract promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeployContract extends PromiseAction {\n    /**\n     * @param code - The code of the contract to be deployed.\n     */\n    constructor(code) {\n        super();\n        this.code = code;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionDeployContract(promiseIndex, this.code);\n    }\n}\n/**\n * A function call promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCall extends PromiseAction {\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    constructor(functionName, args, amount, gas) {\n        super();\n        this.functionName = functionName;\n        this.args = args;\n        this.amount = amount;\n        this.gas = gas;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionFunctionCall(promiseIndex, this.functionName, this.args, this.amount, this.gas);\n    }\n}\n/**\n * A function call raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallRaw extends PromiseAction {\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    constructor(functionName, args, amount, gas) {\n        super();\n        this.functionName = functionName;\n        this.args = args;\n        this.amount = amount;\n        this.gas = gas;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionFunctionCallRaw(promiseIndex, this.functionName, this.args, this.amount, this.gas);\n    }\n}\n/**\n * A function call weight promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallWeight extends PromiseAction {\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    constructor(functionName, args, amount, gas, weight) {\n        super();\n        this.functionName = functionName;\n        this.args = args;\n        this.amount = amount;\n        this.gas = gas;\n        this.weight = weight;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionFunctionCallWeight(promiseIndex, this.functionName, this.args, this.amount, this.gas, this.weight);\n    }\n}\n/**\n * A function call weight raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallWeightRaw extends PromiseAction {\n    /**\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    constructor(functionName, args, amount, gas, weight) {\n        super();\n        this.functionName = functionName;\n        this.args = args;\n        this.amount = amount;\n        this.gas = gas;\n        this.weight = weight;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionFunctionCallWeightRaw(promiseIndex, this.functionName, this.args, this.amount, this.gas, this.weight);\n    }\n}\n/**\n * A transfer promise action.\n *\n * @extends {PromiseAction}\n */\nexport class Transfer extends PromiseAction {\n    /**\n     * @param amount - The amount of NEAR to transfer.\n     */\n    constructor(amount) {\n        super();\n        this.amount = amount;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionTransfer(promiseIndex, this.amount);\n    }\n}\n/**\n * A stake promise action.\n *\n * @extends {PromiseAction}\n */\nexport class Stake extends PromiseAction {\n    /**\n     * @param amount - The amount of NEAR to transfer.\n     * @param publicKey - The public key to use for staking.\n     */\n    constructor(amount, publicKey) {\n        super();\n        this.amount = amount;\n        this.publicKey = publicKey;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionStake(promiseIndex, this.amount, this.publicKey.data);\n    }\n}\n/**\n * A add full access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class AddFullAccessKey extends PromiseAction {\n    /**\n     * @param publicKey - The public key to add as a full access key.\n     * @param nonce - The nonce to use.\n     */\n    constructor(publicKey, nonce) {\n        super();\n        this.publicKey = publicKey;\n        this.nonce = nonce;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionAddKeyWithFullAccess(promiseIndex, this.publicKey.data, this.nonce);\n    }\n}\n/**\n * A add access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class AddAccessKey extends PromiseAction {\n    /**\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     * @param nonce - The nonce to use.\n     */\n    constructor(publicKey, allowance, receiverId, functionNames, nonce) {\n        super();\n        this.publicKey = publicKey;\n        this.allowance = allowance;\n        this.receiverId = receiverId;\n        this.functionNames = functionNames;\n        this.nonce = nonce;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionAddKeyWithFunctionCall(promiseIndex, this.publicKey.data, this.nonce, this.allowance, this.receiverId, this.functionNames);\n    }\n}\n/**\n * A delete key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeleteKey extends PromiseAction {\n    /**\n     * @param publicKey - The public key to delete from the account.\n     */\n    constructor(publicKey) {\n        super();\n        this.publicKey = publicKey;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionDeleteKey(promiseIndex, this.publicKey.data);\n    }\n}\n/**\n * A delete account promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeleteAccount extends PromiseAction {\n    /**\n     * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n     */\n    constructor(beneficiaryId) {\n        super();\n        this.beneficiaryId = beneficiaryId;\n    }\n    add(promiseIndex) {\n        near.promiseBatchActionDeleteAccount(promiseIndex, this.beneficiaryId);\n    }\n}\nclass PromiseSingle {\n    constructor(accountId, actions, after, promiseIndex) {\n        this.accountId = accountId;\n        this.actions = actions;\n        this.after = after;\n        this.promiseIndex = promiseIndex;\n    }\n    constructRecursively() {\n        if (this.promiseIndex !== null) {\n            return this.promiseIndex;\n        }\n        const promiseIndex = this.after\n            ? near.promiseBatchThen(this.after.constructRecursively(), this.accountId)\n            : near.promiseBatchCreate(this.accountId);\n        this.actions.forEach((action) => action.add(promiseIndex));\n        this.promiseIndex = promiseIndex;\n        return promiseIndex;\n    }\n}\nexport class PromiseJoint {\n    constructor(promiseA, promiseB, promiseIndex) {\n        this.promiseA = promiseA;\n        this.promiseB = promiseB;\n        this.promiseIndex = promiseIndex;\n    }\n    constructRecursively() {\n        if (this.promiseIndex !== null) {\n            return this.promiseIndex;\n        }\n        const result = near.promiseAnd(this.promiseA.constructRecursively(), this.promiseB.constructRecursively());\n        this.promiseIndex = result;\n        return result;\n    }\n}\n/**\n * A high level class to construct and work with NEAR promises.\n */\nexport class NearPromise {\n    /**\n     * @param subtype - The subtype of the promise.\n     * @param shouldReturn - Whether the promise should return.\n     */\n    constructor(subtype, shouldReturn) {\n        this.subtype = subtype;\n        this.shouldReturn = shouldReturn;\n    }\n    /**\n     * Creates a new promise to the provided account ID.\n     *\n     * @param accountId - The account ID on which to call the promise.\n     */\n    static new(accountId) {\n        const subtype = new PromiseSingle(accountId, [], null, null);\n        return new NearPromise(subtype, false);\n    }\n    addAction(action) {\n        if (this.subtype instanceof PromiseJoint) {\n            throw new Error(\"Cannot add action to a joint promise.\");\n        }\n        this.subtype.actions.push(action);\n        return this;\n    }\n    /**\n     * Creates a create account promise action and adds it to the current promise.\n     */\n    createAccount() {\n        return this.addAction(new CreateAccount());\n    }\n    /**\n     * Creates a deploy contract promise action and adds it to the current promise.\n     *\n     * @param code - The code of the contract to be deployed.\n     */\n    deployContract(code) {\n        return this.addAction(new DeployContract(code));\n    }\n    /**\n     * Creates a function call promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    functionCall(functionName, args, amount, gas) {\n        return this.addAction(new FunctionCall(functionName, args, amount, gas));\n    }\n    /**\n     * Creates a function call raw promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     */\n    functionCallRaw(functionName, args, amount, gas) {\n        return this.addAction(new FunctionCallRaw(functionName, args, amount, gas));\n    }\n    /**\n     * Creates a function call weight promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The utf-8 string arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    functionCallWeight(functionName, args, amount, gas, weight) {\n        return this.addAction(new FunctionCallWeight(functionName, args, amount, gas, weight));\n    }\n    /**\n     * Creates a function call weight raw promise action and adds it to the current promise.\n     *\n     * @param functionName - The name of the function to be called.\n     * @param args - The arguments to be passed to the function.\n     * @param amount - The amount of NEAR to attach to the call.\n     * @param gas - The amount of Gas to attach to the call.\n     * @param weight - The weight of unused Gas to use.\n     */\n    functionCallWeightRaw(functionName, args, amount, gas, weight) {\n        return this.addAction(new FunctionCallWeightRaw(functionName, args, amount, gas, weight));\n    }\n    /**\n     * Creates a transfer promise action and adds it to the current promise.\n     *\n     * @param amount - The amount of NEAR to transfer.\n     */\n    transfer(amount) {\n        return this.addAction(new Transfer(amount));\n    }\n    /**\n     * Creates a stake promise action and adds it to the current promise.\n     *\n     * @param amount - The amount of NEAR to transfer.\n     * @param publicKey - The public key to use for staking.\n     */\n    stake(amount, publicKey) {\n        return this.addAction(new Stake(amount, publicKey));\n    }\n    /**\n     * Creates a add full access key promise action and adds it to the current promise.\n     * Uses 0n as the nonce.\n     *\n     * @param publicKey - The public key to add as a full access key.\n     */\n    addFullAccessKey(publicKey) {\n        return this.addFullAccessKeyWithNonce(publicKey, 0n);\n    }\n    /**\n     * Creates a add full access key promise action and adds it to the current promise.\n     * Allows you to specify the nonce.\n     *\n     * @param publicKey - The public key to add as a full access key.\n     * @param nonce - The nonce to use.\n     */\n    addFullAccessKeyWithNonce(publicKey, nonce) {\n        return this.addAction(new AddFullAccessKey(publicKey, nonce));\n    }\n    /**\n     * Creates a add access key promise action and adds it to the current promise.\n     * Uses 0n as the nonce.\n     *\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     */\n    addAccessKey(publicKey, allowance, receiverId, functionNames) {\n        return this.addAccessKeyWithNonce(publicKey, allowance, receiverId, functionNames, 0n);\n    }\n    /**\n     * Creates a add access key promise action and adds it to the current promise.\n     * Allows you to specify the nonce.\n     *\n     * @param publicKey - The public key to add as a access key.\n     * @param allowance - The allowance for the key in yoctoNEAR.\n     * @param receiverId - The account ID of the receiver.\n     * @param functionNames - The names of functions to authorize.\n     * @param nonce - The nonce to use.\n     */\n    addAccessKeyWithNonce(publicKey, allowance, receiverId, functionNames, nonce) {\n        return this.addAction(new AddAccessKey(publicKey, allowance, receiverId, functionNames, nonce));\n    }\n    /**\n     * Creates a delete key promise action and adds it to the current promise.\n     *\n     * @param publicKey - The public key to delete from the account.\n     */\n    deleteKey(publicKey) {\n        return this.addAction(new DeleteKey(publicKey));\n    }\n    /**\n     * Creates a delete account promise action and adds it to the current promise.\n     *\n     * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n     */\n    deleteAccount(beneficiaryId) {\n        return this.addAction(new DeleteAccount(beneficiaryId));\n    }\n    /**\n     * Joins the provided promise with the current promise, making the current promise a joint promise subtype.\n     *\n     * @param other - The promise to join with the current promise.\n     */\n    and(other) {\n        const subtype = new PromiseJoint(this, other, null);\n        return new NearPromise(subtype, false);\n    }\n    /**\n     * Adds a callback to the current promise.\n     *\n     * @param other - The promise to be executed as the promise.\n     */\n    then(other) {\n        assert(other.subtype instanceof PromiseSingle, \"Cannot callback joint promise.\");\n        assert(other.subtype.after === null, \"Cannot callback promise which is already scheduled after another\");\n        other.subtype.after = this;\n        return other;\n    }\n    /**\n     * Sets the shouldReturn field to true.\n     */\n    asReturn() {\n        this.shouldReturn = true;\n        return this;\n    }\n    /**\n     * Recursively goes through the current promise to get the promise index.\n     */\n    constructRecursively() {\n        const result = this.subtype.constructRecursively();\n        if (this.shouldReturn) {\n            near.promiseReturn(result);\n        }\n        return result;\n    }\n    /**\n     * Called by NearBindgen, when return object is a NearPromise instance.\n     */\n    onReturn() {\n        this.asReturn().constructRecursively();\n    }\n    /**\n     * Attach the promise to transaction but does not return it. The promise will be executed, but\n     * whether it success or not will not affect the transaction result. If you want the promise fail\n     * also makes the transaction fail, you can simply return the promise from a @call method.\n     */\n    build() {\n        return this.constructRecursively();\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/account_id.d.ts",
    "content": "/**\n * A string that represents a NEAR account ID.\n */\nexport declare type AccountId = string;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/account_id.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/collections.d.ts",
    "content": "/**\n * Options for retrieving and storing data in the SDK collections.\n */\nexport interface GetOptions<DataType> {\n    /**\n     * A constructor function to call after deserializing a value. Typically this is a constructor of the class you are storing.\n     *\n     * @param value - The value returned from deserialization - either the provided `deserializer` or default deserialization function.\n     */\n    reconstructor?(value: unknown): DataType;\n    /**\n     * A default value to return if the original value is not present or null.\n     */\n    defaultValue?: DataType;\n    /**\n     * A serializer function to customize the serialization of the collection for this call.\n     *\n     * @param valueToSerialize - The value that will be serialized - either the `DataType` or a unknown value.\n     */\n    serializer?(valueToSerialize: unknown): Uint8Array;\n    /**\n     * A deserializer function to customize the deserialization of values after reading from NEAR storage for this call.\n     *\n     * @param valueToDeserialize - The Uint8Array retrieved from NEAR storage to deserialize.\n     */\n    deserializer?(valueToDeserialize: Uint8Array): unknown;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/collections.js",
    "content": "export {};\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/gas.d.ts",
    "content": "/**\n * The Gas amount specified in yoctoNEAR.\n */\nexport declare type Gas = bigint;\n/**\n * One TGas - Tera Gas. 10^12 yoctoNEAR.\n */\nexport declare const ONE_TERA_GAS: Gas;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/gas.js",
    "content": "/**\n * One TGas - Tera Gas. 10^12 yoctoNEAR.\n */\nexport const ONE_TERA_GAS = 1000000000000n;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/index.d.ts",
    "content": "export * from \"./account_id\";\nexport * from \"./gas\";\nexport * from \"./primitives\";\nexport * from \"./public_key\";\nexport * from \"./vm_types\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/index.js",
    "content": "export * from \"./account_id\";\nexport * from \"./gas\";\nexport * from \"./primitives\";\nexport * from \"./public_key\";\nexport * from \"./vm_types\";\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/primitives.d.ts",
    "content": "/**\n * The amount of storage used in yoctoNEAR.\n */\nexport declare type StorageUsage = bigint;\n/**\n * A large integer representing the block height.\n */\nexport declare type BlockHeight = bigint;\n/**\n * A large integer representing the epoch height.\n */\nexport declare type EpochHeight = bigint;\n/**\n * The amount of tokens in yoctoNEAR.\n */\nexport declare type Balance = bigint;\n/**\n * A large integer representing the nonce.\n */\nexport declare type Nonce = bigint;\n/**\n * The amount of Gas Weight in integers - whole numbers.\n */\nexport declare type GasWeight = bigint;\n/**\n * One yoctoNEAR. 10^-24 NEAR.\n */\nexport declare const ONE_YOCTO: Balance;\n/**\n * One NEAR. 1 NEAR = 10^24 yoctoNEAR.\n */\nexport declare const ONE_NEAR: Balance;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/primitives.js",
    "content": "/**\n * One yoctoNEAR. 10^-24 NEAR.\n */\nexport const ONE_YOCTO = 1n;\n/**\n * One NEAR. 1 NEAR = 10^24 yoctoNEAR.\n */\nexport const ONE_NEAR = 1000000000000000000000000n;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/public_key.d.ts",
    "content": "export declare enum CurveType {\n    ED25519 = 0,\n    SECP256K1 = 1\n}\nexport declare function curveTypeFromStr(value: string): CurveType;\nexport declare class ParsePublicKeyError extends Error {\n}\nexport declare class InvalidLengthError extends ParsePublicKeyError {\n    length: number;\n    expectedLength: number;\n    constructor(length: number, expectedLength: number);\n}\nexport declare class Base58Error extends ParsePublicKeyError {\n    error: string;\n    constructor(error: string);\n}\nexport declare class UnknownCurve extends ParsePublicKeyError {\n    constructor();\n}\n/**\n * A abstraction on top of the NEAR public key string.\n * Public key in a binary format with base58 string serialization with human-readable curve.\n * The key types currently supported are `secp256k1` and `ed25519`.\n */\nexport declare class PublicKey {\n    /**\n     * The actual value of the public key.\n     */\n    data: Uint8Array;\n    private type;\n    /**\n     * @param data - The string you want to create a PublicKey from.\n     */\n    constructor(data: Uint8Array);\n    /**\n     * The curve type of the public key.\n     */\n    curveType(): CurveType;\n    /**\n     * Create a public key from a public key string.\n     *\n     * @param publicKeyString - The public key string you want to create a PublicKey from.\n     */\n    static fromString(publicKeyString: string): PublicKey;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/public_key.js",
    "content": "import { base58 } from \"@scure/base\";\nimport { concat } from \"../utils\";\nexport var CurveType;\n(function (CurveType) {\n    CurveType[CurveType[\"ED25519\"] = 0] = \"ED25519\";\n    CurveType[CurveType[\"SECP256K1\"] = 1] = \"SECP256K1\";\n})(CurveType || (CurveType = {}));\nvar DataLength;\n(function (DataLength) {\n    DataLength[DataLength[\"ED25519\"] = 32] = \"ED25519\";\n    DataLength[DataLength[\"SECP256K1\"] = 64] = \"SECP256K1\";\n})(DataLength || (DataLength = {}));\nfunction getCurveType(curveType) {\n    switch (curveType) {\n        case CurveType.ED25519:\n        case CurveType.SECP256K1:\n            return curveType;\n        default:\n            throw new UnknownCurve();\n    }\n}\nfunction dataLength(curveType) {\n    switch (curveType) {\n        case CurveType.ED25519:\n        case CurveType.SECP256K1:\n            return {\n                [CurveType.ED25519]: DataLength.ED25519,\n                [CurveType.SECP256K1]: DataLength.SECP256K1,\n            }[curveType];\n        default:\n            throw new UnknownCurve();\n    }\n}\nfunction splitKeyTypeData(value) {\n    const idx = value.indexOf(\":\");\n    if (idx >= 0) {\n        return [\n            curveTypeFromStr(value.substring(0, idx)),\n            value.substring(idx + 1),\n        ];\n    }\n    else {\n        return [CurveType.ED25519, value];\n    }\n}\nexport function curveTypeFromStr(value) {\n    switch (value) {\n        case \"ed25519\":\n            return CurveType.ED25519;\n        case \"secp256k1\":\n            return CurveType.SECP256K1;\n        default:\n            throw new UnknownCurve();\n    }\n}\nexport class ParsePublicKeyError extends Error {\n}\nexport class InvalidLengthError extends ParsePublicKeyError {\n    constructor(length, expectedLength) {\n        super(`Invalid length: ${length}. Expected: ${expectedLength}`);\n        this.length = length;\n        this.expectedLength = expectedLength;\n    }\n}\nexport class Base58Error extends ParsePublicKeyError {\n    constructor(error) {\n        super(`Base58 error: ${error}`);\n        this.error = error;\n    }\n}\nexport class UnknownCurve extends ParsePublicKeyError {\n    constructor() {\n        super(\"Unknown curve\");\n    }\n}\n/**\n * A abstraction on top of the NEAR public key string.\n * Public key in a binary format with base58 string serialization with human-readable curve.\n * The key types currently supported are `secp256k1` and `ed25519`.\n */\nexport class PublicKey {\n    /**\n     * @param data - The string you want to create a PublicKey from.\n     */\n    constructor(data) {\n        const curveLenght = dataLength(data[0]);\n        if (data.length !== curveLenght + 1) {\n            throw new InvalidLengthError(data.length, curveLenght + 1);\n        }\n        this.type = getCurveType(data[0]);\n        this.data = data;\n    }\n    /**\n     * The curve type of the public key.\n     */\n    curveType() {\n        return this.type;\n    }\n    /**\n     * Create a public key from a public key string.\n     *\n     * @param publicKeyString - The public key string you want to create a PublicKey from.\n     */\n    static fromString(publicKeyString) {\n        const [curve, keyData] = splitKeyTypeData(publicKeyString);\n        let data;\n        try {\n            data = base58.decode(keyData);\n        }\n        catch (error) {\n            throw new Base58Error(error.message);\n        }\n        return new PublicKey(concat(new Uint8Array([curve]), data));\n    }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/vm_types.d.ts",
    "content": "/**\n * The index for NEAR receipts.\n */\nexport declare type ReceiptIndex = bigint;\n/**\n * The index for iterators.\n */\nexport declare type IteratorIndex = bigint;\n/**\n * A Promise result in near can be one of:\n * - NotReady = 0 - the promise you are specifying is still not ready, not yet failed nor successful.\n * - Successful = 1 - the promise has been successfully executed and you can retrieve the resulting value.\n * - Failed = 2 - the promise execution has failed.\n */\nexport declare enum PromiseResult {\n    NotReady = 0,\n    Successful = 1,\n    Failed = 2\n}\n/**\n * A promise error can either be due to the promise failing or not yet being ready.\n */\nexport declare enum PromiseError {\n    Failed = 0,\n    NotReady = 1\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/types/vm_types.js",
    "content": "/**\n * A Promise result in near can be one of:\n * - NotReady = 0 - the promise you are specifying is still not ready, not yet failed nor successful.\n * - Successful = 1 - the promise has been successfully executed and you can retrieve the resulting value.\n * - Failed = 2 - the promise execution has failed.\n */\nexport var PromiseResult;\n(function (PromiseResult) {\n    PromiseResult[PromiseResult[\"NotReady\"] = 0] = \"NotReady\";\n    PromiseResult[PromiseResult[\"Successful\"] = 1] = \"Successful\";\n    PromiseResult[PromiseResult[\"Failed\"] = 2] = \"Failed\";\n})(PromiseResult || (PromiseResult = {}));\n/**\n * A promise error can either be due to the promise failing or not yet being ready.\n */\nexport var PromiseError;\n(function (PromiseError) {\n    PromiseError[PromiseError[\"Failed\"] = 0] = \"Failed\";\n    PromiseError[PromiseError[\"NotReady\"] = 1] = \"NotReady\";\n})(PromiseError || (PromiseError = {}));\n"
  },
  {
    "path": "packages/near-sdk-js/lib/utils.d.ts",
    "content": "import { GetOptions } from \"./types/collections\";\nexport interface Env {\n    uint8array_to_latin1_string(a: Uint8Array): string;\n    uint8array_to_utf8_string(a: Uint8Array): string;\n    latin1_string_to_uint8array(s: string): Uint8Array;\n    utf8_string_to_uint8array(s: string): Uint8Array;\n}\n/**\n * A PromiseIndex which represents the ID of a NEAR Promise.\n */\nexport declare type PromiseIndex = number | bigint;\n/**\n * A number that specifies the amount of NEAR in yoctoNEAR.\n */\nexport declare type NearAmount = number | bigint;\n/**\n * A number that specifies the ID of a register in the NEAR WASM virtual machine.\n */\nexport declare type Register = number | bigint;\nexport declare const ERR_INCONSISTENT_STATE = \"The collection is an inconsistent state. Did previous smart contract execution terminate unexpectedly?\";\nexport declare const ERR_INDEX_OUT_OF_BOUNDS = \"Index out of bounds\";\n/**\n * Concat two Uint8Array\n * @param array1\n * @param array2\n * @returns the concatenation of two array\n */\nexport declare function concat(array1: Uint8Array, array2: Uint8Array): Uint8Array;\n/**\n * Asserts that the expression passed to the function is truthy, otherwise throws a new Error with the provided message.\n *\n * @param expression - The expression to be asserted.\n * @param message - The error message to be printed.\n */\nexport declare function assert(expression: unknown, message: string): asserts expression;\nexport declare type Mutable<T> = {\n    -readonly [P in keyof T]: T[P];\n};\nexport declare function getValueWithOptions<DataType>(subDatatype: unknown, value: Uint8Array | null, options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null;\nexport declare function serializeValueWithOptions<DataType>(value: DataType, { serializer }?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array;\nexport declare function serialize(valueToSerialize: unknown): Uint8Array;\nexport declare function deserialize(valueToDeserialize: Uint8Array): unknown;\nexport declare function decodeObj2class(class_instance: any, obj: any): any;\n/**\n * Validates the Account ID according to the NEAR protocol\n * [Account ID rules](https://nomicon.io/DataStructures/Account#account-id-rules).\n *\n * @param accountId - The Account ID string you want to validate.\n */\nexport declare function validateAccountId(accountId: string): boolean;\n/**\n * A subset of NodeJS TextEncoder API\n */\nexport declare class TextEncoder {\n    encode(s: string): Uint8Array;\n}\n/**\n * A subset of NodeJS TextDecoder API. Only support utf-8 and latin1 encoding.\n */\nexport declare class TextDecoder {\n    encoding: string;\n    constructor(encoding?: string);\n    decode(a: Uint8Array): string;\n}\n/**\n * Convert a string to Uint8Array, each character must have a char code between 0-255.\n * @param s - string that with only Latin1 character to convert\n * @returns result Uint8Array\n */\nexport declare function bytes(s: string): Uint8Array;\n/**\n * Convert a Uint8Array to string, each uint8 to the single character of that char code\n * @param a - Uint8Array to convert\n * @returns result string\n */\nexport declare function str(a: Uint8Array): string;\n/**\n * Encode the string to Uint8Array with UTF-8 encoding\n * @param s - String to encode\n * @returns result Uint8Array\n */\nexport declare function encode(s: string): Uint8Array;\n/**\n * Decode the Uint8Array to string in UTF-8 encoding\n * @param a - array to decode\n * @returns result string\n */\nexport declare function decode(a: Uint8Array): string;\n/**\n * When implemented, allow object to be stored as collection key\n */\nexport interface IntoStorageKey {\n    into_storage_key(): string;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/utils.js",
    "content": "import { cloneDeep } from \"lodash-es\";\nconst TYPE_KEY = \"typeInfo\";\nvar TypeBrand;\n(function (TypeBrand) {\n    TypeBrand[\"BIGINT\"] = \"bigint\";\n    TypeBrand[\"DATE\"] = \"date\";\n})(TypeBrand || (TypeBrand = {}));\nexport const ERR_INCONSISTENT_STATE = \"The collection is an inconsistent state. Did previous smart contract execution terminate unexpectedly?\";\nexport const ERR_INDEX_OUT_OF_BOUNDS = \"Index out of bounds\";\nconst ACCOUNT_ID_REGEX = /^(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\n/**\n * Concat two Uint8Array\n * @param array1\n * @param array2\n * @returns the concatenation of two array\n */\nexport function concat(array1, array2) {\n    const mergedArray = new Uint8Array(array1.length + array2.length);\n    mergedArray.set(array1);\n    mergedArray.set(array2, array1.length);\n    return mergedArray;\n}\n/**\n * Asserts that the expression passed to the function is truthy, otherwise throws a new Error with the provided message.\n *\n * @param expression - The expression to be asserted.\n * @param message - The error message to be printed.\n */\nexport function assert(expression, message) {\n    if (!expression) {\n        throw new Error(\"assertion failed: \" + message);\n    }\n}\nexport function getValueWithOptions(subDatatype, value, options = {}) {\n    if (value === null) {\n        return options?.defaultValue ?? null;\n    }\n    const deserializer = options.deserializer || deserialize;\n    // here is an obj\n    let deserialized = deserializer(value);\n    if (deserialized === undefined || deserialized === null) {\n        return options?.defaultValue ?? null;\n    }\n    if (options?.reconstructor) {\n        // example: // { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n        const collection = options.reconstructor(deserialized);\n        if (subDatatype !== undefined &&\n            // eslint-disable-next-line no-prototype-builtins\n            subDatatype.hasOwnProperty(\"class\") &&\n            // eslint-disable-next-line no-prototype-builtins\n            subDatatype[\"class\"].hasOwnProperty(\"value\")) {\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-ignore\n            collection.subtype = function () {\n                // example: {class: UnorderedMap, value: UnorderedMap}\n                return subDatatype[\"class\"][\"value\"];\n            };\n        }\n        return collection;\n    }\n    // example: { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n    if (subDatatype !== undefined) {\n        // subtype info is a class constructor, Such as Car\n        if (typeof subDatatype === \"function\") {\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-ignore\n            deserialized = decodeObj2class(new subDatatype(), deserialized);\n        }\n        else if (typeof subDatatype === \"object\") {\n            // normal collections of array, map; subtype will be:\n            //  {map: { key: 'string', value: 'string' }} or {array: {value: 'string'}} ..\n            // eslint-disable-next-line no-prototype-builtins\n            if (subDatatype.hasOwnProperty(\"map\")) {\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore\n                for (const mkey in deserialized) {\n                    if (subDatatype[\"map\"][\"value\"] !== \"string\") {\n                        deserialized[mkey] = decodeObj2class(new subDatatype[\"map\"][\"value\"](), value[mkey]);\n                    }\n                }\n                // eslint-disable-next-line no-prototype-builtins\n            }\n            else if (subDatatype.hasOwnProperty(\"array\")) {\n                const new_vec = [];\n                // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n                // @ts-ignore\n                for (const k in deserialized) {\n                    if (subDatatype[\"array\"][\"value\"] !== \"string\") {\n                        new_vec.push(decodeObj2class(new subDatatype[\"array\"][\"value\"](), value[k]));\n                    }\n                }\n                deserialized = new_vec;\n                // eslint-disable-next-line no-prototype-builtins\n            }\n        }\n    }\n    return deserialized;\n}\nexport function serializeValueWithOptions(value, { serializer } = {\n    serializer: serialize,\n}) {\n    return serializer(value);\n}\nexport function serialize(valueToSerialize) {\n    return encode(JSON.stringify(valueToSerialize, function (key, value) {\n        if (typeof value === \"bigint\") {\n            return {\n                value: value.toString(),\n                [TYPE_KEY]: TypeBrand.BIGINT,\n            };\n        }\n        if (typeof this[key] === \"object\" &&\n            this[key] !== null &&\n            this[key] instanceof Date) {\n            return {\n                value: this[key].toISOString(),\n                [TYPE_KEY]: TypeBrand.DATE,\n            };\n        }\n        return value;\n    }));\n}\nexport function deserialize(valueToDeserialize) {\n    return JSON.parse(decode(valueToDeserialize), (_, value) => {\n        if (value !== null &&\n            typeof value === \"object\" &&\n            Object.keys(value).length === 2 &&\n            Object.keys(value).every((key) => [\"value\", TYPE_KEY].includes(key))) {\n            switch (value[TYPE_KEY]) {\n                case TypeBrand.BIGINT:\n                    return BigInt(value[\"value\"]);\n                case TypeBrand.DATE:\n                    return new Date(value[\"value\"]);\n            }\n        }\n        return value;\n    });\n}\nexport function decodeObj2class(class_instance, obj) {\n    if (typeof obj != \"object\" ||\n        typeof obj === \"bigint\" ||\n        obj instanceof Date ||\n        class_instance.constructor.schema === undefined) {\n        return obj;\n    }\n    let key;\n    for (key in obj) {\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        const value = obj[key];\n        if (typeof value == \"object\") {\n            // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n            // @ts-ignore\n            const ty = class_instance.constructor.schema[key];\n            // eslint-disable-next-line no-prototype-builtins\n            if (ty !== undefined && ty.hasOwnProperty(\"map\")) {\n                for (const mkey in value) {\n                    if (ty[\"map\"][\"value\"] === \"string\") {\n                        class_instance[key][mkey] = value[mkey];\n                    }\n                    else {\n                        class_instance[key][mkey] = decodeObj2class(new ty[\"map\"][\"value\"](), value[mkey]);\n                    }\n                }\n                // eslint-disable-next-line no-prototype-builtins\n            }\n            else if (ty !== undefined && ty.hasOwnProperty(\"array\")) {\n                for (const k in value) {\n                    if (ty[\"array\"][\"value\"] === \"string\") {\n                        class_instance[key].push(value[k]);\n                    }\n                    else {\n                        class_instance[key].push(decodeObj2class(new ty[\"array\"][\"value\"](), value[k]));\n                    }\n                }\n                // eslint-disable-next-line no-prototype-builtins\n            }\n            else if (ty !== undefined && ty.hasOwnProperty(\"class\")) {\n                // => nested_lookup_recordes:  {class: UnorderedMap, value: {class: LookupMap }},\n                class_instance[key] = ty[\"class\"].reconstruct(obj[key]);\n                // eslint-disable-next-line no-prototype-builtins\n                if (ty.hasOwnProperty(\"value\")) {\n                    const subtype_value = ty[\"value\"];\n                    class_instance[key].subtype = function () {\n                        // example: { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n                        // example: UnorderedMap or {class: UnorderedMap, value: 'string'}\n                        return subtype_value;\n                    };\n                }\n            }\n            else if (ty !== undefined && typeof ty.reconstruct === \"function\") {\n                class_instance[key] = ty.reconstruct(obj[key]);\n            }\n            else {\n                // normal case with nested Class, such as field is truck: Truck,\n                class_instance[key] = decodeObj2class(class_instance[key], obj[key]);\n            }\n        }\n        else {\n            class_instance[key] = obj[key];\n        }\n    }\n    const instance_tmp = cloneDeep(class_instance);\n    for (key in obj) {\n        if (typeof class_instance[key] == \"object\" &&\n            !(class_instance[key] instanceof Date)) {\n            class_instance[key] = instance_tmp[key];\n        }\n    }\n    return class_instance;\n}\n/**\n * Validates the Account ID according to the NEAR protocol\n * [Account ID rules](https://nomicon.io/DataStructures/Account#account-id-rules).\n *\n * @param accountId - The Account ID string you want to validate.\n */\nexport function validateAccountId(accountId) {\n    return (accountId.length >= 2 &&\n        accountId.length <= 64 &&\n        ACCOUNT_ID_REGEX.test(accountId));\n}\n/**\n * A subset of NodeJS TextEncoder API\n */\nexport class TextEncoder {\n    encode(s) {\n        return env.utf8_string_to_uint8array(s);\n    }\n}\n/**\n * A subset of NodeJS TextDecoder API. Only support utf-8 and latin1 encoding.\n */\nexport class TextDecoder {\n    constructor(encoding = \"utf-8\") {\n        this.encoding = encoding;\n    }\n    decode(a) {\n        if (this.encoding == \"utf-8\") {\n            return env.uint8array_to_utf8_string(a);\n        }\n        else if (this.encoding == \"latin1\") {\n            return env.uint8array_to_latin1_string(a);\n        }\n        else {\n            throw new Error(\"unsupported encoding: \" + this.encoding);\n        }\n    }\n}\n/**\n * Convert a string to Uint8Array, each character must have a char code between 0-255.\n * @param s - string that with only Latin1 character to convert\n * @returns result Uint8Array\n */\nexport function bytes(s) {\n    return env.latin1_string_to_uint8array(s);\n}\n/**\n * Convert a Uint8Array to string, each uint8 to the single character of that char code\n * @param a - Uint8Array to convert\n * @returns result string\n */\nexport function str(a) {\n    return env.uint8array_to_latin1_string(a);\n}\n/**\n * Encode the string to Uint8Array with UTF-8 encoding\n * @param s - String to encode\n * @returns result Uint8Array\n */\nexport function encode(s) {\n    return env.utf8_string_to_uint8array(s);\n}\n/**\n * Decode the Uint8Array to string in UTF-8 encoding\n * @param a - array to decode\n * @returns result string\n */\nexport function decode(a) {\n    return env.uint8array_to_utf8_string(a);\n}\n"
  },
  {
    "path": "packages/near-sdk-js/lib/version.d.ts",
    "content": "export declare const LIB_VERSION: string;\n"
  },
  {
    "path": "packages/near-sdk-js/lib/version.js",
    "content": "import * as fs from \"fs\";\nimport { fileURLToPath } from \"url\";\nconst PACKAGE_JSON = JSON.parse(fs.readFileSync(fileURLToPath(new URL(\"../package.json\", import.meta.url)), \"utf-8\"));\nexport const LIB_VERSION = PACKAGE_JSON[\"version\"];\n"
  },
  {
    "path": "packages/near-sdk-js/package.json",
    "content": "{\n  \"name\": \"near-sdk-js\",\n  \"version\": \"2.0.0\",\n  \"description\": \"High Level JavaScript SDK for building smart contracts on NEAR\",\n  \"main\": \"lib/index.js\",\n  \"types\": \"lib/index.d.ts\",\n  \"type\": \"module\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/near/near-sdk-js.git\"\n  },\n  \"homepage\": \"https://github.com/near/near-sdk-js\",\n  \"keywords\": [\n    \"JS\",\n    \"JavaScript\",\n    \"NEAR\",\n    \"SDK\",\n    \"contract\",\n    \"smart\",\n    \"smart-contract\"\n  ],\n  \"license\": \"(MIT AND Apache-2.0)\",\n  \"scripts\": {\n    \"build\": \"tsc -p ./tsconfig.json\",\n    \"lint\": \"eslint --fix .\",\n    \"format\": \"prettier --write .\",\n    \"preinstall\": \"npx only-allow pnpm\",\n    \"postinstall\": \"node lib/cli/post-install.js\"\n  },\n  \"bin\": {\n    \"near-sdk-js\": \"lib/cli/cli.js\"\n  },\n  \"author\": \"Near Inc <hello@nearprotocol.com>\",\n  \"dependencies\": {\n    \"@babel/core\": \"7.23.5\",\n    \"@babel/plugin-proposal-decorators\": \"7.23.5\",\n    \"@babel/preset-typescript\": \"7.23.3\",\n    \"@babel/types\": \"7.23.5\",\n    \"@rollup/plugin-babel\": \"5.3.1\",\n    \"@rollup/plugin-commonjs\": \"21.1.0\",\n    \"@rollup/plugin-node-resolve\": \"13.3.0\",\n    \"@scure/base\": \"1.1.7\",\n    \"@types/estree\": \"1.0.5\",\n    \"commander\": \"9.5.0\",\n    \"json-schema\": \"0.4.0\",\n    \"lodash-es\": \"4.17.21\",\n    \"near-abi\": \"0.1.1\",\n    \"near-typescript-json-schema\": \"0.55.0\",\n    \"rollup\": \"2.79.1\",\n    \"rollup-plugin-sourcemaps\": \"0.6.3\",\n    \"signale\": \"1.4.0\",\n    \"ts-morph\": \"16.0.0\",\n    \"typescript\": \"4.7.4\"\n  },\n  \"files\": [\n    \"builder\",\n    \"lib/*.js\",\n    \"lib/*.d.ts\",\n    \"lib/collections/*\",\n    \"lib/types/*\",\n    \"lib/cli/*.js\",\n    \"lib/cli/*.d.ts\",\n    \"lib/cli/build-tools/*\"\n  ],\n  \"devDependencies\": {\n    \"@rollup/plugin-typescript\": \"8.5.0\",\n    \"@types/babel__core\": \"7.20.5\",\n    \"@types/babel__traverse\": \"7.20.4\",\n    \"@types/eslint\": \"9.6.0\",\n    \"@types/node\": \"17.0.45\",\n    \"@types/rollup\": \"0.54.0\",\n    \"@types/signale\": \"1.4.7\",\n    \"@typescript-eslint/eslint-plugin\": \"5.62.0\",\n    \"@typescript-eslint/parser\": \"5.62.0\",\n    \"chalk\": \"5.3.0\",\n    \"eslint\": \"8.54.0\",\n    \"eslint-config-prettier\": \"8.10.0\",\n    \"json5\": \"2.2.3\",\n    \"npm-run-all\": \"4.1.5\",\n    \"prettier\": \"2.8.8\",\n    \"typescript\": \"4.7.4\"\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/api.ts",
    "content": "import {\n  assert,\n  NearAmount,\n  PromiseIndex,\n  Register,\n  str,\n  encode,\n  decode,\n} from \"./utils\";\nimport { GasWeight, PromiseResult } from \"./types\";\n\nconst U64_MAX = 2n ** 64n - 1n;\nconst EVICTED_REGISTER = U64_MAX - 1n;\n\n// Interface available in QuickJS\ninterface Env {\n  // Panic\n  panic_utf8(message: Uint8Array): never;\n\n  // Logging\n  log(message: string): void;\n  log_utf8(message: Uint8Array): void;\n  log_utf16(message: Uint8Array): void;\n\n  // Read from register\n  read_register(register: Register): Uint8Array;\n\n  // Storage\n  storage_read(key: Uint8Array, register: Register): bigint;\n  storage_has_key(key: Uint8Array): bigint;\n  storage_write(key: Uint8Array, value: Uint8Array, register: Register): bigint;\n  storage_remove(key: Uint8Array, register: Register): bigint;\n  storage_usage(): bigint;\n\n  // Caller methods\n  signer_account_id(register: Register): void;\n  signer_account_pk(register: Register): void;\n  attached_deposit(): bigint;\n  predecessor_account_id(register: Register): void;\n  input(register: Register): void;\n\n  // Account data\n  account_balance(): bigint;\n  account_locked_balance(): bigint;\n  current_account_id(register: Register): void;\n  validator_stake(accountId: string): bigint;\n  validator_total_stake(): bigint;\n\n  // Blockchain info\n  block_index(): bigint;\n  block_timestamp(): bigint;\n  epoch_height(): bigint;\n\n  // Gas\n  prepaid_gas(): bigint;\n  used_gas(): bigint;\n\n  // Helper methods and cryptography\n  value_return(value: Uint8Array): void;\n  random_seed(register: Register): void;\n  sha256(value: Uint8Array, register: Register): void;\n  keccak256(value: Uint8Array, register: Register): void;\n  keccak512(value: Uint8Array, register: Register): void;\n  ripemd160(value: Uint8Array, register: Register): void;\n  ecrecover(\n    hash: Uint8Array,\n    sig: Uint8Array,\n    v: number,\n    malleabilityFlag: number,\n    register: Register\n  ): bigint;\n  alt_bn128_g1_multiexp(value: Uint8Array, register: Register): void;\n  alt_bn128_g1_sum(value: Uint8Array, register: Register): void;\n  alt_bn128_pairing_check(value: Uint8Array): bigint;\n\n  // Promises\n  promise_create(\n    accountId: string,\n    methodName: string,\n    args: Uint8Array,\n    amount: NearAmount,\n    gas: NearAmount\n  ): bigint;\n  promise_then(\n    promiseIndex: bigint,\n    accountId: string,\n    methodName: string,\n    args: Uint8Array,\n    amount: NearAmount,\n    gas: NearAmount\n  ): bigint;\n  promise_and(...promiseIndexes: bigint[]): bigint;\n  promise_batch_create(accountId: string): bigint;\n  promise_batch_then(promiseIndex: bigint, accountId: string): bigint;\n  promise_batch_action_create_account(promiseIndex: bigint): void;\n  promise_batch_action_deploy_contract(\n    promiseIndex: bigint,\n    code: Uint8Array\n  ): void;\n  promise_batch_action_function_call(\n    promiseIndex: bigint,\n    methodName: string,\n    args: Uint8Array,\n    amount: NearAmount,\n    gas: NearAmount\n  ): void;\n  promise_batch_action_transfer(promiseIndex: bigint, amount: NearAmount): void;\n  promise_batch_action_stake(\n    promiseIndex: bigint,\n    amount: NearAmount,\n    publicKey: Uint8Array\n  ): void;\n  promise_batch_action_add_key_with_full_access(\n    promiseIndex: bigint,\n    publicKey: Uint8Array,\n    nonce: number | bigint\n  ): void;\n  promise_batch_action_add_key_with_function_call(\n    promiseIndex: bigint,\n    publicKey: Uint8Array,\n    nonce: number | bigint,\n    allowance: NearAmount,\n    receiverId: string,\n    methodNames: string\n  ): void;\n  promise_batch_action_delete_key(\n    promiseIndex: bigint,\n    publicKey: Uint8Array\n  ): void;\n  promise_batch_action_delete_account(\n    promiseIndex: bigint,\n    beneficiaryId: string\n  ): void;\n  promise_batch_action_function_call_weight(\n    promiseIndex: bigint,\n    methodName: string,\n    args: Uint8Array,\n    amount: NearAmount,\n    gas: NearAmount,\n    weight: GasWeight\n  ): void;\n  promise_results_count(): bigint;\n  promise_result(promiseIndex: bigint, register: Register): PromiseResult;\n  promise_return(promiseIndex: bigint): void;\n\n  // These are exported C functions that not part of NEAR VM Logic (host functions)\n  uint8array_to_latin1_string(a: Uint8Array): string;\n  uint8array_to_utf8_string(a: Uint8Array): string;\n  latin1_string_to_uint8array(s: string): Uint8Array;\n  utf8_string_to_uint8array(s: string): Uint8Array;\n}\n\ndeclare const env: Env;\n\n/**\n * Logs parameters in the NEAR WASM virtual machine.\n *\n * @param params - Parameters to log.\n */\nexport function log(...params: unknown[]): void {\n  env.log(\n    params.reduce<string>((accumulated, parameter, index) => {\n      // Stringify undefined\n      const param = parameter === undefined ? \"undefined\" : parameter;\n      // Convert Objects to strings and convert to string\n      const stringified =\n        typeof param === \"object\" ? JSON.stringify(param) : `${param}`;\n\n      if (index === 0) {\n        return stringified;\n      }\n\n      return `${accumulated} ${stringified}`;\n    }, \"\")\n  );\n}\n\n/**\n * Returns the account ID of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport function signerAccountId(): string {\n  env.signer_account_id(0);\n  return str(env.read_register(0));\n}\n\n/**\n * Returns the public key of the account that signed the transaction.\n * Can only be called in a call or initialize function.\n */\nexport function signerAccountPk(): Uint8Array {\n  env.signer_account_pk(0);\n  return env.read_register(0);\n}\n\n/**\n * Returns the account ID of the account that called the function.\n * Can only be called in a call or initialize function.\n */\nexport function predecessorAccountId(): string {\n  env.predecessor_account_id(0);\n  return str(env.read_register(0));\n}\n\n/**\n * Returns the account ID of the current contract - the contract that is being executed.\n */\nexport function currentAccountId(): string {\n  env.current_account_id(0);\n  return str(env.read_register(0));\n}\n\n/**\n * Returns the current block index.\n */\nexport function blockIndex(): bigint {\n  return env.block_index();\n}\n\n/**\n * Returns the current block height.\n */\nexport function blockHeight(): bigint {\n  return blockIndex();\n}\n\n/**\n * Returns the current block timestamp.\n */\nexport function blockTimestamp(): bigint {\n  return env.block_timestamp();\n}\n\n/**\n * Returns the current epoch height.\n */\nexport function epochHeight(): bigint {\n  return env.epoch_height();\n}\n\n/**\n * Returns the amount of NEAR attached to this function call.\n * Can only be called in payable functions.\n */\nexport function attachedDeposit(): bigint {\n  return env.attached_deposit();\n}\n\n/**\n * Returns the amount of Gas that was attached to this function call.\n */\nexport function prepaidGas(): bigint {\n  return env.prepaid_gas();\n}\n\n/**\n * Returns the amount of Gas that has been used by this function call until now.\n */\nexport function usedGas(): bigint {\n  return env.used_gas();\n}\n\n/**\n * Returns the current account's account balance.\n */\nexport function accountBalance(): bigint {\n  return env.account_balance();\n}\n\n/**\n * Returns the current account's locked balance.\n */\nexport function accountLockedBalance(): bigint {\n  return env.account_locked_balance();\n}\n\n/**\n * Reads the value from NEAR storage that is stored under the provided key.\n *\n * @param key - The key to read from storage.\n */\nexport function storageReadRaw(key: Uint8Array): Uint8Array | null {\n  const returnValue = env.storage_read(key, 0);\n\n  if (returnValue !== 1n) {\n    return null;\n  }\n\n  return env.read_register(0);\n}\n\n/**\n * Reads the utf-8 string value from NEAR storage that is stored under the provided key.\n *\n * @param key - The utf-8 string key to read from storage.\n */\nexport function storageRead(key: string): string | null {\n  const ret = storageReadRaw(encode(key));\n  if (ret !== null) {\n    return decode(ret);\n  }\n  return null;\n}\n\n/**\n * Checks for the existence of a value under the provided key in NEAR storage.\n *\n * @param key - The key to check for in storage.\n */\nexport function storageHasKeyRaw(key: Uint8Array): boolean {\n  return env.storage_has_key(key) === 1n;\n}\n\n/**\n * Checks for the existence of a value under the provided utf-8 string key in NEAR storage.\n *\n * @param key - The utf-8 string key to check for in storage.\n */\nexport function storageHasKey(key: string): boolean {\n  return storageHasKeyRaw(encode(key));\n}\n\n/**\n * Get the last written or removed value from NEAR storage.\n */\nexport function storageGetEvictedRaw(): Uint8Array {\n  return env.read_register(EVICTED_REGISTER);\n}\n\n/**\n * Get the last written or removed value from NEAR storage as utf-8 string.\n */\nexport function storageGetEvicted(): string {\n  return decode(storageGetEvictedRaw());\n}\n\n/**\n * Returns the current accounts NEAR storage usage.\n */\nexport function storageUsage(): bigint {\n  return env.storage_usage();\n}\n\n/**\n * Writes the provided bytes to NEAR storage under the provided key.\n *\n * @param key - The key under which to store the value.\n * @param value - The value to store.\n */\nexport function storageWriteRaw(key: Uint8Array, value: Uint8Array): boolean {\n  return env.storage_write(key, value, EVICTED_REGISTER) === 1n;\n}\n\n/**\n * Writes the provided utf-8 string to NEAR storage under the provided key.\n *\n * @param key - The utf-8 string key under which to store the value.\n * @param value - The utf-8 string value to store.\n */\nexport function storageWrite(key: string, value: string): boolean {\n  return storageWriteRaw(encode(key), encode(value));\n}\n\n/**\n * Removes the value of the provided key from NEAR storage.\n *\n * @param key - The key to be removed.\n */\nexport function storageRemoveRaw(key: Uint8Array): boolean {\n  return env.storage_remove(key, EVICTED_REGISTER) === 1n;\n}\n\n/**\n * Removes the value of the provided utf-8 string key from NEAR storage.\n *\n * @param key - The utf-8 string key to be removed.\n */\nexport function storageRemove(key: string): boolean {\n  return storageRemoveRaw(encode(key));\n}\n\n/**\n * Returns the cost of storing 0 Byte on NEAR storage.\n */\nexport function storageByteCost(): bigint {\n  return 10_000_000_000_000_000_000n;\n}\n\n/**\n * Returns the arguments passed to the current smart contract call.\n */\nexport function inputRaw(): Uint8Array {\n  env.input(0);\n  return env.read_register(0);\n}\n\n/**\n * Returns the arguments passed to the current smart contract call as utf-8 string.\n */\nexport function input(): string {\n  return decode(inputRaw());\n}\n\n/**\n * Returns the value from the NEAR WASM virtual machine.\n *\n * @param value - The value to return.\n */\nexport function valueReturnRaw(value: Uint8Array): void {\n  env.value_return(value);\n}\n\n/**\n * Returns the utf-8 string value from the NEAR WASM virtual machine.\n *\n * @param value - The utf-8 string value to return.\n */\nexport function valueReturn(value: string): void {\n  valueReturnRaw(encode(value));\n}\n\n/**\n * Returns a random string of bytes.\n */\nexport function randomSeed(): Uint8Array {\n  env.random_seed(0);\n  return env.read_register(0);\n}\n\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport function promiseCreateRaw(\n  accountId: string,\n  methodName: string,\n  args: Uint8Array,\n  amount: NearAmount,\n  gas: NearAmount\n): PromiseIndex {\n  return env.promise_create(\n    accountId,\n    methodName,\n    args,\n    amount,\n    gas\n  ) as unknown as PromiseIndex;\n}\n\n/**\n * Create a NEAR promise call to a contract on the blockchain.\n *\n * @param accountId - The account ID of the target contract.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR attached to the call.\n * @param gas - The amount of Gas attached to the call.\n */\nexport function promiseCreate(\n  accountId: string,\n  methodName: string,\n  args: string,\n  amount: NearAmount,\n  gas: NearAmount\n): PromiseIndex {\n  return promiseCreateRaw(accountId, methodName, encode(args), amount, gas);\n}\n\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseThenRaw(\n  promiseIndex: PromiseIndex,\n  accountId: string,\n  methodName: string,\n  args: Uint8Array,\n  amount: NearAmount,\n  gas: NearAmount\n): PromiseIndex {\n  return env.promise_then(\n    promiseIndex as unknown as bigint,\n    accountId,\n    methodName,\n    args,\n    amount,\n    gas\n  ) as unknown as PromiseIndex;\n}\n\n/**\n * Attach a callback NEAR promise to be executed after a provided promise.\n *\n * @param promiseIndex - The promise after which to call the callback.\n * @param accountId - The account ID of the contract to perform the callback on.\n * @param methodName - The name of the method to call.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseThen(\n  promiseIndex: PromiseIndex,\n  accountId: string,\n  methodName: string,\n  args: string,\n  amount: NearAmount,\n  gas: NearAmount\n): PromiseIndex {\n  return promiseThenRaw(\n    promiseIndex,\n    accountId,\n    methodName,\n    encode(args),\n    amount,\n    gas\n  );\n}\n\n/**\n * Join an arbitrary array of NEAR promises.\n *\n * @param promiseIndexes - An arbitrary array of NEAR promise indexes to join.\n */\nexport function promiseAnd(...promiseIndexes: PromiseIndex[]): PromiseIndex {\n  return env.promise_and(\n    ...(promiseIndexes as unknown as bigint[])\n  ) as unknown as PromiseIndex;\n}\n\n/**\n * Create a NEAR promise which will have multiple promise actions inside.\n *\n * @param accountId - The account ID of the target contract.\n */\nexport function promiseBatchCreate(accountId: string): PromiseIndex {\n  return env.promise_batch_create(accountId) as unknown as PromiseIndex;\n}\n\n/**\n * Attach a callback NEAR promise to a batch of NEAR promise actions.\n *\n * @param promiseIndex - The NEAR promise index of the batch.\n * @param accountId - The account ID of the target contract.\n */\nexport function promiseBatchThen(\n  promiseIndex: PromiseIndex,\n  accountId: string\n): PromiseIndex {\n  return env.promise_batch_then(\n    promiseIndex as unknown as bigint,\n    accountId\n  ) as unknown as PromiseIndex;\n}\n\n/**\n * Attach a create account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a create account action to.\n */\nexport function promiseBatchActionCreateAccount(\n  promiseIndex: PromiseIndex\n): void {\n  env.promise_batch_action_create_account(promiseIndex as unknown as bigint);\n}\n\n/**\n * Attach a deploy contract promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a deploy contract action to.\n * @param code - The WASM byte code of the contract to be deployed.\n */\nexport function promiseBatchActionDeployContract(\n  promiseIndex: PromiseIndex,\n  code: Uint8Array\n): void {\n  env.promise_batch_action_deploy_contract(\n    promiseIndex as unknown as bigint,\n    code\n  );\n}\n\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseBatchActionFunctionCallRaw(\n  promiseIndex: PromiseIndex,\n  methodName: string,\n  args: Uint8Array,\n  amount: NearAmount,\n  gas: NearAmount\n): void {\n  env.promise_batch_action_function_call(\n    promiseIndex as unknown as bigint,\n    methodName,\n    args,\n    amount,\n    gas\n  );\n}\n\n/**\n * Attach a function call promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n */\nexport function promiseBatchActionFunctionCall(\n  promiseIndex: PromiseIndex,\n  methodName: string,\n  args: string,\n  amount: NearAmount,\n  gas: NearAmount\n): void {\n  promiseBatchActionFunctionCallRaw(\n    promiseIndex,\n    methodName,\n    encode(args),\n    amount,\n    gas\n  );\n}\n\n/**\n * Attach a transfer promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a transfer action to.\n * @param amount - The amount of NEAR to transfer.\n */\nexport function promiseBatchActionTransfer(\n  promiseIndex: PromiseIndex,\n  amount: NearAmount\n): void {\n  env.promise_batch_action_transfer(promiseIndex as unknown as bigint, amount);\n}\n\n/**\n * Attach a stake promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a stake action to.\n * @param amount - The amount of NEAR to stake.\n * @param publicKey - The public key with which to stake.\n */\nexport function promiseBatchActionStake(\n  promiseIndex: PromiseIndex,\n  amount: NearAmount,\n  publicKey: Uint8Array\n): void {\n  env.promise_batch_action_stake(\n    promiseIndex as unknown as bigint,\n    amount,\n    publicKey\n  );\n}\n\n/**\n * Attach a add full access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add full access key action to.\n * @param publicKey - The public key to add as a full access key.\n * @param nonce - The nonce to use.\n */\nexport function promiseBatchActionAddKeyWithFullAccess(\n  promiseIndex: PromiseIndex,\n  publicKey: Uint8Array,\n  nonce: number | bigint\n): void {\n  env.promise_batch_action_add_key_with_full_access(\n    promiseIndex as unknown as bigint,\n    publicKey,\n    nonce\n  );\n}\n\n/**\n * Attach a add access key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a add access key action to.\n * @param publicKey - The public key to add.\n * @param nonce - The nonce to use.\n * @param allowance - The allowance of the access key.\n * @param receiverId - The account ID of the receiver.\n * @param methodNames - The names of the method to allow the key for.\n */\nexport function promiseBatchActionAddKeyWithFunctionCall(\n  promiseIndex: PromiseIndex,\n  publicKey: Uint8Array,\n  nonce: number | bigint,\n  allowance: NearAmount,\n  receiverId: string,\n  methodNames: string\n): void {\n  env.promise_batch_action_add_key_with_function_call(\n    promiseIndex as unknown as bigint,\n    publicKey,\n    nonce,\n    allowance,\n    receiverId,\n    methodNames\n  );\n}\n\n/**\n * Attach a delete key promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete key action to.\n * @param publicKey - The public key to delete.\n */\nexport function promiseBatchActionDeleteKey(\n  promiseIndex: PromiseIndex,\n  publicKey: Uint8Array\n): void {\n  env.promise_batch_action_delete_key(\n    promiseIndex as unknown as bigint,\n    publicKey\n  );\n}\n\n/**\n * Attach a delete account promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a delete account action to.\n * @param beneficiaryId - The account ID of the beneficiary - the account that receives the remaining amount of NEAR.\n */\nexport function promiseBatchActionDeleteAccount(\n  promiseIndex: PromiseIndex,\n  beneficiaryId: string\n): void {\n  env.promise_batch_action_delete_account(\n    promiseIndex as unknown as bigint,\n    beneficiaryId\n  );\n}\n\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport function promiseBatchActionFunctionCallWeightRaw(\n  promiseIndex: PromiseIndex,\n  methodName: string,\n  args: Uint8Array,\n  amount: NearAmount,\n  gas: NearAmount,\n  weight: GasWeight\n): void {\n  env.promise_batch_action_function_call_weight(\n    promiseIndex as unknown as bigint,\n    methodName,\n    args,\n    amount,\n    gas,\n    weight\n  );\n}\n\n/**\n * Attach a function call with weight promise action to the NEAR promise index with the provided promise index.\n *\n * @param promiseIndex - The index of the promise to attach a function call with weight action to.\n * @param methodName - The name of the method to be called.\n * @param args - The utf-8 string arguments to call the method with.\n * @param amount - The amount of NEAR to attach to the call.\n * @param gas - The amount of Gas to attach to the call.\n * @param weight - The weight of unused Gas to use.\n */\nexport function promiseBatchActionFunctionCallWeight(\n  promiseIndex: PromiseIndex,\n  methodName: string,\n  args: string,\n  amount: NearAmount,\n  gas: NearAmount,\n  weight: GasWeight\n): void {\n  promiseBatchActionFunctionCallWeightRaw(\n    promiseIndex,\n    methodName,\n    encode(args),\n    amount,\n    gas,\n    weight\n  );\n}\n\n/**\n * The number of promise results available.\n */\nexport function promiseResultsCount(): bigint {\n  return env.promise_results_count();\n}\n\n/**\n * Returns the result of the NEAR promise for the passed promise index.\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport function promiseResultRaw(promiseIndex: PromiseIndex): Uint8Array {\n  const status = env.promise_result(promiseIndex as unknown as bigint, 0);\n\n  assert(\n    Number(status) === PromiseResult.Successful,\n    `Promise result ${\n      status == PromiseResult.Failed\n        ? \"Failed\"\n        : status == PromiseResult.NotReady\n        ? \"NotReady\"\n        : status\n    }`\n  );\n\n  return env.read_register(0);\n}\n\n/**\n * Returns the result of the NEAR promise for the passed promise index as utf-8 string\n *\n * @param promiseIndex - The index of the promise to return the result for.\n */\nexport function promiseResult(promiseIndex: PromiseIndex): string {\n  return decode(promiseResultRaw(promiseIndex));\n}\n\n/**\n * Executes the promise in the NEAR WASM virtual machine.\n *\n * @param promiseIndex - The index of the promise to execute.\n */\nexport function promiseReturn(promiseIndex: PromiseIndex): void {\n  env.promise_return(promiseIndex as unknown as bigint);\n}\n\n/**\n * Returns sha256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function sha256(value: Uint8Array): Uint8Array {\n  env.sha256(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Returns keccak256 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function keccak256(value: Uint8Array): Uint8Array {\n  env.keccak256(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Returns keccak512 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function keccak512(value: Uint8Array): Uint8Array {\n  env.keccak512(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Returns ripemd160 hash of given value\n * @param value - value to be hashed, in Bytes\n * @returns hash result in Bytes\n */\nexport function ripemd160(value: Uint8Array): Uint8Array {\n  env.ripemd160(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Recovers an ECDSA signer address from a 32-byte message hash and a corresponding\n * signature along with v recovery byte. Takes in an additional flag to check for\n * malleability of the signature which is generally only ideal for transactions.\n *\n * @param hash - 32-byte message hash\n * @param sig - signature\n * @param v - number of recovery byte\n * @param malleabilityFlag - whether to check malleability\n * @returns 64 bytes representing the public key if the recovery was successful.\n */\nexport function ecrecover(\n  hash: Uint8Array,\n  sig: Uint8Array,\n  v: number,\n  malleabilityFlag: number\n): Uint8Array | null {\n  const returnValue = env.ecrecover(hash, sig, v, malleabilityFlag, 0);\n\n  if (returnValue === 0n) {\n    return null;\n  }\n\n  return env.read_register(0);\n}\n\n// NOTE: \"env.panic(msg)\" is not exported, use \"throw Error(msg)\" instead\n\n/**\n * Panic the transaction execution with given message\n * @param msg - panic message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport function panicUtf8(msg: Uint8Array): never {\n  env.panic_utf8(msg);\n}\n\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-8 sequence\n */\nexport function logUtf8(msg: Uint8Array) {\n  env.log_utf8(msg);\n}\n\n/**\n * Log the message in transaction logs\n * @param msg - message in raw bytes, which should be a valid UTF-16 sequence\n */\nexport function logUtf16(msg: Uint8Array) {\n  env.log_utf16(msg);\n}\n\n/**\n * Returns the number of staked NEAR of given validator, in yoctoNEAR\n * @param accountId - validator's AccountID\n * @returns - staked amount\n */\nexport function validatorStake(accountId: string): bigint {\n  return env.validator_stake(accountId);\n}\n\n/**\n * Returns the number of staked NEAR of all validators, in yoctoNEAR\n * @returns total staked amount\n */\nexport function validatorTotalStake(): bigint {\n  return env.validator_total_stake();\n}\n\n/**\n * Computes multiexp on alt_bn128 curve using Pippenger's algorithm \\sum_i\n * mul_i g_{1 i} should be equal result.\n *\n * @param value - sequence of (g1:G1, fr:Fr), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * `value` is encoded as packed, little-endian\n * `[((u256, u256), u256)]` slice.\n *\n * @returns multi exp sum\n */\nexport function altBn128G1Multiexp(value: Uint8Array): Uint8Array {\n  env.alt_bn128_g1_multiexp(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Computes sum for signed g1 group elements on alt_bn128 curve \\sum_i\n * (-1)^{sign_i} g_{1 i} should be equal result.\n *\n * @param value - sequence of (sign:bool, g1:G1), where\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq.\n * value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns sum over Fq.\n */\nexport function altBn128G1Sum(value: Uint8Array): Uint8Array {\n  env.alt_bn128_g1_sum(value, 0);\n  return env.read_register(0);\n}\n\n/**\n * Computes pairing check on alt_bn128 curve.\n * \\sum_i e(g_{1 i}, g_{2 i}) should be equal one (in additive notation), e(g1, g2) is Ate pairing\n *\n * @param value - sequence of (g1:G1, g2:G2), where\n * G2 is Fr-ordered subgroup point (x:Fq2, y:Fq2) on alt_bn128 twist,\n * alt_bn128 twist is Y^2 = X^3 + 3/(i+9) curve over Fq2\n * Fq2 is complex field element (re: Fq, im: Fq)\n * G1 is point (x:Fq, y:Fq) on alt_bn128,\n * alt_bn128 is Y^2 = X^3 + 3 curve over Fq\n * `value` is encoded a as packed, little-endian\n * `[((u256, u256), ((u256, u256), (u256, u256)))]` slice.\n *\n * @returns whether pairing check pass\n */\nexport function altBn128PairingCheck(value: Uint8Array): boolean {\n  return env.alt_bn128_pairing_check(value) === 1n;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/abi.ts",
    "content": "import ts, { ClassDeclaration, Decorator, NodeArray } from \"typescript\";\nimport JSON5 from 'json5';\nimport * as abi from \"near-abi\";\nimport * as TJS from \"near-typescript-json-schema\";\nimport { JSONSchema7 } from \"json-schema\";\nimport * as fs from \"fs\";\nimport { LIB_VERSION } from \"../version.js\";\n\nfunction parseMetadata(packageJsonPath: string): abi.AbiMetadata {\n  const packageJson = JSON5.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n\n  let authors: string[] = [];\n  if (packageJson[\"author\"]) authors.push(packageJson[\"author\"]);\n  authors = authors.concat(packageJson[\"contributors\"] || []);\n\n  return {\n    name: packageJson[\"name\"],\n    version: packageJson[\"version\"],\n    authors,\n    build: {\n      compiler: \"tsc \" + ts.version,\n      builder: \"near-sdk-js \" + LIB_VERSION,\n    },\n  };\n}\n\nfunction getProgramFromFiles(\n  files: string[],\n  jsonCompilerOptions: string,\n  basePath = \"./\"\n): ts.Program {\n  const { options, errors } = ts.convertCompilerOptionsFromJson(\n    jsonCompilerOptions,\n    basePath\n  );\n  if (errors.length > 0) {\n    errors.forEach((error) => {\n      console.log(error.messageText);\n    });\n    throw Error(\"Invalid compiler options\");\n  }\n  return ts.createProgram(files, options);\n}\n\nfunction validateNearClass(node: ts.Node) {\n  if (node.kind !== ts.SyntaxKind.ClassDeclaration) {\n    throw Error(\"Expected NEAR function to be inside of a class\");\n  }\n  const classDeclaration = node as ClassDeclaration;\n  const decorators =\n    classDeclaration.decorators || ([] as unknown as NodeArray<Decorator>);\n  const containsNearBindgen = decorators.some((decorator) => {\n    if (decorator.expression.kind !== ts.SyntaxKind.CallExpression)\n      return false;\n    const decoratorExpression = decorator.expression as ts.CallExpression;\n    if (decoratorExpression.expression.kind !== ts.SyntaxKind.Identifier)\n      return false;\n    const decoratorIdentifier = decoratorExpression.expression as ts.Identifier;\n    const decoratorName = decoratorIdentifier.text;\n    return decoratorName === \"NearBindgen\";\n  });\n\n  if (!containsNearBindgen) {\n    throw Error(\n      \"Expected NEAR function to be inside of a class decorated with @NearBindgen\"\n    );\n  }\n}\n\nexport function runAbiCompilerPlugin(\n  tsFile: string,\n  packageJsonPath: string,\n  tsConfigJsonPath: string\n) {\n  const tsConfig = JSON5.parse(fs.readFileSync(tsConfigJsonPath, \"utf8\"));\n  const program = getProgramFromFiles([tsFile], tsConfig[\"compilerOptions\"]);\n  const typeChecker = program.getTypeChecker();\n\n  const diagnostics = ts.getPreEmitDiagnostics(program);\n  if (diagnostics.length > 0) {\n    diagnostics.forEach((diagnostic) => {\n      const message = ts.flattenDiagnosticMessageText(\n        diagnostic.messageText,\n        \"\\n\"\n      );\n      if (diagnostic.file && diagnostic.start) {\n        const { line, character } =\n          diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n        console.error(\n          `${diagnostic.file.fileName} (${line + 1},${\n            character + 1\n          }): ${message}`\n        );\n      } else {\n        console.error(message);\n      }\n    });\n    throw Error(\"Failed to compile the contract\");\n  }\n\n  const generator = TJS.buildGenerator(program);\n  if (!generator) {\n    throw Error(\n      \"Failed to generate ABI due to an unexpected typescript-json-schema error. Please report this.\"\n    );\n  }\n\n  const abiFunctions: abi.AbiFunction[] = [];\n\n  program.getSourceFiles().forEach((sourceFile, _sourceFileIdx) => {\n    function inspect(node: ts.Node, tc: ts.TypeChecker) {\n      if (node.kind === ts.SyntaxKind.MethodDeclaration) {\n        const methodDeclaration = node as ts.MethodDeclaration;\n        const decorators =\n          methodDeclaration.decorators ||\n          ([] as unknown as NodeArray<Decorator>);\n        let isCall = false;\n        let isView = false;\n        let isInit = false;\n        const abiModifiers: abi.AbiFunctionModifier[] = [];\n        decorators.forEach((decorator) => {\n          if (decorator.expression.kind !== ts.SyntaxKind.CallExpression)\n            return;\n          const decoratorExpression = decorator.expression as ts.CallExpression;\n          if (decoratorExpression.expression.kind !== ts.SyntaxKind.Identifier)\n            return;\n          const decoratorIdentifier =\n            decoratorExpression.expression as ts.Identifier;\n          const decoratorName = decoratorIdentifier.text;\n          if (decoratorName === \"call\") {\n            isCall = true;\n            decoratorExpression.arguments.forEach((arg) => {\n              if (arg.kind !== ts.SyntaxKind.ObjectLiteralExpression) return;\n              const objLiteral = arg as ts.ObjectLiteralExpression;\n              objLiteral.properties.forEach((prop) => {\n                // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                const propName = (prop.name as any).text;\n                if (propName === \"privateFunction\") {\n                  if (prop.kind !== ts.SyntaxKind.PropertyAssignment) return;\n                  const propAssignment = prop as ts.PropertyAssignment;\n                  const init = propAssignment.initializer;\n                  if (init.kind === ts.SyntaxKind.TrueKeyword) {\n                    abiModifiers.push(abi.AbiFunctionModifier.Private);\n                  } else if (init.kind === ts.SyntaxKind.FalseKeyword) {\n                    // Do nothing\n                  } else {\n                    throw Error(\n                      \"Unexpected initializer for `privateFunction`: kind \" +\n                        init.kind\n                    );\n                  }\n                }\n                if (propName === \"payableFunction\") {\n                  if (prop.kind !== ts.SyntaxKind.PropertyAssignment) return;\n                  const propAssignment = prop as ts.PropertyAssignment;\n                  const init = propAssignment.initializer;\n                  if (init.kind === ts.SyntaxKind.TrueKeyword) {\n                    abiModifiers.push(abi.AbiFunctionModifier.Payable);\n                  } else if (init.kind === ts.SyntaxKind.FalseKeyword) {\n                    // Do nothing\n                  } else {\n                    throw Error(\n                      \"Unexpected initializer for `publicFunction`: kind \" +\n                        init.kind\n                    );\n                  }\n                }\n              });\n            });\n          }\n          if (decoratorName === \"view\") isView = true;\n          if (decoratorName === \"initialize\") {\n            isInit = true;\n            abiModifiers.push(abi.AbiFunctionModifier.Init);\n          }\n        });\n        const nearDecoratorsCount = [isCall, isView, isInit].filter(\n          (b) => b\n        ).length;\n        if (nearDecoratorsCount > 1) {\n          throw Error(\n            \"NEAR function cannot be init, call and view at the same time\"\n          );\n        }\n        if (nearDecoratorsCount === 0) {\n          return;\n        }\n        validateNearClass(node.parent);\n\n        let abiParams: abi.AbiJsonParameter[] = [];\n        if (methodDeclaration.parameters.length > 1) {\n          throw Error(\n            \"Expected NEAR function to have a single object parameter, but got \" +\n              methodDeclaration.parameters.length\n          );\n        } else if (methodDeclaration.parameters.length === 1) {\n          const jsonObjectParameter = methodDeclaration.parameters[0];\n          if (!jsonObjectParameter.type) {\n            throw Error(\n              \"Expected NEAR function to have explicit types, e.g. `{ id }: {id : string }`\"\n            );\n          }\n\n          if (jsonObjectParameter.type.kind !== ts.SyntaxKind.TypeLiteral) {\n            throw Error(\n              \"Expected NEAR function to have a single object binding parameter, e.g. `{ id }: { id: string }`\"\n            );\n          }\n\n          const typeLiteral = jsonObjectParameter.type as ts.TypeLiteralNode;\n          abiParams = typeLiteral.members.map((member) => {\n            if (member.kind !== ts.SyntaxKind.PropertySignature) {\n              throw Error(\n                \"Expected NEAR function to have a single object binding parameter, e.g. `{ id }: { id: string }`\"\n              );\n            }\n            const propertySignature = member as ts.PropertySignature;\n            const nodeType = tc.getTypeAtLocation(propertySignature.type);\n            const schema = generator.getTypeDefinition(nodeType, true);\n            const abiParameter: abi.AbiJsonParameter = {\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              name: (propertySignature.name as any).text,\n              type_schema: schema as JSONSchema7,\n            };\n\n            return abiParameter;\n          });\n        }\n        let abiResult: abi.AbiType | undefined = undefined;\n        const returnType = methodDeclaration.type;\n        if (returnType) {\n          const nodeType = tc.getTypeAtLocation(returnType);\n          const schema = generator.getTypeDefinition(nodeType, true);\n          abiResult = {\n            serialization_type: abi.AbiSerializationType.Json,\n            type_schema: schema,\n          };\n        }\n        const abiFunction: abi.AbiFunction = {\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n          name: (methodDeclaration.name as any).text,\n          kind: isView ? abi.AbiFunctionKind.View : abi.AbiFunctionKind.Call,\n        };\n        if (abiModifiers.length > 0) {\n          abiFunction.modifiers = abiModifiers;\n        }\n        if (abiParams.length > 0) {\n          abiFunction.params = {\n            serialization_type: abi.AbiSerializationType.Json,\n            args: abiParams,\n          };\n        }\n        if (abiResult) {\n          abiFunction.result = abiResult;\n        }\n        abiFunctions.push(abiFunction);\n      } else {\n        ts.forEachChild(node, (n) => inspect(n, tc));\n      }\n    }\n    inspect(sourceFile, typeChecker);\n  });\n  const abiRoot: abi.AbiRoot = {\n    schema_version: abi.SCHEMA_VERSION,\n    metadata: parseMetadata(packageJsonPath),\n    body: {\n      functions: abiFunctions,\n      root_schema: generator.getSchemaForSymbol(\n        \"String\",\n        true,\n        false\n      ) as JSONSchema7,\n    },\n  };\n  return abiRoot;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/build-tools/include-bytes.ts",
    "content": "import { PluginPass } from \"@babel/core\";\nimport { Node, Visitor } from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\nimport { readFileSync } from \"fs\";\nimport { join, dirname } from \"path\";\n\nconst assertStringLiteral: typeof t[\"assertStringLiteral\"] =\n  t.assertStringLiteral;\n\nexport default function (): { visitor: Visitor } {\n  return {\n    visitor: {\n      CallExpression(\n        path,\n        { opts, file }: PluginPass & { opts: { root?: string } }\n      ): void {\n        if (!(\"name\" in path.node.callee)) {\n          return;\n        }\n\n        // Extract the called method name.\n        const name = path.node.callee.name;\n\n        // If the method name is not \"includeBytes\" do nothing.\n        if (name === \"includeBytes\") {\n          // Extract the called method arguments.\n          const args = path.node.arguments;\n\n          // Get the path of file\n          const filename = file.opts.filename;\n\n          // User settings\n          const root = opts.root || dirname(filename);\n\n          // Read binary file into bytes, so encoding is 'latin1' (each byte is 0-255, become one character)\n          const encoding = \"latin1\";\n\n          const [firstArg] = args;\n\n          // Require first arg to be a string literal\n          assertStringLiteral(firstArg);\n\n          // Error if filename is not found\n          if (filename === undefined || filename === \"unknown\") {\n            throw new Error(\"`includeBytes` function called outside of file\");\n          }\n\n          if (!(\"value\" in firstArg && typeof firstArg.value === \"string\")) {\n            throw new Error(\n              `\\`includeBytes\\` function called with invalid argument: ${args[0]}`\n            );\n          }\n\n          // Generate and locate the file\n          const fileRelPath = firstArg.value; // Get literal string value\n          const filePath = join(root, fileRelPath);\n          const fileSrc = readFileSync(filePath, { encoding }).toString();\n\n          path.replaceWith(\n            t.callExpression(\n              t.memberExpression(\n                t.identifier(\"env\"),\n                t.identifier(\"latin1_string_to_uint8array\")\n              ),\n              [t.stringLiteral(fileSrc)]\n            ) as Node\n          );\n        }\n      },\n    },\n  };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/build-tools/near-bindgen-exporter.ts",
    "content": "import { PluginPass } from \"@babel/core\";\nimport { Node, Visitor } from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\nimport signal from \"signale\";\n\nconst { Signale } = signal;\n\n/**\n * A list of supported method types/decorators.\n */\nconst methodTypes = [\"call\", \"view\", \"initialize\", \"migrate\"];\n\n/**\n * A helper function that inserts a new throw Error statement with\n * the passed message.\n *\n * @param message - The message to throw inside the error\n */\nfunction throwError(message: string): t.BlockStatement {\n  return t.blockStatement([\n    t.throwStatement(\n      t.newExpression(t.identifier(\"Error\"), [t.stringLiteral(message)])\n    ),\n  ]);\n}\n\n/**\n * A helper function that inserts a new state reading expression.\n * It reads state into _\\_state_ via _\\_getState_.\n *\n * ```typescript\n * const _state = Contract._getState();\n * ```\n *\n * @param classId - The class ID of the class which we are extending.\n */\nfunction readState(classId: t.Identifier, methodType: string): t.VariableDeclaration {\n  if (methodType === \"migrate\") {\n    return t.variableDeclaration(\"const\", [\n      t.variableDeclarator(\n        t.identifier(\"_state\"),\n        t.nullLiteral()\n      ),\n    ]);\n  }\n\n  return t.variableDeclaration(\"const\", [\n    t.variableDeclarator(\n      t.identifier(\"_state\"),\n      t.callExpression(\n        t.memberExpression(classId, t.identifier(\"_getState\")),\n        []\n      )\n    ),\n  ]);\n}\n\n/**\n * A helper function that inserts a double initialization check.\n *\n * ```typescript\n * if (_state) {\n *   throw new Error('Contract already initialized');\n * }\n * ```\n *\n * @param methodType - The type of the method being called.\n */\nfunction preventDoubleInit(\n  methodType: string\n): t.EmptyStatement | t.IfStatement {\n  if (methodType !== \"initialize\") {\n    return t.emptyStatement();\n  }\n\n  return t.ifStatement(\n    t.identifier(\"_state\"),\n    throwError(\"Contract already initialized\")\n  );\n}\n\n/**\n * A helper function that inserts a initialization check.\n *\n * ```typescript\n * if (!_state) {\n *   throw new Error('Contract must be initialized');\n * }\n * ```\n *\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n *\n * @returns {t.EmptyStatement | t.IfStatement}\n */\nfunction ensureInitBeforeCall(\n  classId: t.Identifier,\n  methodType: string\n): t.EmptyStatement | t.IfStatement {\n  if (![\"call\", \"view\"].includes(methodType)) {\n    return t.emptyStatement();\n  }\n\n  return t.ifStatement(\n    t.logicalExpression(\n      \"&&\",\n      t.unaryExpression(\"!\", t.identifier(\"_state\")),\n      t.callExpression(\n        t.memberExpression(classId, t.identifier(\"_requireInit\")),\n        []\n      )\n    ),\n    throwError(\"Contract must be initialized\")\n  );\n}\n\n/**\n * A helper function that inserts a contract creation expression.\n * It creates a new instance of the class by calling the _\\_create_ method\n * on the contract class.\n *\n * ```typescript\n * let _contract = Contract._create();\n * ```\n *\n * @param classId - The class ID of the class being extended.\n */\nfunction initializeContractClass(classId: t.Identifier): t.VariableDeclaration {\n  return t.variableDeclaration(\"const\", [\n    t.variableDeclarator(\n      t.identifier(\"_contract\"),\n      t.callExpression(t.memberExpression(classId, t.identifier(\"_create\")), [])\n    ),\n  ]);\n}\n\n/**\n * A helper function that inserts a state reconstruction statement.\n * It calls the _\\_reconstruct_ method on the _\\_contract_ object.\n *\n * ```typescript\n * if (_state) {\n *   Contract._reconstruct(_contract, _state);\n * }\n * ```\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n */\nfunction reconstructState(\n  classId: t.Identifier,\n  methodType: string\n): t.EmptyStatement | t.IfStatement {\n  if (![\"call\", \"view\"].includes(methodType)) {\n    return t.emptyStatement();\n  }\n\n  return t.ifStatement(\n    t.identifier(\"_state\"),\n    t.blockStatement([\n      t.expressionStatement(\n        t.callExpression(\n          t.memberExpression(classId, t.identifier(\"_reconstruct\")),\n          [t.identifier(\"_contract\"), t.identifier(\"_state\")]\n        )\n      ),\n    ])\n  );\n}\n\n/**\n * A helper function that inserts a argument collection expression.\n * It calls the _\\_getArgs_ function on the class object.\n *\n * ```typescript\n * const _args = Contract._getArgs();\n * ```\n * @param classId - The class ID of the class being extended.\n */\nfunction collectArguments(classId: t.Identifier): t.VariableDeclaration {\n  return t.variableDeclaration(\"const\", [\n    t.variableDeclarator(\n      t.identifier(\"_args\"),\n      t.callExpression(\n        t.memberExpression(classId, t.identifier(\"_getArgs\")),\n        []\n      )\n    ),\n  ]);\n}\n\n/**\n * A helper function that inserts a contract method call expression.\n * It calls the appropriate contract method and passes the collected _\\_args_.\n *\n * ```typescript\n * const _result = _contract.method(args);\n * ```\n *\n * @param methodName - The name of the method being called.\n */\nfunction callContractMethod(methodName: string): t.VariableDeclaration {\n  return t.variableDeclaration(\"const\", [\n    t.variableDeclarator(\n      t.identifier(\"_result\"),\n      t.callExpression(\n        t.memberExpression(t.identifier(\"_contract\"), t.identifier(methodName)),\n        [t.identifier(\"_args\")]\n      )\n    ),\n  ]);\n}\n\n/**\n * A helper function that inserts a save to storage expression.\n * It calls the _\\_saveToStorage_ method if a initialize or call method is called.\n *\n * ```typescript\n * Contract._saveToStorage(_contract);\n * ```\n *\n * @param classId - The class ID of the class being extended.\n * @param methodType - The type of the method being called.\n */\nfunction saveToStorage(\n  classId: t.Identifier,\n  methodType: string\n): t.EmptyStatement | t.ExpressionStatement {\n  if (![\"initialize\", \"call\", \"migrate\"].includes(methodType)) {\n    return t.emptyStatement();\n  }\n\n  return t.expressionStatement(\n    t.callExpression(\n      t.memberExpression(classId, t.identifier(\"_saveToStorage\")),\n      [t.identifier(\"_contract\")]\n    )\n  );\n}\n\n/**\n * A helper function that inserts a NearPromise execution call or a valuer return call.\n * It checks for the return type of the called function and either performs a NearPromise\n * _onReturn_ call or a _value\\_return_ environment function to return the value to the callee.\n *\n * ```typescript\n * if (_result !== undefined) {\n *   if (_result && _result.constructor && _result.constructor.name === 'NearPromise') {\n *     _result.onReturn();\n *   } else {\n *     near.valueReturnRaw(_contract._serialize(result));\n *   }\n * }\n * ```\n *\n * @param classId - The class ID of the class being extended.\n */\nfunction executePromise(classId: t.Identifier): t.IfStatement {\n  return t.ifStatement(\n    t.binaryExpression(\n      \"!==\",\n      t.identifier(\"_result\"),\n      t.identifier(\"undefined\")\n    ),\n    t.ifStatement(\n      t.logicalExpression(\n        \"&&\",\n        t.logicalExpression(\n          \"&&\",\n          t.identifier(\"_result\"),\n          t.memberExpression(\n            t.identifier(\"_result\"),\n            t.identifier(\"constructor\")\n          )\n        ),\n        t.binaryExpression(\n          \"===\",\n          t.memberExpression(\n            t.memberExpression(\n              t.identifier(\"_result\"),\n              t.identifier(\"constructor\")\n            ),\n            t.identifier(\"name\")\n          ),\n          t.stringLiteral(\"NearPromise\")\n        )\n      ),\n      t.expressionStatement(\n        t.callExpression(\n          t.memberExpression(t.identifier(\"_result\"), t.identifier(\"onReturn\")),\n          []\n        )\n      ),\n      t.expressionStatement(\n        t.callExpression(\n          t.memberExpression(t.identifier(\"env\"), t.identifier(\"value_return\")),\n          [\n            t.callExpression(\n              t.memberExpression(classId, t.identifier(\"_serialize\")),\n              [t.identifier(\"_result\"), t.booleanLiteral(true)]\n            ),\n          ]\n        )\n      )\n    )\n  );\n}\n\n/**\n * A helper function that inserts the overridden function declaration into the class.\n *\n * @param classId - The class ID of the class being extended.\n * @param methodName - The name of the method being called.\n * @param methodType - The type of the method being called.\n */\nfunction createDeclaration(\n  classId: t.Identifier,\n  methodName: string,\n  methodType: string\n): t.ExportNamedDeclaration {\n  return t.exportNamedDeclaration(\n    t.functionDeclaration(\n      t.identifier(methodName),\n      [],\n      t.blockStatement([\n        // Read the state of the contract from storage.\n        // const _state = Contract._getState();\n        readState(classId, methodType),\n        // Throw if initialized on any subsequent init function calls.\n        // if (_state) { throw new Error('Contract already initialized'); }\n        preventDoubleInit(methodType),\n        // Throw if NOT initialized on any non init function calls.\n        // if (!_state) { throw new Error('Contract must be initialized'); }\n        ensureInitBeforeCall(classId, methodType),\n        // Create instance of contract by calling _create function.\n        // let _contract = Contract._create();\n        initializeContractClass(classId),\n        // Reconstruct the contract with the state if the state is valid.\n        // if (_state) { Contract._reconstruct(_contract, _state); }\n        reconstructState(classId, methodType),\n        // Collect the arguments sent to the function.\n        // const _args = Contract._getArgs();\n        collectArguments(classId),\n        // Perform the actual function call to the appropriate contract method.\n        // const _result = _contract.method(args);\n        callContractMethod(methodName),\n        // If the method called is either an initialize or call method type, save the changes to storage.\n        // Contract._saveToStorage(_contract);\n        saveToStorage(classId, methodType),\n        // If a NearPromise is returned from the function call the onReturn method to execute the promise.\n        // if (_result !== undefined)\n        //   if (_result && _result.constructor && _result.constructor.name === 'NearPromise')\n        //     _result.onReturn();\n        //   else\n        //     near.valueReturnRaw(_contract._serialize(result));\n        executePromise(classId),\n      ])\n    )\n  );\n}\n\nexport default function (): { visitor: Visitor } {\n  return {\n    visitor: {\n      ClassDeclaration(\n        path,\n        { opts: { verbose } }: PluginPass & { opts: { verbose: boolean } }\n      ): void {\n        // Capture the node of the current path.\n        const classNode = path.node;\n\n        // Check that the class is decorated with NearBindgen otherwise do nothing.\n        if (\n          classNode.decorators &&\n          \"callee\" in classNode.decorators[0].expression &&\n          \"name\" in classNode.decorators[0].expression.callee &&\n          classNode.decorators[0].expression.callee.name === \"NearBindgen\"\n        ) {\n          // Iterate over the children of the class node.\n          classNode.body.body.forEach((child) => {\n            // Check that the child is a class method and has decorators.\n            if (\n              child.type === \"ClassMethod\" &&\n              child.kind === \"method\" &&\n              child.decorators &&\n              \"callee\" in child.decorators[0].expression &&\n              \"name\" in child.decorators[0].expression.callee\n            ) {\n              // Capture the decorator name.\n              const methodType = child.decorators[0].expression.callee.name;\n\n              // Check that the decorator is one of the supported method types.\n              if (methodTypes.includes(methodType) && \"name\" in child.key) {\n                // Insert the method override into the class declaration.\n                path.insertAfter(\n                  createDeclaration(\n                    classNode.id as t.Identifier,\n                    child.key.name,\n                    methodType\n                  ) as Node\n                );\n\n                if (verbose) {\n                  new Signale({\n                    scope: \"near-bindgen-exporter\",\n                  }).info(`Babel ${child.key.name} method export done.`);\n                }\n              }\n            }\n          });\n        }\n      },\n    },\n  };\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/cli.ts",
    "content": "#!/usr/bin/env node\n\nimport fs from \"fs\";\nimport path, { basename, dirname } from \"path\";\n\nimport { nodeResolve } from \"@rollup/plugin-node-resolve\";\nimport sourcemaps from \"rollup-plugin-sourcemaps\";\nimport { babel } from \"@rollup/plugin-babel\";\nimport { rollup } from \"rollup\";\nimport { Command } from \"commander\";\nimport signal from \"signale\";\n\nimport { executeCommand, validateContract } from \"./utils.js\";\nimport { runAbiCompilerPlugin } from \"./abi.js\";\n\nconst { Signale } = signal;\nconst PROJECT_DIR = process.cwd();\nconst NEAR_SDK_JS = \"node_modules/near-sdk-js\";\nconst TSC = \"node_modules/.bin/tsc\";\nconst QJSC_DIR = `${NEAR_SDK_JS}/lib/cli/deps/quickjs`;\nconst QJSC = `${NEAR_SDK_JS}/lib/cli/deps/qjsc`;\n\nconst program = new Command();\n\nprogram\n  .name(\"near-sdk-js\")\n  .addCommand(\n    new Command(\"build\")\n      .usage(\"[source] [target]\")\n      .description(\"Build NEAR JS Smart-contract\")\n      .argument(\"[source]\", \"Contract to build.\", \"src/index.js\")\n      .argument(\"[target]\", \"Target file path and name.\", \"build/contract.wasm\")\n      .argument(\"[packageJson]\", \"Target file path and name.\", \"package.json\")\n      .argument(\"[tsConfig]\", \"Target file path and name.\", \"tsconfig.json\")\n      .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n      .option(\"--generateABI\", \"Whether to generate ABI.\", false)\n      .action(buildCom)\n  )\n  .addCommand(\n    new Command(\"validateContract\")\n      .usage(\"[source]\")\n      .description(\n        \"Validate a NEAR JS Smart-contract. Validates the contract by checking that all parameters are initialized in the constructor. Works only for typescript.\"\n      )\n      .argument(\"[source]\", \"Contract to validate.\", \"src/index.ts\")\n      .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n      .action(validateCom)\n  )\n  .addCommand(\n    new Command(\"checkTypescript\")\n      .usage(\"[source]\")\n      .description(\n        \"Run TSC with some cli flags - warning - ignores tsconfig.json.\"\n      )\n      .argument(\"[source]\", \"Typescript file to validate\", \"src/index.ts\")\n      .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n      .action(checkTypescriptCom)\n  )\n  .addCommand(\n    new Command(\"createJsFileWithRollup\")\n      .usage(\"[source] [target]\")\n      .description(\n        \"Create intermediate javascript file for later processing with QJSC\"\n      )\n      .argument(\"[source]\", \"Contract to build.\", \"src/index.js\")\n      .argument(\n        \"[target]\",\n        \"Target file path and name. The default corresponds to contract.js\",\n        \"build/contract.wasm\"\n      )\n      .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n      .action(createJsFileWithRollupCom)\n  )\n  .addCommand(\n    new Command(\"transpileJsAndBuildWasm\")\n      .usage(\"[source] [target]\")\n      .description(\n        \"Transpiles the target javascript file into .c and .h using QJSC then compiles that into wasm using clang\"\n      )\n      .argument(\n        \"[target]\",\n        \"Target file path and name. The js file must correspond to the same path with the js extension.\",\n        \"build/contract.wasm\"\n      )\n      .option(\"--verbose\", \"Whether to print more verbose output.\", false)\n      .action(transpileJsAndBuildWasmCom)\n  )\n  .parse();\n\nfunction getTargetDir(target: string): string {\n  return dirname(target);\n}\n\nfunction getTargetExt(target: string): string {\n  return target.split(\".\").pop();\n}\n\nfunction getTargetFileName(target: string): string {\n  return basename(target, `.${getTargetExt(target)}`);\n}\n\nfunction getRollupTarget(target: string): string {\n  return `${getTargetDir(target)}/${getTargetFileName(target)}.js`;\n}\n\nfunction getQjscTarget(target: string): string {\n  return `${getTargetDir(target)}/${getTargetFileName(target)}.h`;\n}\n\nfunction getContractTarget(target: string): string {\n  return `${getTargetDir(target)}/${getTargetFileName(target)}.wasm`;\n}\n\nfunction getContractAbi(target: string): string {\n  return `${getTargetDir(target)}/${getTargetFileName(target)}-abi.json`;\n}\n\nfunction requireTargetExt(target: string): void {\n  if (getTargetExt(target) === \"wasm\") {\n    return;\n  }\n\n  signal.error(\n    `Unsupported target ${getTargetExt(\n      target\n    )}, make sure target ends with .wasm!`\n  );\n  process.exit(1);\n}\n\nfunction ensureTargetDirExists(target: string): void {\n  const targetDir = getTargetDir(target);\n  if (fs.existsSync(targetDir)) {\n    return;\n  }\n\n  signal.await(`Creating ${targetDir} directory...`);\n  fs.mkdirSync(targetDir, {});\n}\n\nexport async function validateCom(\n  source: string,\n  { verbose = false }: { verbose: boolean }\n): Promise<void> {\n  const signale = new Signale({ scope: \"validate\", interactive: !verbose });\n\n  signale.await(`Validating ${source} contract...`);\n\n  if (!(await validateContract(source, verbose))) {\n    process.exit(1);\n  }\n}\n\nexport async function checkTypescriptCom(\n  source: string,\n  { verbose = false }: { verbose: boolean }\n): Promise<void> {\n  const signale = new Signale({\n    scope: \"checkTypescript\",\n    interactive: !verbose,\n  });\n\n  const sourceExt = source.split(\".\").pop();\n  if (sourceExt !== \"ts\") {\n    signale.info(`Source file is not a typescript file ${source}`);\n    return;\n  }\n\n  signale.await(`Typechecking ${source} with tsc...`);\n  await checkTsBuildWithTsc(source, verbose);\n}\n\nexport async function generateAbi(\n  source: string,\n  target: string,\n  packageJson: string,\n  tsConfig: string,\n  { verbose = false }: { verbose: boolean }\n): Promise<void> {\n  const signale = new Signale({ scope: \"generateAbi\", interactive: !verbose });\n\n  const sourceExt = source.split(\".\").pop();\n  if (sourceExt !== \"ts\") {\n    signale.info(\n      `Skipping ABI generation as source file is not a typescript file ${source}`\n    );\n    return;\n  }\n\n  signale.await(\"Generating ABI...\");\n  const abi = runAbiCompilerPlugin(source, packageJson, tsConfig);\n  fs.writeFileSync(getContractAbi(target), JSON.stringify(abi, null, 2));\n  signale.success(`Generated ${getContractAbi(target)} ABI successfully!`);\n}\n\nexport async function createJsFileWithRollupCom(\n  source: string,\n  target: string,\n  { verbose = false }: { verbose: boolean }\n): Promise<void> {\n  const signale = new Signale({\n    scope: \"createJsFileWithRollup\",\n    interactive: !verbose,\n  });\n\n  requireTargetExt(target);\n  ensureTargetDirExists(target);\n\n  signale.await(`Creating ${source} file with Rollup...`);\n  await createJsFileWithRullup(source, getRollupTarget(target), verbose);\n}\n\nexport async function transpileJsAndBuildWasmCom(\n  target: string,\n  { verbose = false }: { verbose: boolean }\n): Promise<void> {\n  const signale = new Signale({\n    scope: \"transpileJsAndBuildWasm\",\n    interactive: !verbose,\n  });\n\n  requireTargetExt(target);\n  ensureTargetDirExists(target);\n\n  signale.await(`Creating ${getQjscTarget(target)} file with QJSC...`);\n  await createHeaderFileWithQjsc(\n    getRollupTarget(target),\n    getQjscTarget(target),\n    verbose\n  );\n\n  signale.await(\"Generating methods.h file...\");\n  await createMethodsHeaderFile(getRollupTarget(target), verbose);\n\n  signale.await(`Creating ${getContractTarget(target)} contract...`);\n  await createWasmContract(\n    getQjscTarget(target),\n    getContractTarget(target),\n    verbose\n  );\n\n  signale.await(\"Executing wasi-stub...\");\n  await wasiStubContract(getContractTarget(target), verbose);\n\n  signale.success(\n    `Generated ${getContractTarget(target)} contract successfully!`\n  );\n}\n\nexport async function buildCom(\n  source: string,\n  target: string,\n  packageJson: string,\n  tsConfig: string,\n  { verbose = false, generateABI = false }: { verbose: boolean, generateABI: boolean },\n): Promise<void> {\n  const signale = new Signale({ scope: \"build\", interactive: !verbose });\n\n  requireTargetExt(target);\n\n  signale.await(`Building ${source} contract...`);\n\n  await checkTypescriptCom(source, { verbose });\n\n  ensureTargetDirExists(target);\n\n  if (generateABI) {\n    await generateAbi(source, target, packageJson, tsConfig, { verbose });\n  }\n\n  await validateCom(source, { verbose });\n\n  await createJsFileWithRollupCom(source, target, { verbose });\n\n  await transpileJsAndBuildWasmCom(target, { verbose });\n}\n\nasync function checkTsBuildWithTsc(\n  sourceFileWithPath: string,\n  verbose = false\n) {\n  await executeCommand(\n    `${TSC} --noEmit --skipLibCheck --experimentalDecorators --target es2020 --moduleResolution node ${sourceFileWithPath}`,\n    verbose\n  );\n}\n\n// Common build function\nasync function createJsFileWithRullup(\n  sourceFileWithPath: string,\n  rollupTarget: string,\n  verbose = false\n) {\n  const bundle = await rollup({\n    input: sourceFileWithPath,\n    plugins: [\n      nodeResolve({\n        extensions: [\".js\", \".ts\"],\n      }),\n      sourcemaps(),\n      // commonjs(),\n      babel({\n        babelHelpers: \"bundled\",\n        extensions: [\".ts\", \".js\", \".jsx\", \".es6\", \".es\", \".mjs\"],\n        presets: [\"@babel/preset-typescript\"],\n        plugins: [\n          \"near-sdk-js/lib/cli/build-tools/include-bytes.js\",\n          [\n            \"near-sdk-js/lib/cli/build-tools/near-bindgen-exporter.js\",\n            { verbose },\n          ],\n          [\"@babel/plugin-proposal-decorators\", { version: \"legacy\" }],\n        ],\n      }),\n    ],\n  });\n\n  await bundle.write({\n    sourcemap: true,\n    file: rollupTarget,\n    format: \"es\",\n  });\n}\n\nasync function createHeaderFileWithQjsc(\n  rollupTarget: string,\n  qjscTarget: string,\n  verbose = false\n) {\n  await executeCommand(\n    `${QJSC} -c -m -o ${qjscTarget} -N code ${rollupTarget}`,\n    verbose\n  );\n}\n\nasync function createMethodsHeaderFile(rollupTarget: string, verbose = false) {\n  const buildPath = path.dirname(rollupTarget);\n\n  if (verbose) {\n    new Signale({ scope: \"method-header\" }).info(rollupTarget);\n  }\n\n  const mod = await import(`${PROJECT_DIR}/${rollupTarget}`);\n  const exportNames = Object.keys(mod);\n  if (exportNames.includes('panic')) {\n    signal.error(\n      \"'panic' is a reserved word, please use another name for contract method\"\n    );\n    process.exit(1);\n  }\n  const methods = exportNames.reduce(\n    (result, key) => `${result}DEFINE_NEAR_METHOD(${key})\\n`,\n    \"\"\n  );\n\n  fs.writeFileSync(`${buildPath}/methods.h`, methods);\n}\n\nasync function createWasmContract(\n  qjscTarget: string,\n  contractTarget: string,\n  verbose = false\n) {\n  const WASI_SDK_PATH = `${NEAR_SDK_JS}/lib/cli/deps/wasi-sdk`;\n\n  const CC = `${WASI_SDK_PATH}/bin/clang --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot`;\n  const DEFS = `-D_GNU_SOURCE '-DCONFIG_VERSION=\"2021-03-27\"' -DCONFIG_BIGNUM`;\n\n  const INCLUDES = `-I${QJSC_DIR} -I.`;\n  const ORIGINAL_BUILDER_PATH = `${NEAR_SDK_JS}/builder/builder.c`;\n  const NEW_BUILDER_PATH = `${path.dirname(contractTarget)}/builder.c`;\n  const SOURCES = `${NEW_BUILDER_PATH} ${QJSC_DIR}/quickjs.c ${QJSC_DIR}/libregexp.c ${QJSC_DIR}/libunicode.c ${QJSC_DIR}/cutils.c ${QJSC_DIR}/quickjs-libc-min.c ${QJSC_DIR}/libbf.c`;\n  const LIBS = `-lm`;\n\n  // copying builder.c file to the build folder\n  fs.cpSync(ORIGINAL_BUILDER_PATH, NEW_BUILDER_PATH);\n\n  fs.renameSync(qjscTarget, \"build/code.h\");\n\n  await executeCommand(\n    `${CC} --target=wasm32-wasi -nostartfiles -Oz -flto ${DEFS} ${INCLUDES} ${SOURCES} ${LIBS} -Wl,--no-entry -Wl,--allow-undefined -Wl,-z,stack-size=${\n      256 * 1024\n    } -Wl,--lto-O3 -o ${contractTarget}`,\n    verbose\n  );\n}\n\nasync function wasiStubContract(contractTarget: string, verbose = false) {\n  const WASI_STUB = `${NEAR_SDK_JS}/lib/cli/deps/binaryen/wasi-stub/run.sh`;\n  await executeCommand(`${WASI_STUB} ${contractTarget}`, verbose);\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/post-install.ts",
    "content": "import { executeCommand, download } from \"./utils.js\";\nimport signal from \"signale\";\nimport os from \"os\";\nimport fs from \"fs\";\n\nconst { Signale } = signal;\n\nconst signale = new Signale({ scope: \"postinstall\", interactive: true });\n\n// Clean existing deps folder\nprocess.chdir(\"lib/cli\");\nconst DEPS = \"deps\";\nfs.rmSync(DEPS, { recursive: true, force: true });\nfs.mkdirSync(DEPS);\nprocess.chdir(DEPS);\n\nconst PLATFORM = os.platform();\nconst ARCH = os.arch();\nconsole.log(`Current platform: ${PLATFORM}, current architecture: ${ARCH}`);\n\nconst SUPPORTED_PLATFORMS = [\"linux\", \"darwin\"]; // Unsupported platforms: 'win32', 'aix', 'freebsd', 'openbsd', 'sunos', 'android'\nconst SUPPORTED_ARCH = [\"x64\", \"arm64\"]; // Unsupported arch: 'arm', 'ia32', 'mips','mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32'\n\nif (!SUPPORTED_PLATFORMS.includes(PLATFORM)) {\n  console.error(`Platform ${PLATFORM} is not supported at the moment`);\n  process.exit(1);\n}\n\nif (!SUPPORTED_ARCH.includes(ARCH)) {\n  console.error(`Architecture ${ARCH} is not supported at the moment`);\n  process.exit(1);\n}\n\nsignale.await(\"Installing wasi-stub...\");\n\nconst BINARYEN_VERSION = `0.1.16`;\nconst BINARYEN_VERSION_TAG = `v${BINARYEN_VERSION}`;\n\nconst BINARYEN_SYSTEM_NAME =\n  PLATFORM === \"linux\"\n    ? \"Linux\"\n    : PLATFORM === \"darwin\"\n    ? \"macOS\"\n    : PLATFORM === \"win32\"\n    ? \"windows\"\n    : \"other\";\n\nconst BINARYEN_ARCH_NAME = (ARCH == 'aarch64') ? 'ARM64' : ARCH.toUpperCase();\n\nconst BINARYEN_TAR_NAME = `binaryen-${BINARYEN_SYSTEM_NAME}-${BINARYEN_ARCH_NAME}.tar.gz`;\n\nawait download(\n  `https://github.com/ailisp/binaryen/releases/download/${BINARYEN_VERSION_TAG}/${BINARYEN_TAR_NAME}`\n);\n\nfs.mkdirSync(\"binaryen\");\n\nawait executeCommand(`tar xvf ${BINARYEN_TAR_NAME} --directory binaryen`);\nfs.rmSync(BINARYEN_TAR_NAME);\n\nsignale.await(\"Installing QuickJS...\");\n\nconst QUICK_JS_VERSION = `0.1.3`;\nconst QUICK_JS_VERSION_TAG = `v${QUICK_JS_VERSION}`;\n\nconst QUICK_JS_SYSTEM_NAME =\n  PLATFORM === \"linux\"\n    ? \"Linux\"\n    : PLATFORM === \"darwin\"\n    ? \"macOS\"\n    : PLATFORM === \"win32\"\n    ? \"windows\"\n    : \"other\";\n\nconst QUICK_JS_ARCH_NAME =\n  ARCH === \"x64\" ? \"X64\" : ARCH === \"arm64\" ? \"arm64\" : \"other\";\n\nconst QUICK_JS_TAR_NAME = `${QUICK_JS_VERSION_TAG}.tar.gz`;\nconst QUICK_JS_DOWNLOADED_FOLDER_NAME = `quickjs-${QUICK_JS_VERSION}`;\nconst QUICK_JS_TARGET_FOLDER_NAME = \"quickjs\";\nconst QUICK_JS_DOWNLOADED_NAME = `qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_JS_ARCH_NAME}`;\nconst QUICK_JS_TARGET_NAME = \"qjsc\";\n\n// Download QuickJS\nawait download(\n  `https://github.com/near/quickjs/releases/download/${QUICK_JS_VERSION_TAG}/qjsc-${QUICK_JS_SYSTEM_NAME}-${QUICK_JS_ARCH_NAME}`\n);\nawait download(\n  `https://github.com/near/quickjs/archive/refs/tags/${QUICK_JS_VERSION_TAG}.tar.gz`\n);\n\n// Extract QuickJS\nawait executeCommand(`tar xvf ${QUICK_JS_TAR_NAME}`);\n\n// Delete .tar file\nfs.rmSync(QUICK_JS_TAR_NAME);\n\n// Delete version from folder name\nfs.renameSync(QUICK_JS_DOWNLOADED_FOLDER_NAME, QUICK_JS_TARGET_FOLDER_NAME);\n\n// Rename qjsc file\nfs.renameSync(QUICK_JS_DOWNLOADED_NAME, QUICK_JS_TARGET_NAME);\n\n// chmod qjsc\nfs.chmodSync(QUICK_JS_TARGET_NAME, 0o755);\n\nsignale.await(\"Installing wasi-sdk...\");\n\nconst WASI_SDK_MAJOR_VER = 11;\nconst WASI_SDK_MINOR_VER = 0;\nconst WASI_SDK_DOWNLOADED_FOLDER_NAME = `wasi-sdk-${WASI_SDK_MAJOR_VER}.${WASI_SDK_MINOR_VER}`;\nconst WASI_SDK_SYSTEM_NAME =\n  PLATFORM === \"linux\"\n    ? \"linux\"\n    : PLATFORM === \"darwin\"\n    ? \"macos\"\n    : PLATFORM === \"win32\"\n    ? \"windows\"\n    : \"other\";\nconst WASI_SDK_TAR_NAME = `${WASI_SDK_DOWNLOADED_FOLDER_NAME}-${WASI_SDK_SYSTEM_NAME}.tar.gz`;\n\n// Download WASI SDK\nawait download(\n  `https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_MAJOR_VER}/${WASI_SDK_TAR_NAME}`\n);\n\n// Extract WASI SDK\nawait executeCommand(`tar xvf ${WASI_SDK_TAR_NAME}`);\n\n// Delete .tar file\nfs.rmSync(WASI_SDK_TAR_NAME);\n\n// Delete version from folder name\nfs.renameSync(WASI_SDK_DOWNLOADED_FOLDER_NAME, \"wasi-sdk\");\n\nsignale.success(\"Successfully finished postinstall script!\");\n"
  },
  {
    "path": "packages/near-sdk-js/src/cli/utils.ts",
    "content": "import childProcess from \"child_process\";\nimport { promisify } from \"util\";\nimport signal from \"signale\";\nimport { Project } from \"ts-morph\";\nimport chalk from \"chalk\";\n\nconst { Signale } = signal;\n\nconst exec = promisify(childProcess.exec);\n\nexport async function executeCommand(\n  command: string,\n  verbose = false\n): Promise<string> {\n  const signale = new Signale({ scope: \"exec\", interactive: !verbose });\n\n  if (verbose) {\n    signale.info(`Running command: ${command}`);\n  }\n\n  let stdout,\n    stderr,\n    code = 0;\n  try {\n    ({ stdout, stderr } = await exec(command));\n  } catch (error) {\n    ({ stdout, stderr, code } = error);\n  }\n  if (code != 0) {\n    signale.error(`Command failed: ${command}`);\n\n    const failDueToNameConflict = stderr.match(/conflicting types for '([a-zA-Z0-9_]+)'/);\n    if (failDueToNameConflict && failDueToNameConflict.length > 1) {\n      signale.error(`'${failDueToNameConflict[1]}' is a reserved word, please use another name for contract method\"`);\n    }\n  }\n  if (stderr && verbose) {\n    signale.error(`Command stderr: ${stderr}`);\n  }\n  if (verbose) {\n    signale.info(`Command stdout: ${stdout}`);\n  }\n  if (code != 0) {\n    process.exit(1);\n  }\n  return stdout.trim();\n}\n\nexport async function download(url: string, verbose = false) {\n  await executeCommand(`curl -LOf ${url}`, verbose);\n}\n\nconst UNINITIALIZED_PARAMETERS_ERROR =\n  \"All parameters must be initialized in the constructor. Uninitialized parameters:\";\n\n/**\n * Validates the contract by checking that all parameters are initialized in the constructor. Works only for contracts written in TypeScript.\n *\n * @param contractPath - Path to the contract.\n * @param verbose - Whether to print verbose output.\n **/\nexport async function validateContract(\n  contractPath: string,\n  verbose = false\n): Promise<boolean> {\n  const signale = new Signale({ scope: \"validate-contract\" });\n\n  const project = new Project();\n  project.addSourceFilesAtPaths(contractPath);\n\n  const sourceFile = project.getSourceFile(contractPath);\n  const classDeclarations = sourceFile.getClasses();\n\n  for (const classDeclaration of classDeclarations) {\n    const classStructure = classDeclaration.getStructure();\n    const { decorators, properties, name } = classStructure;\n    const hasNearBindgen = decorators.some(\n      ({ name }) => name === \"NearBindgen\"\n    );\n\n    if (hasNearBindgen) {\n      if (verbose) {\n        signale.info(`Validating ${name} class...`);\n      }\n\n      const constructors = classDeclaration.getConstructors();\n      const hasConstructor = constructors.length > 0;\n      const propertiesToBeInited = properties.filter(\n        ({ initializer }) => !initializer\n      );\n\n      if (!hasConstructor && propertiesToBeInited.length === 0) {\n        return true;\n      }\n\n      if (!hasConstructor && propertiesToBeInited.length > 0) {\n        signale.error(\n          chalk.redBright(\n            `${UNINITIALIZED_PARAMETERS_ERROR} ${propertiesToBeInited\n              .map(({ name }) => name)\n              .join(\", \")}`\n          )\n        );\n        return false;\n      }\n\n      const [constructor] = constructors;\n      const constructorContent = constructor.getText();\n\n      if (verbose) {\n        signale.info(\"Checking for non initialized properties...\");\n      }\n\n      const nonInitedProperties = propertiesToBeInited.reduce(\n        (properties, { name }) => {\n          if (constructorContent.includes(`this.${name}`)) {\n            return properties;\n          }\n\n          return [...properties, name];\n        },\n        [] as string[]\n      );\n\n      if (nonInitedProperties.length > 0) {\n        signale.error(\n          chalk.redBright(\n            `${UNINITIALIZED_PARAMETERS_ERROR} ${nonInitedProperties.join(\n              \", \"\n            )}`\n          )\n        );\n        return false;\n      }\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/index.ts",
    "content": "export * from \"./lookup-map\";\nexport * from \"./lookup-set\";\nexport * from \"./unordered-map\";\nexport * from \"./unordered-set\";\nexport * from \"./vector\";\nexport * from \"./subtype\";\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/lookup-map.ts",
    "content": "import * as near from \"../api\";\nimport { GetOptions } from \"../types/collections\";\nimport {\n  getValueWithOptions,\n  serializeValueWithOptions,\n  encode,\n} from \"../utils\";\nimport { SubType } from \"./subtype\";\n\n/**\n * A lookup map that stores data in NEAR storage.\n */\nexport class LookupMap<DataType> extends SubType<DataType> {\n  /**\n   * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n   */\n  constructor(readonly keyPrefix: string) {\n    super();\n  }\n\n  /**\n   * Checks whether the collection contains the value.\n   *\n   * @param key - The value for which to check the presence.\n   */\n  containsKey(key: string): boolean {\n    const storageKey = this.keyPrefix + key;\n    return near.storageHasKey(storageKey);\n  }\n\n  /**\n   * Get the data stored at the provided key.\n   *\n   * @param key - The key at which to look for the data.\n   * @param options - Options for retrieving the data.\n   */\n  get(\n    key: string,\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): DataType | null {\n    const storageKey = this.keyPrefix + key;\n    const value = near.storageReadRaw(encode(storageKey));\n    if (options == undefined) {\n      options = {};\n    }\n    options = this.set_reconstructor(options);\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Removes and retrieves the element with the provided key.\n   *\n   * @param key - The key at which to remove data.\n   * @param options - Options for retrieving the data.\n   */\n  remove(\n    key: string,\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): DataType | null {\n    const storageKey = this.keyPrefix + key;\n\n    if (!near.storageRemove(storageKey)) {\n      return options?.defaultValue ?? null;\n    }\n\n    const value = near.storageGetEvictedRaw();\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Store a new value at the provided key.\n   *\n   * @param key - The key at which to store in the collection.\n   * @param newValue - The value to store in the collection.\n   * @param options - Options for retrieving and storing the data.\n   */\n  set(\n    key: string,\n    newValue: DataType,\n    options?: GetOptions<DataType>\n  ): DataType | null {\n    const storageKey = this.keyPrefix + key;\n    const storageValue = serializeValueWithOptions(newValue, options);\n\n    if (!near.storageWriteRaw(encode(storageKey), storageValue)) {\n      return options?.defaultValue ?? null;\n    }\n\n    const value = near.storageGetEvictedRaw();\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Extends the current collection with the passed in array of key-value pairs.\n   *\n   * @param keyValuePairs - The key-value pairs to extend the collection with.\n   * @param options - Options for storing the data.\n   */\n  extend(\n    keyValuePairs: [string, DataType][],\n    options?: GetOptions<DataType>\n  ): void {\n    for (const [key, value] of keyValuePairs) {\n      this.set(key, value, options);\n    }\n  }\n\n  /**\n   * Serialize the collection.\n   *\n   * @param options - Options for storing the data.\n   */\n  serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array {\n    return serializeValueWithOptions(this, options);\n  }\n\n  /**\n   * Converts the deserialized data from storage to a JavaScript instance of the collection.\n   *\n   * @param data - The deserialized data to create an instance from.\n   */\n  static reconstruct<DataType>(data: LookupMap<unknown>): LookupMap<DataType> {\n    return new LookupMap(data.keyPrefix);\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/lookup-set.ts",
    "content": "import * as near from \"../api\";\nimport { GetOptions } from \"../types/collections\";\nimport { serializeValueWithOptions } from \"../utils\";\n\n/**\n * A lookup set collection that stores entries in NEAR storage.\n */\nexport class LookupSet<DataType> {\n  /**\n   * @param keyPrefix - The byte prefix to use when storing elements inside this collection.\n   */\n  constructor(readonly keyPrefix: string) {}\n\n  /**\n   * Checks whether the collection contains the value.\n   *\n   * @param key - The value for which to check the presence.\n   * @param options - Options for storing data.\n   */\n  contains(\n    key: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): boolean {\n    const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n    return near.storageHasKey(storageKey);\n  }\n\n  /**\n   * Returns true if the element was present in the set.\n   *\n   * @param key - The entry to remove.\n   * @param options - Options for storing data.\n   */\n  remove(\n    key: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): boolean {\n    const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n    return near.storageRemove(storageKey);\n  }\n\n  /**\n   * If the set did not have this value present, `true` is returned.\n   * If the set did have this value present, `false` is returned.\n   *\n   * @param key - The value to store in the collection.\n   * @param options - Options for storing the data.\n   */\n  set(\n    key: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): boolean {\n    const storageKey = this.keyPrefix + serializeValueWithOptions(key, options);\n    return !near.storageWrite(storageKey, \"\");\n  }\n\n  /**\n   * Extends the current collection with the passed in array of elements.\n   *\n   * @param keys - The elements to extend the collection with.\n   * @param options - Options for storing the data.\n   */\n  extend(\n    keys: DataType[],\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): void {\n    keys.forEach((key) => this.set(key, options));\n  }\n\n  /**\n   * Serialize the collection.\n   *\n   * @param options - Options for storing the data.\n   */\n  serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array {\n    return serializeValueWithOptions(this, options);\n  }\n\n  /**\n   * Converts the deserialized data from storage to a JavaScript instance of the collection.\n   *\n   * @param data - The deserialized data to create an instance from.\n   */\n  static reconstruct<DataType>(data: LookupSet<unknown>): LookupSet<DataType> {\n    return new LookupSet(data.keyPrefix);\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/subtype.ts",
    "content": "import { GetOptions } from \"../types/collections\";\n\nexport abstract class SubType<DataType> {\n  /* eslint-disable @typescript-eslint/no-explicit-any */\n  /* eslint-disable @typescript-eslint/no-empty-function */\n  subtype(): any {}\n\n  set_reconstructor(\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): Omit<GetOptions<DataType>, \"serializer\"> {\n    if (options == undefined) {\n      options = {};\n    }\n    const subtype = this.subtype();\n    if (options.reconstructor == undefined && subtype != undefined) {\n      if (\n        // eslint-disable-next-line no-prototype-builtins\n        subtype.hasOwnProperty(\"class\") &&\n        typeof subtype.class.reconstruct === \"function\"\n      ) {\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        options.reconstructor = subtype.class.reconstruct;\n      } else if (typeof subtype.reconstruct === \"function\") {\n        options.reconstructor = subtype.reconstruct;\n      }\n    }\n    return options;\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/unordered-map.ts",
    "content": "import {\n  assert,\n  ERR_INCONSISTENT_STATE,\n  getValueWithOptions,\n  Mutable,\n  serializeValueWithOptions,\n  encode,\n  decode,\n} from \"../utils\";\nimport { Vector, VectorIterator } from \"./vector\";\nimport { LookupMap } from \"./lookup-map\";\nimport { GetOptions } from \"../types/collections\";\nimport { SubType } from \"./subtype\";\n\ntype ValueAndIndex = [value: string, index: number];\n\n/**\n * An unordered map that stores data in NEAR storage.\n */\nexport class UnorderedMap<DataType> extends SubType<DataType> {\n  readonly _keys: Vector<string>;\n  readonly values: LookupMap<ValueAndIndex>;\n\n  /**\n   * @param prefix - The byte prefix to use when storing elements inside this collection.\n   */\n  constructor(readonly prefix: string) {\n    super();\n    this._keys = new Vector<string>(`${prefix}u`); // intentional different prefix with old UnorderedMap\n    this.values = new LookupMap<ValueAndIndex>(`${prefix}m`);\n  }\n\n  /**\n   * The number of elements stored in the collection.\n   */\n  get length() {\n    return this._keys.length;\n  }\n\n  /**\n   * Checks whether the collection is empty.\n   */\n  isEmpty(): boolean {\n    return this._keys.isEmpty();\n  }\n\n  /**\n   * Get the data stored at the provided key.\n   *\n   * @param key - The key at which to look for the data.\n   * @param options - Options for retrieving the data.\n   */\n  get(\n    key: string,\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): DataType | null {\n    const valueAndIndex = this.values.get(key);\n\n    if (valueAndIndex === null) {\n      return options?.defaultValue ?? null;\n    }\n    options = this.set_reconstructor(options);\n\n    const [value] = valueAndIndex;\n\n    return getValueWithOptions(this.subtype(), encode(value), options);\n  }\n\n  /**\n   * Store a new value at the provided key.\n   *\n   * @param key - The key at which to store in the collection.\n   * @param value - The value to store in the collection.\n   * @param options - Options for retrieving and storing the data.\n   */\n  set(\n    key: string,\n    value: DataType,\n    options?: GetOptions<DataType>\n  ): DataType | null {\n    const valueAndIndex = this.values.get(key);\n    const serialized = serializeValueWithOptions(value, options);\n\n    if (valueAndIndex === null) {\n      const newElementIndex = this.length;\n\n      this._keys.push(key);\n      this.values.set(key, [decode(serialized), newElementIndex]);\n\n      return null;\n    }\n\n    const [oldValue, oldIndex] = valueAndIndex;\n    this.values.set(key, [decode(serialized), oldIndex]);\n\n    return getValueWithOptions(this.subtype(), encode(oldValue), options);\n  }\n\n  /**\n   * Removes and retrieves the element with the provided key.\n   *\n   * @param key - The key at which to remove data.\n   * @param options - Options for retrieving the data.\n   */\n  remove(\n    key: string,\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): DataType | null {\n    const oldValueAndIndex = this.values.remove(key);\n\n    if (oldValueAndIndex === null) {\n      return options?.defaultValue ?? null;\n    }\n\n    const [value, index] = oldValueAndIndex;\n\n    assert(this._keys.swapRemove(index) !== null, ERR_INCONSISTENT_STATE);\n\n    // the last key is swapped to key[index], the corresponding [value, index] need update\n    if (!this._keys.isEmpty() && index !== this._keys.length) {\n      // if there is still elements and it was not the last element\n      const swappedKey = this._keys.get(index);\n      const swappedValueAndIndex = this.values.get(swappedKey);\n\n      assert(swappedValueAndIndex !== null, ERR_INCONSISTENT_STATE);\n\n      this.values.set(swappedKey, [swappedValueAndIndex[0], index]);\n    }\n\n    return getValueWithOptions(this.subtype(), encode(value), options);\n  }\n\n  /**\n   * Remove all of the elements stored within the collection.\n   */\n  clear(): void {\n    for (const key of this._keys) {\n      // Set instead of remove to avoid loading the value from storage.\n      this.values.set(key, null);\n    }\n\n    this._keys.clear();\n  }\n\n  [Symbol.iterator](): UnorderedMapIterator<DataType> {\n    return new UnorderedMapIterator<DataType>(this);\n  }\n\n  /**\n   * Create a iterator on top of the default collection iterator using custom options.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  private createIteratorWithOptions(options?: GetOptions<DataType>): {\n    [Symbol.iterator](): UnorderedMapIterator<DataType>;\n  } {\n    return {\n      [Symbol.iterator]: () => new UnorderedMapIterator(this, options),\n    };\n  }\n\n  /**\n   * Return a JavaScript array of the data stored within the collection.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  toArray(options?: GetOptions<DataType>): [string, DataType][] {\n    const array = [];\n\n    const iterator = options ? this.createIteratorWithOptions(options) : this;\n\n    for (const value of iterator) {\n      array.push(value);\n    }\n\n    return array;\n  }\n\n  /**\n   * Extends the current collection with the passed in array of key-value pairs.\n   *\n   * @param keyValuePairs - The key-value pairs to extend the collection with.\n   */\n  extend(keyValuePairs: [string, DataType][]) {\n    for (const [key, value] of keyValuePairs) {\n      this.set(key, value);\n    }\n  }\n\n  /**\n   * Serialize the collection.\n   *\n   * @param options - Options for storing the data.\n   */\n  serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array {\n    return serializeValueWithOptions(this, options);\n  }\n\n  /**\n   * Converts the deserialized data from storage to a JavaScript instance of the collection.\n   *\n   * @param data - The deserialized data to create an instance from.\n   */\n  static reconstruct<DataType>(\n    data: UnorderedMap<DataType>\n  ): UnorderedMap<DataType> {\n    // removing readonly modifier\n    type MutableUnorderedMap = Mutable<UnorderedMap<DataType>>;\n    const map = new UnorderedMap(data.prefix) as MutableUnorderedMap;\n\n    // reconstruct keys Vector\n    map._keys = new Vector(`${data.prefix}u`);\n    map._keys.length = data._keys.length;\n    // reconstruct values LookupMap\n    map.values = new LookupMap(`${data.prefix}m`);\n\n    return map as UnorderedMap<DataType>;\n  }\n\n  keys({ start, limit }): string[] {\n    const ret = [];\n    if (start === undefined) {\n      start = 0;\n    }\n    if (limit == undefined) {\n      limit = this.length - start;\n    }\n    for (let i = start; i < start + limit; i++) {\n      ret.push(this._keys.get(i));\n    }\n    return ret;\n  }\n}\n\n/**\n * An iterator for the UnorderedMap collection.\n */\nclass UnorderedMapIterator<DataType> {\n  private keys: VectorIterator<string>;\n  private map: LookupMap<ValueAndIndex>;\n\n  /**\n   * @param unorderedMap - The unordered map collection to create an iterator for.\n   * @param options - Options for retrieving and storing data.\n   */\n  constructor(\n    unorderedMap: UnorderedMap<DataType>,\n    private options?: GetOptions<DataType>\n  ) {\n    this.keys = new VectorIterator(unorderedMap._keys);\n    this.map = unorderedMap.values;\n    this.subtype = unorderedMap.subtype;\n  }\n\n  /* eslint-disable @typescript-eslint/no-explicit-any */\n  /* eslint-disable @typescript-eslint/no-empty-function */\n  subtype(): any {}\n\n  next(): { value: [string | null, DataType | null]; done: boolean } {\n    const key = this.keys.next();\n\n    if (key.done) {\n      return { value: [key.value, null], done: key.done };\n    }\n\n    const valueAndIndex = this.map.get(key.value);\n\n    assert(valueAndIndex !== null, ERR_INCONSISTENT_STATE);\n\n    return {\n      done: key.done,\n      value: [\n        key.value,\n        getValueWithOptions(\n          this.subtype(),\n          encode(valueAndIndex[0]),\n          this.options\n        ),\n      ],\n    };\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/unordered-set.ts",
    "content": "import * as near from \"../api\";\nimport {\n  assert,\n  serializeValueWithOptions,\n  ERR_INCONSISTENT_STATE,\n  encode,\n} from \"../utils\";\nimport { Vector, VectorIterator } from \"./vector\";\nimport { Mutable } from \"../utils\";\nimport { GetOptions } from \"../types/collections\";\n\nfunction serializeIndex(index: number) {\n  const data = new Uint32Array([index]);\n  const array = new Uint8Array(data.buffer);\n\n  return array;\n}\n\nfunction deserializeIndex(rawIndex: Uint8Array): number {\n  const [data] = new Uint32Array(rawIndex.buffer);\n\n  return data;\n}\n\n/**\n * An unordered set that stores data in NEAR storage.\n */\nexport class UnorderedSet<DataType> {\n  readonly elementIndexPrefix: string;\n  readonly _elements: Vector<DataType>;\n\n  /**\n   * @param prefix - The byte prefix to use when storing elements inside this collection.\n   */\n  constructor(readonly prefix: string) {\n    this.elementIndexPrefix = `${prefix}i`;\n    this._elements = new Vector(`${prefix}e`);\n  }\n\n  /**\n   * The number of elements stored in the collection.\n   */\n  get length(): number {\n    return this._elements.length;\n  }\n\n  /**\n   * Checks whether the collection is empty.\n   */\n  isEmpty(): boolean {\n    return this._elements.isEmpty();\n  }\n\n  /**\n   * Checks whether the collection contains the value.\n   *\n   * @param element - The value for which to check the presence.\n   * @param options - Options for storing data.\n   */\n  contains(\n    element: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): boolean {\n    const indexLookup =\n      this.elementIndexPrefix + serializeValueWithOptions(element, options);\n    return near.storageHasKey(indexLookup);\n  }\n\n  /**\n   * If the set did not have this value present, `true` is returned.\n   * If the set did have this value present, `false` is returned.\n   *\n   * @param element - The value to store in the collection.\n   * @param options - Options for storing the data.\n   */\n  set(\n    element: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): boolean {\n    const indexLookup =\n      this.elementIndexPrefix + serializeValueWithOptions(element, options);\n\n    if (near.storageRead(indexLookup)) {\n      return false;\n    }\n\n    const nextIndex = this.length;\n    const nextIndexRaw = serializeIndex(nextIndex);\n    near.storageWriteRaw(encode(indexLookup), nextIndexRaw);\n    this._elements.push(element, options);\n\n    return true;\n  }\n\n  /**\n   * Returns true if the element was present in the set.\n   *\n   * @param element - The entry to remove.\n   * @param options - Options for retrieving and storing data.\n   */\n  remove(element: DataType, options?: GetOptions<DataType>): boolean {\n    const indexLookup =\n      this.elementIndexPrefix + serializeValueWithOptions(element, options);\n    const indexRaw = near.storageReadRaw(encode(indexLookup));\n\n    if (!indexRaw) {\n      return false;\n    }\n\n    // If there is only one element then swap remove simply removes it without\n    // swapping with the last element.\n    if (this.length === 1) {\n      near.storageRemove(indexLookup);\n\n      const index = deserializeIndex(indexRaw);\n      this._elements.swapRemove(index);\n\n      return true;\n    }\n\n    // If there is more than one element then swap remove swaps it with the last\n    // element.\n    const lastElement = this._elements.get(this.length - 1, options);\n\n    assert(!!lastElement, ERR_INCONSISTENT_STATE);\n\n    near.storageRemove(indexLookup);\n\n    // If the removed element was the last element from keys, then we don't need to\n    // reinsert the lookup back.\n    if (lastElement !== element) {\n      const lastLookupElement =\n        this.elementIndexPrefix +\n        serializeValueWithOptions(lastElement, options);\n      near.storageWriteRaw(encode(lastLookupElement), indexRaw);\n    }\n\n    const index = deserializeIndex(indexRaw);\n    this._elements.swapRemove(index);\n\n    return true;\n  }\n\n  /**\n   * Remove all of the elements stored within the collection.\n   */\n  clear(options?: Pick<GetOptions<DataType>, \"serializer\">): void {\n    for (const element of this._elements) {\n      const indexLookup =\n        this.elementIndexPrefix + serializeValueWithOptions(element, options);\n      near.storageRemove(indexLookup);\n    }\n\n    this._elements.clear();\n  }\n\n  [Symbol.iterator](): VectorIterator<DataType> {\n    return this._elements[Symbol.iterator]();\n  }\n\n  /**\n   * Create a iterator on top of the default collection iterator using custom options.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  private createIteratorWithOptions(options?: GetOptions<DataType>): {\n    [Symbol.iterator](): VectorIterator<DataType>;\n  } {\n    return {\n      [Symbol.iterator]: () => new VectorIterator(this._elements, options),\n    };\n  }\n\n  /**\n   * Return a JavaScript array of the data stored within the collection.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  toArray(options?: GetOptions<DataType>): DataType[] {\n    const array = [];\n\n    const iterator = options ? this.createIteratorWithOptions(options) : this;\n\n    for (const value of iterator) {\n      array.push(value);\n    }\n\n    return array;\n  }\n\n  /**\n   * Extends the current collection with the passed in array of elements.\n   *\n   * @param elements - The elements to extend the collection with.\n   */\n  extend(elements: DataType[]): void {\n    for (const element of elements) {\n      this.set(element);\n    }\n  }\n\n  /**\n   * Serialize the collection.\n   *\n   * @param options - Options for storing the data.\n   */\n  serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array {\n    return serializeValueWithOptions(this, options);\n  }\n\n  /**\n   * Converts the deserialized data from storage to a JavaScript instance of the collection.\n   *\n   * @param data - The deserialized data to create an instance from.\n   */\n  static reconstruct<DataType>(\n    data: UnorderedSet<DataType>\n  ): UnorderedSet<DataType> {\n    // removing readonly modifier\n    type MutableUnorderedSet = Mutable<UnorderedSet<DataType>>;\n    const set = new UnorderedSet(data.prefix) as MutableUnorderedSet;\n    // reconstruct Vector\n    const elementsPrefix = data.prefix + \"e\";\n    set._elements = new Vector(elementsPrefix);\n    set._elements.length = data._elements.length;\n\n    return set as UnorderedSet<DataType>;\n  }\n\n  elements({\n    options,\n    start,\n    limit,\n  }: {\n    options?: GetOptions<DataType>;\n    start?: number;\n    limit?: number;\n  }): DataType[] {\n    const ret = [];\n    if (start === undefined) {\n      start = 0;\n    }\n    if (limit == undefined) {\n      limit = this.length - start;\n    }\n    for (let i = start; i < start + limit; i++) {\n      ret.push(this._elements.get(i, options));\n    }\n    return ret;\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/collections/vector.ts",
    "content": "import * as near from \"../api\";\nimport {\n  assert,\n  getValueWithOptions,\n  serializeValueWithOptions,\n  ERR_INCONSISTENT_STATE,\n  ERR_INDEX_OUT_OF_BOUNDS,\n  str,\n  bytes,\n} from \"../utils\";\nimport { GetOptions } from \"../types/collections\";\nimport { SubType } from \"./subtype\";\n\nfunction indexToKey(prefix: string, index: number): string {\n  const data = new Uint32Array([index]);\n  const array = new Uint8Array(data.buffer);\n  const key = str(array);\n\n  return prefix + key;\n}\n\n/**\n * An iterable implementation of vector that stores its content on the trie.\n * Uses the following map: index -> element\n */\nexport class Vector<DataType> extends SubType<DataType> {\n  /**\n   * @param prefix - The byte prefix to use when storing elements inside this collection.\n   * @param length - The initial length of the collection. By default 0.\n   */\n  constructor(readonly prefix: string, public length = 0) {\n    super();\n  }\n\n  /**\n   * Checks whether the collection is empty.\n   */\n  isEmpty(): boolean {\n    return this.length === 0;\n  }\n\n  /**\n   * Get the data stored at the provided index.\n   *\n   * @param index - The index at which to look for the data.\n   * @param options - Options for retrieving the data.\n   */\n  get(\n    index: number,\n    options?: Omit<GetOptions<DataType>, \"serializer\">\n  ): DataType | null {\n    if (index >= this.length) {\n      return options?.defaultValue ?? null;\n    }\n\n    const storageKey = indexToKey(this.prefix, index);\n    const value = near.storageReadRaw(bytes(storageKey));\n    options = this.set_reconstructor(options);\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Removes an element from the vector and returns it in serialized form.\n   * The removed element is replaced by the last element of the vector.\n   * Does not preserve ordering, but is `O(1)`.\n   *\n   * @param index - The index at which to remove the element.\n   * @param options - Options for retrieving and storing the data.\n   */\n  swapRemove(index: number, options?: GetOptions<DataType>): DataType | null {\n    assert(index < this.length, ERR_INDEX_OUT_OF_BOUNDS);\n\n    if (index + 1 === this.length) {\n      return this.pop(options);\n    }\n\n    const key = indexToKey(this.prefix, index);\n    const last = this.pop(options);\n\n    assert(\n      near.storageWriteRaw(\n        bytes(key),\n        serializeValueWithOptions(last, options)\n      ),\n      ERR_INCONSISTENT_STATE\n    );\n\n    const value = near.storageGetEvictedRaw();\n    options = this.set_reconstructor(options);\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Adds data to the collection.\n   *\n   * @param element - The data to store.\n   * @param options - Options for storing the data.\n   */\n  push(\n    element: DataType,\n    options?: Pick<GetOptions<DataType>, \"serializer\">\n  ): void {\n    const key = indexToKey(this.prefix, this.length);\n    this.length += 1;\n\n    near.storageWriteRaw(\n      bytes(key),\n      serializeValueWithOptions(element, options)\n    );\n  }\n\n  /**\n   * Removes and retrieves the element with the highest index.\n   *\n   * @param options - Options for retrieving the data.\n   */\n  pop(options?: Omit<GetOptions<DataType>, \"serializer\">): DataType | null {\n    if (this.isEmpty()) {\n      return options?.defaultValue ?? null;\n    }\n\n    const lastIndex = this.length - 1;\n    const lastKey = indexToKey(this.prefix, lastIndex);\n    this.length -= 1;\n\n    assert(near.storageRemoveRaw(bytes(lastKey)), ERR_INCONSISTENT_STATE);\n\n    const value = near.storageGetEvictedRaw();\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Replaces the data stored at the provided index with the provided data and returns the previously stored data.\n   *\n   * @param index - The index at which to replace the data.\n   * @param element - The data to replace with.\n   * @param options - Options for retrieving and storing the data.\n   */\n  replace(\n    index: number,\n    element: DataType,\n    options?: GetOptions<DataType>\n  ): DataType {\n    assert(index < this.length, ERR_INDEX_OUT_OF_BOUNDS);\n    const key = indexToKey(this.prefix, index);\n\n    assert(\n      near.storageWriteRaw(\n        bytes(key),\n        serializeValueWithOptions(element, options)\n      ),\n      ERR_INCONSISTENT_STATE\n    );\n\n    const value = near.storageGetEvictedRaw();\n    options = this.set_reconstructor(options);\n\n    return getValueWithOptions(this.subtype(), value, options);\n  }\n\n  /**\n   * Extends the current collection with the passed in array of elements.\n   *\n   * @param elements - The elements to extend the collection with.\n   */\n  extend(elements: DataType[]): void {\n    for (const element of elements) {\n      this.push(element);\n    }\n  }\n\n  [Symbol.iterator](): VectorIterator<DataType> {\n    return new VectorIterator(this);\n  }\n\n  /**\n   * Create a iterator on top of the default collection iterator using custom options.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  private createIteratorWithOptions(options?: GetOptions<DataType>): {\n    [Symbol.iterator](): VectorIterator<DataType>;\n  } {\n    return {\n      [Symbol.iterator]: () => new VectorIterator(this, options),\n    };\n  }\n\n  /**\n   * Return a JavaScript array of the data stored within the collection.\n   *\n   * @param options - Options for retrieving and storing the data.\n   */\n  toArray(options?: GetOptions<DataType>): DataType[] {\n    const array = [];\n\n    const iterator = options ? this.createIteratorWithOptions(options) : this;\n\n    for (const value of iterator) {\n      array.push(value);\n    }\n\n    return array;\n  }\n\n  /**\n   * Remove all of the elements stored within the collection.\n   */\n  clear(): void {\n    for (let index = 0; index < this.length; index++) {\n      const key = indexToKey(this.prefix, index);\n      near.storageRemoveRaw(bytes(key));\n    }\n\n    this.length = 0;\n  }\n\n  /**\n   * Serialize the collection.\n   *\n   * @param options - Options for storing the data.\n   */\n  serialize(options?: Pick<GetOptions<DataType>, \"serializer\">): Uint8Array {\n    return serializeValueWithOptions(this, options);\n  }\n\n  /**\n   * Converts the deserialized data from storage to a JavaScript instance of the collection.\n   *\n   * @param data - The deserialized data to create an instance from.\n   */\n  static reconstruct<DataType>(data: Vector<DataType>): Vector<DataType> {\n    const vector = new Vector<DataType>(data.prefix, data.length);\n\n    return vector;\n  }\n}\n\n/**\n * An iterator for the Vector collection.\n */\nexport class VectorIterator<DataType> {\n  private current = 0;\n\n  /**\n   * @param vector - The vector collection to create an iterator for.\n   * @param options - Options for retrieving and storing data.\n   */\n  constructor(\n    private vector: Vector<DataType>,\n    private readonly options?: GetOptions<DataType>\n  ) {}\n\n  next(): {\n    value: DataType | null;\n    done: boolean;\n  } {\n    if (this.current >= this.vector.length) {\n      return { value: null, done: true };\n    }\n\n    const value = this.vector.get(this.current, this.options);\n    this.current += 1;\n\n    return { value, done: false };\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/index.ts",
    "content": "export * from \"./collections\";\nexport * from \"./types\";\nexport * as near from \"./api\";\nexport * from \"./near-bindgen\";\nexport * from \"./promise\";\nexport * from \"./utils\";\n"
  },
  {
    "path": "packages/near-sdk-js/src/near-bindgen.ts",
    "content": "import * as near from \"./api\";\nimport {\n  deserialize,\n  serialize,\n  bytes,\n  encode,\n  decodeObj2class,\n} from \"./utils\";\n\ntype EmptyParameterObject = Record<never, never>;\ntype AnyObject = Record<string, unknown>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype DecoratorFunction = <AnyFunction extends (...args: any) => any>(\n  target: object,\n  key: string | symbol,\n  descriptor: TypedPropertyDescriptor<AnyFunction>\n) => void;\n\n/**\n * Tells the SDK to use this function as the migration function of the contract.\n * The migration function will ignore te existing state.\n * @param _empty - An empty object.\n */\nexport function migrate(_empty: EmptyParameterObject): DecoratorFunction {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return function <AnyFunction extends (...args: any) => any>(\n    _target: object,\n    _key: string | symbol,\n    _descriptor: TypedPropertyDescriptor<AnyFunction>\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n  ): void {};\n}\n\n/**\n * Tells the SDK to use this function as the initialization function of the contract.\n *\n * @param _empty - An empty object.\n */\nexport function initialize(_empty: EmptyParameterObject): DecoratorFunction {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return function <AnyFunction extends (...args: any) => any>(\n    _target: object,\n    _key: string | symbol,\n    _descriptor: TypedPropertyDescriptor<AnyFunction>\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n  ): void {};\n}\n\n/**\n * Tells the SDK to expose this function as a view function.\n *\n * @param _empty - An empty object.\n */\nexport function view(_empty: EmptyParameterObject): DecoratorFunction {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return function <AnyFunction extends (...args: any) => any>(\n    _target: object,\n    _key: string | symbol,\n    _descriptor: TypedPropertyDescriptor<AnyFunction>\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n  ): void {};\n}\n\n/**\n * Tells the SDK to expose this function as a call function.\n * Adds the necessary checks if the function is private or payable.\n *\n * @param options - Options to configure the function behaviour.\n * @param options.privateFunction - Whether the function can be called by other contracts.\n * @param options.payableFunction - Whether the function can accept an attached deposit.\n * @returns\n */\nexport function call(options: {\n  privateFunction?: boolean;\n  payableFunction?: boolean;\n}): DecoratorFunction;\nexport function call({\n  privateFunction = false,\n  payableFunction = false,\n}: {\n  privateFunction?: boolean;\n  payableFunction?: boolean;\n}): DecoratorFunction {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return function <AnyFunction extends (...args: any) => any>(\n    _target: object,\n    _key: string | symbol,\n    descriptor: TypedPropertyDescriptor<AnyFunction>\n  ): void {\n    const originalMethod = descriptor.value;\n\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    descriptor.value = function (\n      ...args: Parameters<AnyFunction>\n    ): ReturnType<AnyFunction> {\n      if (\n        privateFunction &&\n        near.predecessorAccountId() !== near.currentAccountId()\n      ) {\n        throw new Error(\"Function is private\");\n      }\n\n      if (!payableFunction && near.attachedDeposit() > 0n) {\n        throw new Error(\"Function is not payable\");\n      }\n\n      return originalMethod.apply(this, args);\n    };\n  };\n}\n\n/**\n * The interface that a middleware has to implement in order to be used as a middleware function/class.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface Middleware<Arguments extends Array<any>> {\n  /**\n   * The method that gets called with the same arguments that are passed to the function it is wrapping.\n   *\n   * @param args - Arguments that will be passed to the function - immutable.\n   */\n  (...args: Arguments): void;\n}\n\n/**\n * Tells the SDK to apply an array of passed in middleware to the function execution.\n *\n * @param middlewares - The middlewares to be executed.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function middleware<Arguments extends Array<any>>(\n  ...middlewares: Middleware<Arguments>[]\n): DecoratorFunction {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return function <AnyFunction extends (...args: Arguments) => any>(\n    _target: object,\n    _key: string | symbol,\n    descriptor: TypedPropertyDescriptor<AnyFunction>\n  ): void {\n    const originalMethod = descriptor.value;\n\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    descriptor.value = function (...args: Arguments): ReturnType<AnyFunction> {\n      try {\n        middlewares.forEach((middleware) => middleware(...args));\n      } catch (error) {\n        throw new Error(error);\n      }\n\n      return originalMethod.apply(this, args);\n    };\n  };\n}\n\n/**\n * Extends this class with the methods needed to make the contract storable/serializable and readable/deserializable to and from the blockchain.\n * Also tells the SDK to capture and expose all view, call and initialize functions.\n * Tells the SDK whether the contract requires initialization and whether to use a custom serialization/deserialization function when storing/reading the state.\n *\n * @param options - Options to configure the contract behaviour.\n * @param options.requireInit - Whether the contract requires initialization.\n * @param options.serializer - Custom serializer function to use for storing the contract state.\n * @param options.deserializer - Custom deserializer function to use for reading the contract state.\n */\nexport function NearBindgen(options: {\n  requireInit?: boolean;\n  serializer?(value: unknown): Uint8Array;\n  deserializer?(value: Uint8Array): unknown;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n}): any;\nexport function NearBindgen({\n  requireInit = false,\n  serializer = serialize,\n  deserializer = deserialize,\n}: {\n  requireInit?: boolean;\n  serializer?(value: unknown): Uint8Array;\n  deserializer?(value: Uint8Array): unknown;\n}) {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return <T extends { new (...args: any[]): any }>(target: T) => {\n    return class extends target {\n      static _create() {\n        return new target();\n      }\n\n      static _getState(): unknown | null {\n        const rawState = near.storageReadRaw(bytes(\"STATE\"));\n        return rawState ? this._deserialize(rawState) : null;\n      }\n\n      static _saveToStorage(objectToSave: unknown): void {\n        near.storageWriteRaw(bytes(\"STATE\"), this._serialize(objectToSave));\n      }\n\n      static _getArgs(): unknown {\n        return JSON.parse(near.input() || \"{}\");\n      }\n\n      static _serialize(value: unknown, forReturn = false): Uint8Array {\n        if (forReturn) {\n          return encode(\n            JSON.stringify(value, (_, value) =>\n              typeof value === \"bigint\" ? `${value}` : value\n            )\n          );\n        }\n\n        return serializer(value);\n      }\n\n      static _deserialize(value: Uint8Array): unknown {\n        return deserializer(value);\n      }\n\n      static _reconstruct(classObject: object, plainObject: AnyObject): object {\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        if (classObject.constructor.schema === undefined) {\n          for (const item in classObject) {\n            const reconstructor = classObject[item].constructor?.reconstruct;\n\n            classObject[item] = reconstructor\n              ? reconstructor(plainObject[item])\n              : plainObject[item];\n          }\n\n          return classObject;\n        }\n\n        return decodeObj2class(classObject, plainObject);\n      }\n\n      static _requireInit(): boolean {\n        return requireInit;\n      }\n    };\n  };\n}\n\ndeclare module \"./\" {\n  /**\n   * A macro that reads the WASM code from the specified path at compile time.\n   *\n   * @param pathToWasm - The path to the WASM file to read code from.\n   */\n  export function includeBytes(pathToWasm: string): Uint8Array;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/promise.ts",
    "content": "import { assert, PromiseIndex } from \"./utils\";\nimport * as near from \"./api\";\nimport { Balance, PublicKey, AccountId, Gas, GasWeight } from \"./types\";\nimport { Nonce } from \"./types/primitives\";\n\n/**\n * A promise action which can be executed on the NEAR blockchain.\n */\nexport abstract class PromiseAction {\n  /**\n   * The method that describes how a promise action adds it's _action_ to the promise batch with the provided index.\n   *\n   * @param promiseIndex - The index of the promise batch to attach the action to.\n   */\n  abstract add(promiseIndex: PromiseIndex): void;\n}\n\n/**\n * A create account promise action.\n *\n * @extends {PromiseAction}\n */\nexport class CreateAccount extends PromiseAction {\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionCreateAccount(promiseIndex);\n  }\n}\n\n/**\n * A deploy contract promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeployContract extends PromiseAction {\n  /**\n   * @param code - The code of the contract to be deployed.\n   */\n  constructor(public code: Uint8Array) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionDeployContract(promiseIndex, this.code);\n  }\n}\n\n/**\n * A function call promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCall extends PromiseAction {\n  /**\n   * @param functionName - The name of the function to be called.\n   * @param args - The utf-8 string arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   */\n  constructor(\n    public functionName: string,\n    public args: string,\n    public amount: Balance,\n    public gas: Gas\n  ) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionFunctionCall(\n      promiseIndex,\n      this.functionName,\n      this.args,\n      this.amount,\n      this.gas\n    );\n  }\n}\n\n/**\n * A function call raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallRaw extends PromiseAction {\n  /**\n   * @param functionName - The name of the function to be called.\n   * @param args - The arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   */\n  constructor(\n    public functionName: string,\n    public args: Uint8Array,\n    public amount: Balance,\n    public gas: Gas\n  ) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionFunctionCallRaw(\n      promiseIndex,\n      this.functionName,\n      this.args,\n      this.amount,\n      this.gas\n    );\n  }\n}\n\n/**\n * A function call weight promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallWeight extends PromiseAction {\n  /**\n   * @param functionName - The name of the function to be called.\n   * @param args - The utf-8 string arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   * @param weight - The weight of unused Gas to use.\n   */\n  constructor(\n    public functionName: string,\n    public args: string,\n    public amount: Balance,\n    public gas: Gas,\n    public weight: GasWeight\n  ) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionFunctionCallWeight(\n      promiseIndex,\n      this.functionName,\n      this.args,\n      this.amount,\n      this.gas,\n      this.weight\n    );\n  }\n}\n\n/**\n * A function call weight raw promise action.\n *\n * @extends {PromiseAction}\n */\nexport class FunctionCallWeightRaw extends PromiseAction {\n  /**\n   * @param functionName - The name of the function to be called.\n   * @param args - The arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   * @param weight - The weight of unused Gas to use.\n   */\n  constructor(\n    public functionName: string,\n    public args: Uint8Array,\n    public amount: Balance,\n    public gas: Gas,\n    public weight: GasWeight\n  ) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionFunctionCallWeightRaw(\n      promiseIndex,\n      this.functionName,\n      this.args,\n      this.amount,\n      this.gas,\n      this.weight\n    );\n  }\n}\n\n/**\n * A transfer promise action.\n *\n * @extends {PromiseAction}\n */\nexport class Transfer extends PromiseAction {\n  /**\n   * @param amount - The amount of NEAR to transfer.\n   */\n  constructor(public amount: Balance) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionTransfer(promiseIndex, this.amount);\n  }\n}\n\n/**\n * A stake promise action.\n *\n * @extends {PromiseAction}\n */\nexport class Stake extends PromiseAction {\n  /**\n   * @param amount - The amount of NEAR to transfer.\n   * @param publicKey - The public key to use for staking.\n   */\n  constructor(public amount: Balance, public publicKey: PublicKey) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionStake(\n      promiseIndex,\n      this.amount,\n      this.publicKey.data\n    );\n  }\n}\n\n/**\n * A add full access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class AddFullAccessKey extends PromiseAction {\n  /**\n   * @param publicKey - The public key to add as a full access key.\n   * @param nonce - The nonce to use.\n   */\n  constructor(public publicKey: PublicKey, public nonce: Nonce) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionAddKeyWithFullAccess(\n      promiseIndex,\n      this.publicKey.data,\n      this.nonce\n    );\n  }\n}\n\n/**\n * A add access key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class AddAccessKey extends PromiseAction {\n  /**\n   * @param publicKey - The public key to add as a access key.\n   * @param allowance - The allowance for the key in yoctoNEAR.\n   * @param receiverId - The account ID of the receiver.\n   * @param functionNames - The names of functions to authorize.\n   * @param nonce - The nonce to use.\n   */\n  constructor(\n    public publicKey: PublicKey,\n    public allowance: Balance,\n    public receiverId: AccountId,\n    public functionNames: string,\n    public nonce: Nonce\n  ) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionAddKeyWithFunctionCall(\n      promiseIndex,\n      this.publicKey.data,\n      this.nonce,\n      this.allowance,\n      this.receiverId,\n      this.functionNames\n    );\n  }\n}\n\n/**\n * A delete key promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeleteKey extends PromiseAction {\n  /**\n   * @param publicKey - The public key to delete from the account.\n   */\n  constructor(public publicKey: PublicKey) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionDeleteKey(promiseIndex, this.publicKey.data);\n  }\n}\n/**\n * A delete account promise action.\n *\n * @extends {PromiseAction}\n */\nexport class DeleteAccount extends PromiseAction {\n  /**\n   * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n   */\n  constructor(public beneficiaryId: AccountId) {\n    super();\n  }\n\n  add(promiseIndex: PromiseIndex) {\n    near.promiseBatchActionDeleteAccount(promiseIndex, this.beneficiaryId);\n  }\n}\n\nclass PromiseSingle {\n  constructor(\n    public accountId: AccountId,\n    public actions: PromiseAction[],\n    public after: NearPromise | null,\n    public promiseIndex: PromiseIndex | null\n  ) {}\n\n  constructRecursively(): PromiseIndex {\n    if (this.promiseIndex !== null) {\n      return this.promiseIndex;\n    }\n\n    const promiseIndex = this.after\n      ? near.promiseBatchThen(this.after.constructRecursively(), this.accountId)\n      : near.promiseBatchCreate(this.accountId);\n\n    this.actions.forEach((action) => action.add(promiseIndex));\n\n    this.promiseIndex = promiseIndex;\n\n    return promiseIndex;\n  }\n}\n\nexport class PromiseJoint {\n  constructor(\n    public promiseA: NearPromise,\n    public promiseB: NearPromise,\n    public promiseIndex: PromiseIndex | null\n  ) {}\n\n  constructRecursively(): PromiseIndex {\n    if (this.promiseIndex !== null) {\n      return this.promiseIndex;\n    }\n\n    const result = near.promiseAnd(\n      this.promiseA.constructRecursively(),\n      this.promiseB.constructRecursively()\n    );\n    this.promiseIndex = result;\n\n    return result;\n  }\n}\n\ntype PromiseSubtype = PromiseSingle | PromiseJoint;\n\n/**\n * A high level class to construct and work with NEAR promises.\n */\nexport class NearPromise {\n  /**\n   * @param subtype - The subtype of the promise.\n   * @param shouldReturn - Whether the promise should return.\n   */\n  constructor(private subtype: PromiseSubtype, private shouldReturn: boolean) {}\n\n  /**\n   * Creates a new promise to the provided account ID.\n   *\n   * @param accountId - The account ID on which to call the promise.\n   */\n  static new(accountId: AccountId): NearPromise {\n    const subtype = new PromiseSingle(accountId, [], null, null);\n    return new NearPromise(subtype, false);\n  }\n\n  private addAction(action: PromiseAction): NearPromise {\n    if (this.subtype instanceof PromiseJoint) {\n      throw new Error(\"Cannot add action to a joint promise.\");\n    }\n\n    this.subtype.actions.push(action);\n\n    return this;\n  }\n\n  /**\n   * Creates a create account promise action and adds it to the current promise.\n   */\n  createAccount(): NearPromise {\n    return this.addAction(new CreateAccount());\n  }\n\n  /**\n   * Creates a deploy contract promise action and adds it to the current promise.\n   *\n   * @param code - The code of the contract to be deployed.\n   */\n  deployContract(code: Uint8Array): NearPromise {\n    return this.addAction(new DeployContract(code));\n  }\n\n  /**\n   * Creates a function call promise action and adds it to the current promise.\n   *\n   * @param functionName - The name of the function to be called.\n   * @param args - The utf-8 string arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   */\n  functionCall(\n    functionName: string,\n    args: string,\n    amount: Balance,\n    gas: Gas\n  ): NearPromise {\n    return this.addAction(new FunctionCall(functionName, args, amount, gas));\n  }\n\n  /**\n   * Creates a function call raw promise action and adds it to the current promise.\n   *\n   * @param functionName - The name of the function to be called.\n   * @param args - The arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   */\n  functionCallRaw(\n    functionName: string,\n    args: Uint8Array,\n    amount: Balance,\n    gas: Gas\n  ): NearPromise {\n    return this.addAction(new FunctionCallRaw(functionName, args, amount, gas));\n  }\n\n  /**\n   * Creates a function call weight promise action and adds it to the current promise.\n   *\n   * @param functionName - The name of the function to be called.\n   * @param args - The utf-8 string arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   * @param weight - The weight of unused Gas to use.\n   */\n  functionCallWeight(\n    functionName: string,\n    args: string,\n    amount: Balance,\n    gas: Gas,\n    weight: GasWeight\n  ): NearPromise {\n    return this.addAction(\n      new FunctionCallWeight(functionName, args, amount, gas, weight)\n    );\n  }\n\n  /**\n   * Creates a function call weight raw promise action and adds it to the current promise.\n   *\n   * @param functionName - The name of the function to be called.\n   * @param args - The arguments to be passed to the function.\n   * @param amount - The amount of NEAR to attach to the call.\n   * @param gas - The amount of Gas to attach to the call.\n   * @param weight - The weight of unused Gas to use.\n   */\n  functionCallWeightRaw(\n    functionName: string,\n    args: Uint8Array,\n    amount: Balance,\n    gas: Gas,\n    weight: GasWeight\n  ): NearPromise {\n    return this.addAction(\n      new FunctionCallWeightRaw(functionName, args, amount, gas, weight)\n    );\n  }\n\n  /**\n   * Creates a transfer promise action and adds it to the current promise.\n   *\n   * @param amount - The amount of NEAR to transfer.\n   */\n  transfer(amount: Balance): NearPromise {\n    return this.addAction(new Transfer(amount));\n  }\n\n  /**\n   * Creates a stake promise action and adds it to the current promise.\n   *\n   * @param amount - The amount of NEAR to transfer.\n   * @param publicKey - The public key to use for staking.\n   */\n  stake(amount: Balance, publicKey: PublicKey): NearPromise {\n    return this.addAction(new Stake(amount, publicKey));\n  }\n\n  /**\n   * Creates a add full access key promise action and adds it to the current promise.\n   * Uses 0n as the nonce.\n   *\n   * @param publicKey - The public key to add as a full access key.\n   */\n  addFullAccessKey(publicKey: PublicKey): NearPromise {\n    return this.addFullAccessKeyWithNonce(publicKey, 0n);\n  }\n\n  /**\n   * Creates a add full access key promise action and adds it to the current promise.\n   * Allows you to specify the nonce.\n   *\n   * @param publicKey - The public key to add as a full access key.\n   * @param nonce - The nonce to use.\n   */\n  addFullAccessKeyWithNonce(publicKey: PublicKey, nonce: Nonce): NearPromise {\n    return this.addAction(new AddFullAccessKey(publicKey, nonce));\n  }\n\n  /**\n   * Creates a add access key promise action and adds it to the current promise.\n   * Uses 0n as the nonce.\n   *\n   * @param publicKey - The public key to add as a access key.\n   * @param allowance - The allowance for the key in yoctoNEAR.\n   * @param receiverId - The account ID of the receiver.\n   * @param functionNames - The names of functions to authorize.\n   */\n  addAccessKey(\n    publicKey: PublicKey,\n    allowance: Balance,\n    receiverId: AccountId,\n    functionNames: string\n  ): NearPromise {\n    return this.addAccessKeyWithNonce(\n      publicKey,\n      allowance,\n      receiverId,\n      functionNames,\n      0n\n    );\n  }\n\n  /**\n   * Creates a add access key promise action and adds it to the current promise.\n   * Allows you to specify the nonce.\n   *\n   * @param publicKey - The public key to add as a access key.\n   * @param allowance - The allowance for the key in yoctoNEAR.\n   * @param receiverId - The account ID of the receiver.\n   * @param functionNames - The names of functions to authorize.\n   * @param nonce - The nonce to use.\n   */\n  addAccessKeyWithNonce(\n    publicKey: PublicKey,\n    allowance: Balance,\n    receiverId: AccountId,\n    functionNames: string,\n    nonce: Nonce\n  ): NearPromise {\n    return this.addAction(\n      new AddAccessKey(publicKey, allowance, receiverId, functionNames, nonce)\n    );\n  }\n\n  /**\n   * Creates a delete key promise action and adds it to the current promise.\n   *\n   * @param publicKey - The public key to delete from the account.\n   */\n  deleteKey(publicKey: PublicKey): NearPromise {\n    return this.addAction(new DeleteKey(publicKey));\n  }\n\n  /**\n   * Creates a delete account promise action and adds it to the current promise.\n   *\n   * @param beneficiaryId - The beneficiary of the account deletion - the account to receive all of the remaining funds of the deleted account.\n   */\n  deleteAccount(beneficiaryId: AccountId): NearPromise {\n    return this.addAction(new DeleteAccount(beneficiaryId));\n  }\n\n  /**\n   * Joins the provided promise with the current promise, making the current promise a joint promise subtype.\n   *\n   * @param other - The promise to join with the current promise.\n   */\n  and(other: NearPromise): NearPromise {\n    const subtype = new PromiseJoint(this, other, null);\n    return new NearPromise(subtype, false);\n  }\n\n  /**\n   * Adds a callback to the current promise.\n   *\n   * @param other - The promise to be executed as the promise.\n   */\n  then(other: NearPromise): NearPromise {\n    assert(\n      other.subtype instanceof PromiseSingle,\n      \"Cannot callback joint promise.\"\n    );\n\n    assert(\n      other.subtype.after === null,\n      \"Cannot callback promise which is already scheduled after another\"\n    );\n\n    other.subtype.after = this;\n\n    return other;\n  }\n\n  /**\n   * Sets the shouldReturn field to true.\n   */\n  asReturn(): NearPromise {\n    this.shouldReturn = true;\n    return this;\n  }\n\n  /**\n   * Recursively goes through the current promise to get the promise index.\n   */\n  constructRecursively(): PromiseIndex {\n    const result = this.subtype.constructRecursively();\n\n    if (this.shouldReturn) {\n      near.promiseReturn(result);\n    }\n\n    return result;\n  }\n\n  /**\n   * Called by NearBindgen, when return object is a NearPromise instance.\n   */\n  onReturn() {\n    this.asReturn().constructRecursively();\n  }\n\n  /**\n   * Attach the promise to transaction but does not return it. The promise will be executed, but\n   * whether it success or not will not affect the transaction result. If you want the promise fail\n   * also makes the transaction fail, you can simply return the promise from a @call method.\n   */\n  build(): PromiseIndex {\n    return this.constructRecursively();\n  }\n}\n\nexport type PromiseOrValue<T> = NearPromise | T;\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/account_id.ts",
    "content": "/**\n * A string that represents a NEAR account ID.\n */\nexport type AccountId = string;\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/collections.ts",
    "content": "/**\n * Options for retrieving and storing data in the SDK collections.\n */\nexport interface GetOptions<DataType> {\n  /**\n   * A constructor function to call after deserializing a value. Typically this is a constructor of the class you are storing.\n   *\n   * @param value - The value returned from deserialization - either the provided `deserializer` or default deserialization function.\n   */\n  reconstructor?(value: unknown): DataType;\n  /**\n   * A default value to return if the original value is not present or null.\n   */\n  defaultValue?: DataType;\n  /**\n   * A serializer function to customize the serialization of the collection for this call.\n   *\n   * @param valueToSerialize - The value that will be serialized - either the `DataType` or a unknown value.\n   */\n  serializer?(valueToSerialize: unknown): Uint8Array;\n  /**\n   * A deserializer function to customize the deserialization of values after reading from NEAR storage for this call.\n   *\n   * @param valueToDeserialize - The Uint8Array retrieved from NEAR storage to deserialize.\n   */\n  deserializer?(valueToDeserialize: Uint8Array): unknown;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/gas.ts",
    "content": "/**\n * The Gas amount specified in yoctoNEAR.\n */\nexport type Gas = bigint;\n/**\n * One TGas - Tera Gas. 10^12 yoctoNEAR.\n */\nexport const ONE_TERA_GAS: Gas = 1_000_000_000_000n;\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/index.ts",
    "content": "export * from \"./account_id\";\nexport * from \"./gas\";\nexport * from \"./primitives\";\nexport * from \"./public_key\";\nexport * from \"./vm_types\";\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/primitives.ts",
    "content": "/**\n * The amount of storage used in yoctoNEAR.\n */\nexport type StorageUsage = bigint;\n/**\n * A large integer representing the block height.\n */\nexport type BlockHeight = bigint;\n/**\n * A large integer representing the epoch height.\n */\nexport type EpochHeight = bigint;\n/**\n * The amount of tokens in yoctoNEAR.\n */\nexport type Balance = bigint;\n/**\n * A large integer representing the nonce.\n */\nexport type Nonce = bigint;\n/**\n * The amount of Gas Weight in integers - whole numbers.\n */\nexport type GasWeight = bigint;\n/**\n * One yoctoNEAR. 10^-24 NEAR.\n */\nexport const ONE_YOCTO: Balance = 1n;\n/**\n * One NEAR. 1 NEAR = 10^24 yoctoNEAR.\n */\nexport const ONE_NEAR: Balance = 1_000_000_000_000_000_000_000_000n;\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/public_key.ts",
    "content": "import { base58 } from \"@scure/base\";\nimport { concat } from \"../utils\";\n\nexport enum CurveType {\n  ED25519 = 0,\n  SECP256K1 = 1,\n}\n\nenum DataLength {\n  ED25519 = 32,\n  SECP256K1 = 64,\n}\n\nfunction getCurveType(curveType: CurveType | number): CurveType {\n  switch (curveType) {\n    case CurveType.ED25519:\n    case CurveType.SECP256K1:\n      return curveType;\n    default:\n      throw new UnknownCurve();\n  }\n}\n\nfunction dataLength(curveType: CurveType | number): DataLength {\n  switch (curveType) {\n    case CurveType.ED25519:\n    case CurveType.SECP256K1:\n      return {\n        [CurveType.ED25519]: DataLength.ED25519,\n        [CurveType.SECP256K1]: DataLength.SECP256K1,\n      }[curveType];\n    default:\n      throw new UnknownCurve();\n  }\n}\n\nfunction splitKeyTypeData(value: string): [CurveType, string] {\n  const idx = value.indexOf(\":\");\n  if (idx >= 0) {\n    return [\n      curveTypeFromStr(value.substring(0, idx)),\n      value.substring(idx + 1),\n    ];\n  } else {\n    return [CurveType.ED25519, value];\n  }\n}\n\nexport function curveTypeFromStr(value: string): CurveType {\n  switch (value) {\n    case \"ed25519\":\n      return CurveType.ED25519;\n    case \"secp256k1\":\n      return CurveType.SECP256K1;\n    default:\n      throw new UnknownCurve();\n  }\n}\n\nexport class ParsePublicKeyError extends Error {}\n\nexport class InvalidLengthError extends ParsePublicKeyError {\n  constructor(public length: number, public expectedLength: number) {\n    super(`Invalid length: ${length}. Expected: ${expectedLength}`);\n  }\n}\nexport class Base58Error extends ParsePublicKeyError {\n  constructor(public error: string) {\n    super(`Base58 error: ${error}`);\n  }\n}\nexport class UnknownCurve extends ParsePublicKeyError {\n  constructor() {\n    super(\"Unknown curve\");\n  }\n}\n\n/**\n * A abstraction on top of the NEAR public key string.\n * Public key in a binary format with base58 string serialization with human-readable curve.\n * The key types currently supported are `secp256k1` and `ed25519`.\n */\nexport class PublicKey {\n  /**\n   * The actual value of the public key.\n   */\n  public data: Uint8Array;\n  private type: CurveType;\n\n  /**\n   * @param data - The string you want to create a PublicKey from.\n   */\n  constructor(data: Uint8Array) {\n    const curveLenght = dataLength(data[0]);\n\n    if (data.length !== curveLenght + 1) {\n      throw new InvalidLengthError(data.length, curveLenght + 1);\n    }\n\n    this.type = getCurveType(data[0]);\n    this.data = data;\n  }\n\n  /**\n   * The curve type of the public key.\n   */\n  curveType(): CurveType {\n    return this.type;\n  }\n\n  /**\n   * Create a public key from a public key string.\n   *\n   * @param publicKeyString - The public key string you want to create a PublicKey from.\n   */\n  static fromString(publicKeyString: string) {\n    const [curve, keyData] = splitKeyTypeData(publicKeyString);\n    let data: Uint8Array;\n\n    try {\n      data = base58.decode(keyData);\n    } catch (error) {\n      throw new Base58Error(error.message);\n    }\n\n    return new PublicKey(concat(new Uint8Array([curve]), data));\n  }\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/types/vm_types.ts",
    "content": "/**\n * The index for NEAR receipts.\n */\nexport type ReceiptIndex = bigint;\n/**\n * The index for iterators.\n */\nexport type IteratorIndex = bigint;\n\n/**\n * A Promise result in near can be one of:\n * - NotReady = 0 - the promise you are specifying is still not ready, not yet failed nor successful.\n * - Successful = 1 - the promise has been successfully executed and you can retrieve the resulting value.\n * - Failed = 2 - the promise execution has failed.\n */\nexport enum PromiseResult {\n  NotReady = 0,\n  Successful = 1,\n  Failed = 2,\n}\n\n/**\n * A promise error can either be due to the promise failing or not yet being ready.\n */\nexport enum PromiseError {\n  Failed,\n  NotReady,\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/utils.ts",
    "content": "import { GetOptions } from \"./types/collections\";\nimport { cloneDeep } from \"lodash-es\";\n\nexport interface Env {\n  uint8array_to_latin1_string(a: Uint8Array): string;\n  uint8array_to_utf8_string(a: Uint8Array): string;\n  latin1_string_to_uint8array(s: string): Uint8Array;\n  utf8_string_to_uint8array(s: string): Uint8Array;\n}\n\ndeclare const env: Env;\n\n/**\n * A PromiseIndex which represents the ID of a NEAR Promise.\n */\nexport type PromiseIndex = number | bigint;\n/**\n * A number that specifies the amount of NEAR in yoctoNEAR.\n */\nexport type NearAmount = number | bigint;\n/**\n * A number that specifies the ID of a register in the NEAR WASM virtual machine.\n */\nexport type Register = number | bigint;\n\nconst TYPE_KEY = \"typeInfo\";\nenum TypeBrand {\n  BIGINT = \"bigint\",\n  DATE = \"date\",\n}\n\nexport const ERR_INCONSISTENT_STATE =\n  \"The collection is an inconsistent state. Did previous smart contract execution terminate unexpectedly?\";\nexport const ERR_INDEX_OUT_OF_BOUNDS = \"Index out of bounds\";\n\nconst ACCOUNT_ID_REGEX =\n  /^(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\n\n/**\n * Concat two Uint8Array\n * @param array1\n * @param array2\n * @returns the concatenation of two array\n */\nexport function concat(array1: Uint8Array, array2: Uint8Array): Uint8Array {\n  const mergedArray = new Uint8Array(array1.length + array2.length);\n  mergedArray.set(array1);\n  mergedArray.set(array2, array1.length);\n  return mergedArray;\n}\n\n/**\n * Asserts that the expression passed to the function is truthy, otherwise throws a new Error with the provided message.\n *\n * @param expression - The expression to be asserted.\n * @param message - The error message to be printed.\n */\nexport function assert(\n  expression: unknown,\n  message: string\n): asserts expression {\n  if (!expression) {\n    throw new Error(\"assertion failed: \" + message);\n  }\n}\n\nexport type Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nexport function getValueWithOptions<DataType>(\n  subDatatype: unknown,\n  value: Uint8Array | null,\n  options: Omit<GetOptions<DataType>, \"serializer\"> = {}\n): DataType | null {\n  if (value === null) {\n    return options?.defaultValue ?? null;\n  }\n\n  const deserializer = options.deserializer || deserialize;\n\n  // here is an obj\n  let deserialized = deserializer(value);\n\n  if (deserialized === undefined || deserialized === null) {\n    return options?.defaultValue ?? null;\n  }\n\n  if (options?.reconstructor) {\n    // example: // { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n    const collection = options.reconstructor(deserialized);\n    if (\n      subDatatype !== undefined &&\n      // eslint-disable-next-line no-prototype-builtins\n      subDatatype.hasOwnProperty(\"class\") &&\n      // eslint-disable-next-line no-prototype-builtins\n      subDatatype[\"class\"].hasOwnProperty(\"value\")\n    ) {\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      collection.subtype = function () {\n        // example: {class: UnorderedMap, value: UnorderedMap}\n        return subDatatype[\"class\"][\"value\"];\n      };\n    }\n    return collection;\n  }\n\n  // example: { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n  if (subDatatype !== undefined) {\n    // subtype info is a class constructor, Such as Car\n    if (typeof subDatatype === \"function\") {\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      deserialized = decodeObj2class(new subDatatype(), deserialized);\n    } else if (typeof subDatatype === \"object\") {\n      // normal collections of array, map; subtype will be:\n      //  {map: { key: 'string', value: 'string' }} or {array: {value: 'string'}} ..\n      // eslint-disable-next-line no-prototype-builtins\n      if (subDatatype.hasOwnProperty(\"map\")) {\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        for (const mkey in deserialized) {\n          if (subDatatype[\"map\"][\"value\"] !== \"string\") {\n            deserialized[mkey] = decodeObj2class(\n              new subDatatype[\"map\"][\"value\"](),\n              value[mkey]\n            );\n          }\n        }\n        // eslint-disable-next-line no-prototype-builtins\n      } else if (subDatatype.hasOwnProperty(\"array\")) {\n        const new_vec = [];\n        // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n        // @ts-ignore\n        for (const k in deserialized) {\n          if (subDatatype[\"array\"][\"value\"] !== \"string\") {\n            new_vec.push(\n              decodeObj2class(new subDatatype[\"array\"][\"value\"](), value[k])\n            );\n          }\n        }\n        deserialized = new_vec;\n        // eslint-disable-next-line no-prototype-builtins\n      }\n    }\n  }\n\n  return deserialized as DataType;\n}\n\nexport function serializeValueWithOptions<DataType>(\n  value: DataType,\n  { serializer }: Pick<GetOptions<DataType>, \"serializer\"> = {\n    serializer: serialize,\n  }\n): Uint8Array {\n  return serializer(value);\n}\n\nexport function serialize(valueToSerialize: unknown): Uint8Array {\n  return encode(\n    JSON.stringify(valueToSerialize, function (key, value) {\n      if (typeof value === \"bigint\") {\n        return {\n          value: value.toString(),\n          [TYPE_KEY]: TypeBrand.BIGINT,\n        };\n      }\n\n      if (\n        typeof this[key] === \"object\" &&\n        this[key] !== null &&\n        this[key] instanceof Date\n      ) {\n        return {\n          value: this[key].toISOString(),\n          [TYPE_KEY]: TypeBrand.DATE,\n        };\n      }\n\n      return value;\n    })\n  );\n}\n\nexport function deserialize(valueToDeserialize: Uint8Array): unknown {\n  return JSON.parse(decode(valueToDeserialize), (_, value) => {\n    if (\n      value !== null &&\n      typeof value === \"object\" &&\n      Object.keys(value).length === 2 &&\n      Object.keys(value).every((key) => [\"value\", TYPE_KEY].includes(key))\n    ) {\n      switch (value[TYPE_KEY]) {\n        case TypeBrand.BIGINT:\n          return BigInt(value[\"value\"]);\n        case TypeBrand.DATE:\n          return new Date(value[\"value\"]);\n      }\n    }\n\n    return value;\n  });\n}\n\nexport function decodeObj2class(class_instance, obj) {\n  if (\n    typeof obj != \"object\" ||\n    typeof obj === \"bigint\" ||\n    obj instanceof Date ||\n    class_instance.constructor.schema === undefined\n  ) {\n    return obj;\n  }\n  let key;\n  for (key in obj) {\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    const value = obj[key];\n    if (typeof value == \"object\") {\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      const ty = class_instance.constructor.schema[key];\n      // eslint-disable-next-line no-prototype-builtins\n      if (ty !== undefined && ty.hasOwnProperty(\"map\")) {\n        for (const mkey in value) {\n          if (ty[\"map\"][\"value\"] === \"string\") {\n            class_instance[key][mkey] = value[mkey];\n          } else {\n            class_instance[key][mkey] = decodeObj2class(\n              new ty[\"map\"][\"value\"](),\n              value[mkey]\n            );\n          }\n        }\n        // eslint-disable-next-line no-prototype-builtins\n      } else if (ty !== undefined && ty.hasOwnProperty(\"array\")) {\n        for (const k in value) {\n          if (ty[\"array\"][\"value\"] === \"string\") {\n            class_instance[key].push(value[k]);\n          } else {\n            class_instance[key].push(\n              decodeObj2class(new ty[\"array\"][\"value\"](), value[k])\n            );\n          }\n        }\n        // eslint-disable-next-line no-prototype-builtins\n      } else if (ty !== undefined && ty.hasOwnProperty(\"class\")) {\n        // => nested_lookup_recordes:  {class: UnorderedMap, value: {class: LookupMap }},\n        class_instance[key] = ty[\"class\"].reconstruct(obj[key]);\n        // eslint-disable-next-line no-prototype-builtins\n        if (ty.hasOwnProperty(\"value\")) {\n          const subtype_value = ty[\"value\"];\n          class_instance[key].subtype = function () {\n            // example: { collection: {reconstructor: LookupMap.reconstruct, value: 'string'}}\n            // example: UnorderedMap or {class: UnorderedMap, value: 'string'}\n            return subtype_value;\n          };\n        }\n      } else if (ty !== undefined && typeof ty.reconstruct === \"function\") {\n        class_instance[key] = ty.reconstruct(obj[key]);\n      } else {\n        // normal case with nested Class, such as field is truck: Truck,\n        class_instance[key] = decodeObj2class(class_instance[key], obj[key]);\n      }\n    } else {\n      class_instance[key] = obj[key];\n    }\n  }\n  const instance_tmp = cloneDeep(class_instance);\n  for (key in obj) {\n    if (\n      typeof class_instance[key] == \"object\" &&\n      !(class_instance[key] instanceof Date)\n    ) {\n      class_instance[key] = instance_tmp[key];\n    }\n  }\n  return class_instance;\n}\n\n/**\n * Validates the Account ID according to the NEAR protocol\n * [Account ID rules](https://nomicon.io/DataStructures/Account#account-id-rules).\n *\n * @param accountId - The Account ID string you want to validate.\n */\nexport function validateAccountId(accountId: string): boolean {\n  return (\n    accountId.length >= 2 &&\n    accountId.length <= 64 &&\n    ACCOUNT_ID_REGEX.test(accountId)\n  );\n}\n\n/**\n * A subset of NodeJS TextEncoder API\n */\nexport class TextEncoder {\n  encode(s: string): Uint8Array {\n    return env.utf8_string_to_uint8array(s);\n  }\n}\n\n/**\n * A subset of NodeJS TextDecoder API. Only support utf-8 and latin1 encoding.\n */\nexport class TextDecoder {\n  constructor(public encoding: string = \"utf-8\") {}\n\n  decode(a: Uint8Array): string {\n    if (this.encoding == \"utf-8\") {\n      return env.uint8array_to_utf8_string(a);\n    } else if (this.encoding == \"latin1\") {\n      return env.uint8array_to_latin1_string(a);\n    } else {\n      throw new Error(\"unsupported encoding: \" + this.encoding);\n    }\n  }\n}\n\n/**\n * Convert a string to Uint8Array, each character must have a char code between 0-255.\n * @param s - string that with only Latin1 character to convert\n * @returns result Uint8Array\n */\nexport function bytes(s: string): Uint8Array {\n  return env.latin1_string_to_uint8array(s);\n}\n\n/**\n * Convert a Uint8Array to string, each uint8 to the single character of that char code\n * @param a - Uint8Array to convert\n * @returns result string\n */\nexport function str(a: Uint8Array): string {\n  return env.uint8array_to_latin1_string(a);\n}\n\n/**\n * Encode the string to Uint8Array with UTF-8 encoding\n * @param s - String to encode\n * @returns result Uint8Array\n */\nexport function encode(s: string): Uint8Array {\n  return env.utf8_string_to_uint8array(s);\n}\n\n/**\n * Decode the Uint8Array to string in UTF-8 encoding\n * @param a - array to decode\n * @returns result string\n */\nexport function decode(a: Uint8Array): string {\n  return env.uint8array_to_utf8_string(a);\n}\n\n/**\n * When implemented, allow object to be stored as collection key\n */\nexport interface IntoStorageKey {\n  into_storage_key(): string;\n}\n"
  },
  {
    "path": "packages/near-sdk-js/src/version.ts",
    "content": "import * as fs from \"fs\";\nimport { fileURLToPath } from \"url\";\n\nconst PACKAGE_JSON = JSON.parse(\n  fs.readFileSync(\n    fileURLToPath(new URL(\"../package.json\", import.meta.url)),\n    \"utf-8\"\n  )\n);\nexport const LIB_VERSION: string = PACKAGE_JSON[\"version\"];\n"
  },
  {
    "path": "packages/near-sdk-js/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"esModuleInterop\": true,\n    \"lib\": [\"es2015\", \"esnext\", \"dom\"],\n    \"module\": \"esnext\",\n    \"target\": \"es2020\",\n    \"moduleResolution\": \"node\",\n    \"alwaysStrict\": true,\n    \"outDir\": \"./lib\",\n    \"declaration\": true,\n    \"preserveSymlinks\": true,\n    \"preserveWatchOutput\": true,\n    \"pretty\": false,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noImplicitAny\": false,\n    \"noImplicitReturns\": true,\n    \"noUnusedLocals\": true,\n    \"experimentalDecorators\": true,\n    \"resolveJsonModule\": true,\n    \"allowJs\": true,\n    \"skipLibCheck\": true\n  },\n  \"files\": [\n    \"src/index.ts\",\n    \"src/cli/build-tools/near-bindgen-exporter.ts\",\n    \"src/cli/build-tools/include-bytes.ts\",\n    \"src/cli/cli.ts\",\n    \"src/cli/post-install.ts\"\n  ]\n}\n"
  },
  {
    "path": "packages/near-sdk-js/typedoc.json",
    "content": "{\n  \"extends\": [\"../../typedoc.json\"],\n  \"entryPoints\": [\"src\"],\n  \"entryPointStrategy\": \"expand\"\n}\n"
  },
  {
    "path": "pnpm-workspace.yaml",
    "content": "packages:\n  - \"examples\"\n  - \"tests\"\n  - \"packages/*\"\n  - \"benchmark\""
  },
  {
    "path": "tests/.gitignore",
    "content": "node_modules\nbuild"
  },
  {
    "path": "tests/README.md",
    "content": "# NEAR-SDK-JS Tests\n\nThis tests the functionality of high level APIs of NEAR-SDK-JS. Currently, it directly tests all collections and indirectly tests all decorators, serialization/deserialization, utils, code generation and some important APIs. Majority of near-sdk-js can be seen as tested.\n\n# Run tests\n\n```\npnpm install\npnpm build\npnpm test\n```\n\n# Add a new test\n\nCreate a test contract that covers the API you want to test in `src/`. Add a build command in `build.sh`. Write ava test in `__tests__`.\n"
  },
  {
    "path": "tests/__tests__/abi/abi.ava.js",
    "content": "import test from \"ava\";\nimport { generateAbiSnippet } from \"./util.js\";\n\ntest(\"Simple function\", async (t) => {\n  const abi = await generateAbiSnippet(\"simple_function.ts\");\n  t.deepEqual(abi.body.functions[0], {\n    name: \"add\",\n    kind: \"view\",\n    params: {\n      serialization_type: \"json\",\n      args: [\n        {\n          name: \"a\",\n          type_schema: {\n            type: \"number\",\n          },\n        },\n        {\n          name: \"b\",\n          type_schema: {\n            type: \"number\",\n          },\n        },\n      ],\n    },\n    result: {\n      serialization_type: \"json\",\n      type_schema: {\n        type: \"number\",\n      },\n    },\n  });\n});\n\ntest(\"JSON Schema\", async (t) => {\n  const abi = await generateAbiSnippet(\"json_schema.ts\");\n\n  t.is(abi.body.functions[0].params.args.length, 1);\n  t.is(abi.body.functions[0].params.serialization_type, \"json\");\n  t.deepEqual(abi.body.functions[0].params.args[0], {\n    name: \"a\",\n    type_schema: {\n      type: \"number\",\n    },\n  });\n\n  t.deepEqual(abi.body.functions[1].params.args[0], {\n    name: \"a\",\n    type_schema: {\n      type: \"string\",\n    },\n  });\n\n  t.deepEqual(abi.body.functions[2].params.args, [\n    {\n      name: \"a\",\n      type_schema: {\n        type: \"boolean\",\n      },\n    },\n    {\n      name: \"b\",\n      type_schema: {\n        type: \"null\",\n      },\n    },\n  ]);\n\n  t.deepEqual(abi.body.functions[3].params.args, [\n    {\n      name: \"a\",\n      type_schema: {\n        items: [{ type: \"boolean\" }],\n        maxItems: 1,\n        minItems: 1,\n        type: \"array\",\n      },\n    },\n    {\n      name: \"b\",\n      type_schema: {\n        items: [{ type: \"boolean\" }, { type: \"boolean\" }],\n        maxItems: 2,\n        minItems: 2,\n        type: \"array\",\n      },\n    },\n    {\n      name: \"c\",\n      type_schema: {\n        items: [{ type: \"boolean\" }, { type: \"boolean\" }, { type: \"boolean\" }],\n        maxItems: 3,\n        minItems: 3,\n        type: \"array\",\n      },\n    },\n  ]);\n\n  t.deepEqual(abi.body.functions[4].params.args, [\n    {\n      name: \"a\",\n      type_schema: {\n        items: { type: \"boolean\" },\n        type: \"array\",\n      },\n    },\n  ]);\n\n  // typescript use structural type, so no ref to Pair\n  t.deepEqual(abi.body.functions[5].params.args, [\n    {\n      name: \"a\",\n      type_schema: {\n        items: [{ type: \"number\" }, { type: \"number\" }],\n        type: \"array\",\n        minItems: 2,\n        maxItems: 2,\n      },\n    },\n    { name: \"b\", type_schema: { $ref: \"#/definitions/PairNamed\" } },\n  ]);\n  t.deepEqual(abi.body.root_schema.definitions[\"PairNamed\"], {\n    properties: {\n      first: {\n        type: \"number\",\n      },\n      second: {\n        type: \"number\",\n      },\n    },\n    type: \"object\",\n  });\n\n  t.deepEqual(abi.body.root_schema.definitions[\"IpAddrKind\"], {\n    enum: [0, 1],\n    type: \"number\",\n  });\n  t.deepEqual(abi.body.root_schema.definitions[\"IpV4\"], {\n    type: \"object\",\n    properties: {\n      kind: {\n        $ref: \"#/definitions/IpAddrKind.V4\",\n      },\n      octets: {\n        items: [\n          { type: \"number\" },\n          { type: \"number\" },\n          { type: \"number\" },\n          { type: \"number\" },\n        ],\n        maxItems: 4,\n        minItems: 4,\n        type: \"array\",\n      },\n    },\n  });\n  t.deepEqual(abi.body.root_schema.definitions[\"IpV6\"], {\n    type: \"object\",\n    properties: {\n      kind: {\n        $ref: \"#/definitions/IpAddrKind.V6\",\n      },\n      address: {\n        type: \"string\",\n      },\n    },\n  });\n  t.deepEqual(abi.body.functions[6].params.args, [\n    {\n      name: \"simple\",\n      type_schema: { $ref: \"#/definitions/IpAddrKind\" },\n    },\n    {\n      name: \"complex\",\n      type_schema: {\n        anyOf: [\n          {\n            $ref: \"#/definitions/IpV4\",\n          },\n          {\n            $ref: \"#/definitions/IpV6\",\n          },\n        ],\n      },\n    },\n  ]);\n});\n\ntest(\"Modifiers function\", async (t) => {\n  const abi = await generateAbiSnippet(\"modifiers.ts\");\n  t.is(abi.body.functions[0].kind, \"view\");\n  t.is(abi.body.functions[0].modifiers, undefined);\n\n  t.is(abi.body.functions[1].kind, \"call\");\n  t.is(abi.body.functions[1].modifiers, undefined);\n\n  t.is(abi.body.functions[2].kind, \"call\");\n  t.deepEqual(abi.body.functions[2].modifiers, [\"init\"]);\n\n  t.is(abi.body.functions[3].kind, \"call\");\n  t.deepEqual(abi.body.functions[3].modifiers, [\"payable\"]);\n\n  t.is(abi.body.functions[4].kind, \"call\");\n  t.deepEqual(abi.body.functions[4].modifiers, [\"private\"]);\n});\n\ntest(\"Function return\", async (t) => {\n  const abi = await generateAbiSnippet(\"return.ts\");\n  t.deepEqual(abi.body.functions[0], {\n    name: \"foo\",\n    kind: \"view\",\n  });\n  t.deepEqual(abi.body.functions[1], {\n    name: \"bar\",\n    kind: \"view\",\n    result: {\n      serialization_type: \"json\",\n      type_schema: {\n        type: \"number\",\n      },\n    },\n  });\n});\n"
  },
  {
    "path": "tests/__tests__/abi/testcases/json_schema.ts",
    "content": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\n\ntype Pair = [number, number];\n\ninterface PairNamed {\n  first: number;\n  second: number;\n}\n\nenum IpAddrKind {\n  V4,\n  V6,\n}\n\ninterface IpV4 {\n  kind: IpAddrKind.V4;\n  octets: [number, number, number, number];\n}\n\ninterface IpV6 {\n  kind: IpAddrKind.V6;\n  address: string;\n}\n\ntype IpAddr = IpV4 | IpV6;\n\n@NearBindgen({})\nexport class Contract {\n  @view({})\n  numeric({ a }: { a: number }) {}\n\n  @view({})\n  schema_string({ a }: { a: string }) {}\n\n  @view({})\n  schema_other_primitives({ a, b }: { a: boolean; b: null }) {}\n\n  @view({})\n  schema_tuples({\n    a,\n    b,\n    c,\n  }: {\n    a: [boolean];\n    b: [boolean, boolean];\n    c: [boolean, boolean, boolean];\n  }) {}\n\n  @view({})\n  schema_array({ a }: { a: boolean[] }) {}\n\n  @view({})\n  schema_struct({ a, b }: { a: Pair; b: PairNamed }) {}\n\n  @view({})\n  schema_enum({ simple, complex }: { simple: IpAddrKind; complex: IpAddr }) {}\n}\n"
  },
  {
    "path": "tests/__tests__/abi/testcases/modifiers.ts",
    "content": "import { NearBindgen, near, call, view, initialize } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class Contract {\n  @view({})\n  add({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n\n  @call({})\n  add2({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n\n  @initialize({})\n  add3({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n\n  @call({ payableFunction: true })\n  add4({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n\n  @call({ privateFunction: true })\n  add5({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n}\n"
  },
  {
    "path": "tests/__tests__/abi/testcases/return.ts",
    "content": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class Contract {\n  @view({})\n  foo() {}\n\n  @view({})\n  bar(): number {\n    return 0;\n  }\n}\n"
  },
  {
    "path": "tests/__tests__/abi/testcases/simple_function.ts",
    "content": "import { NearBindgen, near, call, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class Contract {\n  @view({})\n  add({ a, b }: { a: number; b: number }): number {\n    return a + b;\n  }\n}\n"
  },
  {
    "path": "tests/__tests__/abi/util.js",
    "content": "import path from \"path\";\nimport fs from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport { runAbiCompilerPlugin } from \"near-sdk-js/lib/cli/abi.js\";\nimport { randomBytes } from \"crypto\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport async function generateAbiSnippet(filename) {\n  const packageJsonPath = path.join(__dirname, \"../../package.json\");\n  const tsConfigJsonPath = path.join(__dirname, \"../../tsconfig.json\");\n\n  const filepath = path.join(__dirname, \"testcases\", filename);\n  return runAbiCompilerPlugin(filepath, packageJsonPath, tsConfigJsonPath);\n}\n"
  },
  {
    "path": "tests/__tests__/bytes.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const bytesContract = await root.createSubAccount(\"bytes-contract\");\n  await bytesContract.deploy(\"build/bytes.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, bytesContract, ali, bob };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Log expected types work\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  let r = await ali.callRaw(bytesContract, \"log_expected_input_tests\", \"\");\n  t.deepEqual(r.result.receipts_outcome[0].outcome.logs, [\n    \"abc\",\n    \"水\",\n    \"333\",\n    \"\\x00\\x01\\xff\",\n    \"\\xe6\\xb0\\xb4\",\n    \"水\",\n    \"水\",\n  ]);\n});\n\ntest(\"Log unexpected types not logging\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  let r = await ali.callRaw(bytesContract, \"log_unexpected_input_tests\", \"\");\n  // logUtf8 and logUtf16 only works with bytes, trying to log it with string is error\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Expect Uint8Array for message\"\n    )\n  );\n  t.deepEqual(r.result.receipts_outcome[0].outcome.logs, []);\n});\n\ntest(\"Log invalid utf-8 sequence panic\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  let r = await ali.callRaw(\n    bytesContract,\n    \"log_invalid_utf8_sequence_test\",\n    \"\"\n  );\n  // console.log(JSON.stringify(r, null, 2))\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-8 sequence.\"\n  );\n});\n\ntest(\"Log invalid utf-16 sequence panic\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  let r = await ali.callRaw(\n    bytesContract,\n    \"log_invalid_utf16_sequence_test\",\n    \"\"\n  );\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-16 sequence.\"\n  );\n});\n\nfunction encodeStateKey(k) {\n  return Buffer.from(k).toString(\"base64\");\n}\n\ntest(\"storage write bytes tests. Any latin1 string: ascii, valid or invalid utf-8 sequence can be convert to Uint8Array correctly\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  await ali.call(bytesContract, \"storage_write_bytes\", \"\");\n  let stateMap = new Map();\n  // viewState doesn't work, because it tries to convert key to utf-8 string, which is not. So we use viewStateRaw\n  let state = await bytesContract.viewStateRaw();\n  for (let { key, value } of state) {\n    stateMap.set(key, value);\n  }\n\n  t.deepEqual(\n    stateMap.get(encodeStateKey(\"abc\")),\n    Buffer.from(\"def\").toString(\"base64\")\n  );\n  t.deepEqual(\n    stateMap.get(encodeStateKey([0x00, 0x01, 0xff])),\n    Buffer.from([0xe6, 0xb0, 0xb4]).toString(\"base64\")\n  );\n  t.deepEqual(\n    stateMap.get(encodeStateKey([0xe6, 0xb0, 0xb4])),\n    Buffer.from([0x00, \"a\".charCodeAt(0), \"b\".charCodeAt(0)]).toString(\"base64\")\n  );\n});\n\ntest(\"storage write utf8, utf8 string convert to Uint8Array tests\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  await ali.call(bytesContract, \"storage_write_utf8\", \"\");\n  let r = await bytesContract.viewRaw(\"storage_read_utf8\", \"\");\n  t.deepEqual(r.result, [...Buffer.from(\"😂\", \"utf-8\")]);\n});\n\ntest(\"Storage read bytes tests\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n\n  await ali.call(bytesContract, \"storage_write_bytes\", \"\");\n  let r = await bytesContract.viewRaw(\"storage_read_ascii_bytes\", \"\");\n  console.log(r);\n  t.deepEqual(r.result, [100, 101, 102]);\n\n  r = await bytesContract.viewRaw(\n    \"storage_read_arbitrary_bytes_key_utf8_sequence_bytes_value\",\n    \"\"\n  );\n  t.deepEqual(r.result, [0xe6, 0xb0, 0xb4]);\n\n  r = await bytesContract.viewRaw(\n    \"storage_read_utf8_sequence_bytes_key_arbitrary_bytes_value\",\n    \"\"\n  );\n  t.deepEqual(r.result, [0x00, \"a\".charCodeAt(0), \"b\".charCodeAt(0)]);\n});\n\ntest(\"panic tests\", async (t) => {\n  const { ali, bytesContract } = t.context.accounts;\n  let r = await ali.callRaw(bytesContract, \"panic_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked:*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panic_ascii_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: abc*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panic_js_number\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: 356*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panic_js_undefined\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked:*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panic_js_null\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: null*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panic_utf8_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: 水*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panicUtf8_valid_utf8_sequence\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: 水*/\n    )\n  );\n\n  r = await ali.callRaw(bytesContract, \"panicUtf8_invalid_utf8_sequence\", \"\");\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-8 sequence.\"\n  );\n});\n\ntest(\"utf8 string can be convert to Uint8Array correctly\", async (t) => {\n  const { bob, bytesContract } = t.context.accounts;\n\n  let res = await bob.callRaw(\n    bytesContract,\n    \"utf8_string_to_uint8array_tests\",\n    \"\"\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n});\n\ntest(\"valid utf8 sequence can be convert to string correctly\", async (t) => {\n  const { bob, bytesContract } = t.context.accounts;\n\n  let res = await bob.callRaw(\n    bytesContract,\n    \"uint8array_to_utf8_string_tests\",\n    \"\"\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n});\n\ntest(\"latin1 sequence can be convert to string correctly\", async (t) => {\n  const { bob, bytesContract } = t.context.accounts;\n\n  let res = await bob.callRaw(\n    bytesContract,\n    \"uint8array_to_latin1_string_tests\",\n    \"\"\n  );\n  t.is(res.result.status.SuccessValue, \"\");\n});\n"
  },
  {
    "path": "tests/__tests__/constructor_validation.ava.js",
    "content": "import test from \"ava\";\nimport { execSync } from \"child_process\";\n\nconst BUILD_FAILURE_ERROR_CODE = 1;\n\ntest(\"should not throw error, constructor is correctly initialized\", async (t) => {\n  t.notThrows(() => {\n    execSync(\n      \"near-sdk-js build src/constructor-validation/all-parameters-set-in-constructor.ts build/all-parameters-set-in-constructor.wasm\"\n    );\n  });\n});\n\ntest(\"should throw error, name is not inited\", async (t) => {\n  const error = t.throws(() => {\n    execSync(\n      \"near-sdk-js build src/constructor-validation/1-parameter-not-set-in-constructor.ts build/1-parameter-not-set-in-constructor.wasm\"\n    );\n  });\n  t.is(error.status, BUILD_FAILURE_ERROR_CODE);\n});\n\ntest(\"should throw error, construcor is empty\", async (t) => {\n  const error = t.throws(() => {\n    execSync(\n      \"near-sdk-js build src/constructor-validation/no-parameters-set-in-constructor.ts build/no-parameters-set-in-constructor.wasm\"\n    );\n  });\n  t.is(error.status, BUILD_FAILURE_ERROR_CODE);\n});\n\ntest(\"should throw error, construcor is not declared\", async (t) => {\n  const error = t.throws(() => {\n    execSync(\n      \"near-sdk-js build src/constructor-validation/no-constructor.ts build/no-constructor.wasm\"\n    );\n  });\n  t.is(error.status, BUILD_FAILURE_ERROR_CODE);\n});\n"
  },
  {
    "path": "tests/__tests__/decorators/migrate.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n  const counter = await root.devDeploy(\"./build/migrate.wasm\");\n\n  const ali = await root.createSubAccount(\"ali\");\n\n  t.context.worker = worker;\n  t.context.accounts = { root, counter, ali };\n});\n\n// If the environment is reused, use test.after to replace test.afterEach\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"migration works\", async (t) => {\n  const { counter, ali } = t.context.accounts;\n\n  const res1 = await counter.view(\"getCount\", {});\n  t.is(res1, 0);\n\n  await ali.call(counter, \"increase\", {});\n\n  const res2 = await counter.view(\"getCount\", {});\n  t.is(res2, 1);\n\n  const migrationRes = await ali.callRaw(counter, \"migrFuncValueTo18\", {});\n\n  t.is(JSON.stringify(migrationRes).includes(\"Count: 0\"), true);\n\n  const res3 = await counter.view(\"getCount\", {});\n  t.is(res3, 18);\n});\n"
  },
  {
    "path": "tests/__tests__/decorators/near_bindgen.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const reqireInitFalse = await root.devDeploy(\"build/require_init_false.wasm\");\n  const reqireInitTrue = await root.devDeploy(\"build/require_init_true.wasm\");\n\n  const ali = await root.createSubAccount(\"ali\");\n\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    reqireInitFalse,\n    reqireInitTrue,\n    ali,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Uninitialized contract throw error if requireInit = true\", async (t) => {\n  const { ali, reqireInitTrue } = t.context.accounts;\n\n  const callResult = await ali.callRaw(reqireInitTrue, \"setStatus\", {\n    status: \"hello\",\n  });\n  t.assert(\n    callResult.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Contract must be initialized\"\n    )\n  );\n\n  const err = await t.throwsAsync(() => reqireInitTrue.view(\"getStatus\", {}));\n  t.assert(err.message.includes(\"Contract must be initialized\"));\n});\n\ntest(\"Uninitialized contract does not throw error if requireInit = false\", async (t) => {\n  const { ali, reqireInitFalse } = t.context.accounts;\n\n  await ali.callRaw(reqireInitFalse, \"setStatus\", { status: \"hello\" });\n\n  t.is(await reqireInitFalse.view(\"getStatus\", {}), \"hello\");\n});\n\ntest(\"Init function panics if called more then once\", async (t) => {\n  const { ali, reqireInitTrue, reqireInitFalse } = t.context.accounts;\n\n  await ali.call(reqireInitTrue, \"init\", { status: \"hello\" });\n  const res1 = await ali.callRaw(reqireInitTrue, \"init\", { status: \"hello\" });\n  t.assert(\n    res1.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Contract already initialized\"\n    )\n  );\n\n  await ali.call(reqireInitFalse, \"init\", { status: \"hello\" });\n  const res2 = await ali.callRaw(reqireInitFalse, \"init\", { status: \"hello\" });\n  t.assert(\n    res2.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Contract already initialized\"\n    )\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/decorators/payable.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\nconst DEPOSIT = 1_000_000_000;\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const payableContract = await root.devDeploy(\"build/payable.wasm\");\n  const ali = await root.createSubAccount(\"ali\");\n\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    payableContract,\n    ali,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"payable: true functions works with deposit\", async (t) => {\n  const { ali, payableContract } = t.context.accounts;\n\n  await t.notThrowsAsync(\n    ali.call(\n      payableContract,\n      \"setValueWithPayableFunction\",\n      { value: \"hello\" },\n      { attachedDeposit: DEPOSIT }\n    )\n  );\n});\n\ntest(\"payable: true functions works without deposit\", async (t) => {\n  const { ali, payableContract } = t.context.accounts;\n\n  await t.notThrowsAsync(\n    ali.call(payableContract, \"setValueWithPayableFunction\", { value: \"hello\" })\n  );\n});\n\ntest(\"payable: false throws if atach deposit\", async (t) => {\n  const { ali, payableContract } = t.context.accounts;\n\n  const result = await ali.callRaw(\n    payableContract,\n    \"setValueWithNotPayableFunction\",\n    { value: \"hello\" },\n    { attachedDeposit: DEPOSIT }\n  );\n\n  t.assert(\n    result.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Function is not payable\"\n    )\n  );\n});\n\ntest(\"payable default throws if atach deposit\", async (t) => {\n  const { ali, payableContract } = t.context.accounts;\n\n  const result = await ali.callRaw(\n    payableContract,\n    \"setValueWithNotPayableFunctionByDefault\",\n    { value: \"hello\" },\n    { attachedDeposit: DEPOSIT }\n  );\n  t.assert(\n    result.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Function is not payable\"\n    )\n  );\n});\n\ntest(\"payable default works without deposit\", async (t) => {\n  const { ali, payableContract } = t.context.accounts;\n\n  await t.notThrowsAsync(\n    ali.call(payableContract, \"setValueWithNotPayableFunctionByDefault\", {\n      value: \"hello\",\n    })\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/decorators/private.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  const worker = await Worker.init();\n  const root = worker.rootAccount;\n\n  const contract = await root.devDeploy(\"build/private.wasm\");\n  const ali = await root.createSubAccount(\"ali\");\n\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    contract,\n    ali,\n  };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"private: true throws if called from another acc\", async (t) => {\n  const { ali, contract } = t.context.accounts;\n\n  const result = await ali.callRaw(contract, \"setValueWithPrivateFunction\", {\n    value: \"hello\",\n  });\n\n  t.assert(\n    result.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Function is private\"\n    )\n  );\n});\n\ntest(\"private: true not throws if called from owner acc\", async (t) => {\n  const { contract } = t.context.accounts;\n\n  await t.notThrowsAsync(\n    contract.call(contract, \"setValueWithNotPrivateFunction\", {\n      value: \"hello\",\n    })\n  );\n});\n\ntest(\"private: default not throws from another acc\", async (t) => {\n  const { ali, contract } = t.context.accounts;\n\n  await t.notThrowsAsync(\n    ali.call(contract, \"setValueWithNotPrivateFunctionByDefault\", {\n      value: \"hello\",\n    })\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/function-params.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  const functionParamsContract = await root.createSubAccount(\n    \"function-params-contract\"\n  );\n  await functionParamsContract.deploy(\"build/function-params.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, functionParamsContract, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"get current account id correct\", async (t) => {\n  const { ali, functionParamsContract } = t.context.accounts;\n  await ali.call(functionParamsContract, \"set_values\", {\n    param1: \"newVal1\",\n    param2: \"newVal2\",\n    param3: \"newVal3\",\n  });\n  let values = await functionParamsContract.view(\"get_values\", \"\");\n  t.deepEqual(values, { val3: \"newVal3\", val2: \"newVal2\", val1: \"newVal1\" });\n});\n"
  },
  {
    "path": "tests/__tests__/lookup-map.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const lookupMapContract = await root.createSubAccount(\"lookup-map-contract\");\n  await lookupMapContract.deploy(\"build/lookup-map.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, lookupMapContract, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"LookupMap set() get()\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), null);\n  t.is(await lookupMapContract.view(\"containsKey\", { key: \"hello\" }), false);\n\n  await ali.call(lookupMapContract, \"set\", { key: \"hello\", value: \"world\" });\n\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n  t.is(await lookupMapContract.view(\"containsKey\", { key: \"hello\" }), true);\n});\n\ntest(\"LookupMap update, remove\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n\n  await ali.call(lookupMapContract, \"set\", { key: \"hello\", value: \"world\" });\n  await ali.call(lookupMapContract, \"set\", { key: \"hello1\", value: \"world0\" });\n\n  // update a value, len shouldn't change\n  await ali.call(lookupMapContract, \"set\", { key: \"hello1\", value: \"world1\" });\n  // update should have effect\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello1\" }), \"world1\");\n  // not update key should not changed\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n  // remove non existing element should not error\n  await ali.call(lookupMapContract, \"remove_key\", { key: \"hello3\" });\n  // remove existing key should work\n  await ali.call(lookupMapContract, \"remove_key\", { key: \"hello1\" });\n  t.is(await lookupMapContract.view(\"containsKey\", { key: \"hello1\" }), false);\n  // not removed key should not affected\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n});\n\ntest(\"LookupMap extend\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n\n  await ali.call(lookupMapContract, \"extend\", {\n    kvs: [\n      [\"hello\", \"world\"],\n      [\"hello1\", \"world1\"],\n      [\"hello2\", \"world2\"],\n    ],\n  });\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello1\" }), \"world1\");\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello2\" }), \"world2\");\n});\n\ntest(\"LookupMap set get object\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n  await ali.call(lookupMapContract, \"add_house\", {});\n  t.is(\n    await lookupMapContract.view(\"get_house\", {}),\n    \"house house1 has 2 rooms. room room1 is 200sqft.\"\n  );\n});\n\ntest(\"LookupMap allows you to use the same key for the second time\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n\n  await ali.call(lookupMapContract, \"set\", { key: \"hello\", value: \"world\" });\n  await ali.call(lookupMapContract, \"set\", { key: \"hello\", value: \"world\" });\n\n  t.is(await lookupMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n});\n\ntest.only(\"UTF-8 in arguments, store in collections & state, return in returns\", async (t) => {\n  const { ali, lookupMapContract } = t.context.accounts;\n\n  let data = {\n    utf8emoji: \"😂\",\n    utf8char: \"水\",\n    // this is the byte sequence of above utf8 char, it will be escaped in js contract\n    // so it won't be mis-recorgnized as above utf8 char.\n    utf8char_charcode_seq: \"\\xe6\\xb0\\xb4\",\n    // this and above shows arbitrary binary data can be put in arguments, state and return\n    // default serialization and deserialization works\n    latin1_charcode_seq: \"\\xc2\\x00\\x01\\xff\",\n  };\n  let res = await ali.callRaw(lookupMapContract, \"set\", {\n    key: \"utf8test\",\n    value: data,\n  });\n  t.is(res.result.status.SuccessValue, \"\");\n\n  t.deepEqual(await lookupMapContract.view(\"get\", { key: \"utf8test\" }), data);\n});\n"
  },
  {
    "path": "tests/__tests__/lookup-set.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const lookupSetContract = await root.createSubAccount(\"lookup-set-contract\");\n  await lookupSetContract.deploy(\"build/lookup-set.wasm\");\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, lookupSetContract, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"LookupSet set() contains()\", async (t) => {\n  const { ali, lookupSetContract } = t.context.accounts;\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello\" }), false);\n\n  await ali.call(lookupSetContract, \"set\", { key: \"hello\" });\n\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello\" }), true);\n});\n\ntest(\"LookupSet remove\", async (t) => {\n  const { ali, lookupSetContract } = t.context.accounts;\n\n  await ali.call(lookupSetContract, \"set\", { key: \"hello\" });\n  await ali.call(lookupSetContract, \"set\", { key: \"hello1\" });\n\n  // remove non existing element should not error\n  await ali.call(lookupSetContract, \"remove_key\", { key: \"hello3\" });\n  // remove existing key should work\n  await ali.call(lookupSetContract, \"remove_key\", { key: \"hello1\" });\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello1\" }), false);\n  // not removed key should not affected\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello\" }), true);\n});\n\ntest(\"LookupSet extend\", async (t) => {\n  const { ali, lookupSetContract } = t.context.accounts;\n\n  await ali.call(lookupSetContract, \"extend\", {\n    keys: [\"hello\", \"world\", \"hello1\"],\n  });\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello\" }), true);\n  t.is(await lookupSetContract.view(\"contains\", { key: \"hello1\" }), true);\n  t.is(await lookupSetContract.view(\"contains\", { key: \"world\" }), true);\n});\n\ntest(\"Add and check exist of object\", async (t) => {\n  const { ali, lookupSetContract } = t.context.accounts;\n  let houseSpec = { name: \"a\", rooms: [{ name: \"bedroom\", size: \"300sqft\" }] };\n  t.is(await lookupSetContract.view(\"house_exist\", houseSpec), false);\n  await ali.call(lookupSetContract, \"add_house\", houseSpec);\n  t.is(await lookupSetContract.view(\"house_exist\", houseSpec), true);\n});\n"
  },
  {
    "path": "tests/__tests__/test-bigint-serialization.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Create and deploy test contract\n  const bsContract = await root.devDeploy(\"build/bigint-serialization.wasm\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, bsContract };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"get initial bigint field value\", async (t) => {\n  const { bsContract } = t.context.accounts;\n  const bigintField = await bsContract.view(\"getBigintField\");\n  t.is(bigintField, `${1n}`);\n});\n\ntest(\"get bigint field after increment\", async (t) => {\n  const { bsContract } = t.context.accounts;\n  const bigintField = await bsContract.view(\"getBigintField\");\n  t.is(bigintField, `${1n}`);\n\n  await bsContract.call(bsContract, \"increment\", \"\");\n  const afterIncrement = await bsContract.view(\"getBigintField\");\n  t.is(afterIncrement, `${2n}`);\n});\n\ntest(\"get bigint field after set\", async (t) => {\n  const { bsContract } = t.context.accounts;\n  const bigintField = await bsContract.view(\"getBigintField\");\n  t.is(bigintField, `${1n}`);\n\n  await bsContract.call(bsContract, \"setBigintField\", { bigintField: `${3n}` });\n  const afterSet = await bsContract.view(\"getBigintField\");\n  t.is(afterSet, `${3n}`);\n});\n"
  },
  {
    "path": "tests/__tests__/test-date-serialization.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Create and deploy test contract\n  const dsContract = await root.createSubAccount(\"ds-contract\");\n  await dsContract.deploy(\"build/date-serialization.wasm\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, dsContract };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"get initial date field value\", async (t) => {\n  const { dsContract } = t.context.accounts;\n  const dateField = await dsContract.view(\"getDateField\");\n  t.is(dateField, new Date(0).toISOString());\n});\n\ntest(\"get date field after set\", async (t) => {\n  const { dsContract } = t.context.accounts;\n  const dateField = await dsContract.view(\"getDateField\");\n  t.is(dateField, new Date(0).toISOString());\n\n  const newDate = new Date();\n  await dsContract.call(dsContract, \"setDateField\", { dateField: newDate });\n  const afterSet = await dsContract.view(\"getDateField\");\n  t.is(afterSet, newDate.toISOString());\n});\n\ntest(\"get date field in milliseconds\", async (t) => {\n  const { dsContract } = t.context.accounts;\n  const dateField = await dsContract.view(\"getDateFieldAsMilliseconds\");\n  t.is(dateField, new Date(0).getTime());\n\n  const newDate = new Date();\n  await dsContract.call(dsContract, \"setDateField\", { dateField: newDate });\n  const afterIncrement = await dsContract.view(\"getDateFieldAsMilliseconds\");\n  t.is(afterIncrement, newDate.getTime());\n});\n"
  },
  {
    "path": "tests/__tests__/test-middlewares.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the contract.\n  const middlewares = await root.createSubAccount(\"middlewares-contract\");\n  await middlewares.deploy(\"build/middlewares.wasm\");\n\n  // Create the init args.\n  const args = JSON.stringify({ randomData: \"anything\" });\n  // Capture the result of the init function call.\n  const result = await middlewares.callRaw(middlewares, \"init\", args);\n\n  // Extract the logs.\n  const { logs } = result.result.receipts_outcome[0].outcome;\n  // Create the expected logs.\n  const expectedLogs = [`Log from middleware: ${args}`];\n\n  // Check for correct logs.\n  t.deepEqual(logs, expectedLogs);\n\n  // Create test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, middlewares, ali };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"The middleware logs with call functions\", async (t) => {\n  const { ali, middlewares } = t.context.accounts;\n\n  // Create the arguments which will be passed to the function.\n  const args = JSON.stringify({ id: \"1\", text: \"hello\" });\n  // Call the function.\n  const result = await ali.callRaw(middlewares, \"add\", args);\n  // Extract the logs.\n  const { logs } = result.result.receipts_outcome[0].outcome;\n  // Create the expected logs.\n  const expectedLogs = [`Log from middleware: ${args}`];\n\n  t.deepEqual(logs, expectedLogs);\n});\n\ntest(\"The middleware logs with view functions\", async (t) => {\n  const { ali, middlewares } = t.context.accounts;\n\n  // Create the arguments which will be passed to the function.\n  const args = JSON.stringify({ id: \"1\", accountId: \"hello\" });\n  // Call the function.\n  const result = await ali.callRaw(middlewares, \"get\", args);\n  // Extract the logs.\n  const { logs } = result.result.receipts_outcome[0].outcome;\n  // Create the expected logs.\n  const expectedLogs = [`Log from middleware: ${args}`];\n\n  t.deepEqual(logs, expectedLogs);\n});\n\ntest(\"The middleware logs with two middleware functions\", async (t) => {\n  const { ali, middlewares } = t.context.accounts;\n\n  // Create the arguments which will be passed to the function.\n  const args = JSON.stringify({ id: \"1\", accountId: \"hello\" });\n  // Call the function.\n  const result = await ali.callRaw(middlewares, \"get_two\", args);\n  // Extract the logs.\n  const { logs } = result.result.receipts_outcome[0].outcome;\n  // Create the expected logs.\n  const expectedLogs = [`Log from middleware: ${args}`, \"Second log!\"];\n\n  t.deepEqual(logs, expectedLogs);\n});\n\ntest(\"The middleware logs with private functions\", async (t) => {\n  const { ali, middlewares } = t.context.accounts;\n\n  // Create the arguments which will be passed to the function.\n  const args = { id: \"test\", accountId: \"tset\" };\n  // Call the function.\n  const result = await ali.callRaw(middlewares, \"get_private\", \"\");\n  // Extract the logs.\n  const { logs } = result.result.receipts_outcome[0].outcome;\n  // Create the expected logs.\n  const expectedLogs = [`Log from middleware: ${args}`];\n\n  t.deepEqual(logs, expectedLogs);\n});\n"
  },
  {
    "path": "tests/__tests__/test-public-key.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Create and deploy test contract\n  const pkContract = await root.createSubAccount(\"pk\");\n  await pkContract.deploy(\"build/public-key.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, pkContract, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"add signer key should success\", async (t) => {\n  const { ali, pkContract } = t.context.accounts;\n  let r = await ali.callRaw(pkContract, \"test_add_signer_key\", \"\");\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"add ed25519 key bytes should success\", async (t) => {\n  const { ali, pkContract } = t.context.accounts;\n  let r = await ali.callRaw(pkContract, \"test_add_ed25519_key_bytes\", \"\");\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"add ed25519 key string should success\", async (t) => {\n  const { ali, pkContract } = t.context.accounts;\n  let r = await ali.callRaw(pkContract, \"test_add_ed25519_key_string\", \"\");\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"add secp256k1 key bytes should success\", async (t) => {\n  const { bob, pkContract } = t.context.accounts;\n  let r = await bob.callRaw(pkContract, \"test_add_secp256k1_key_bytes\", \"\");\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"add secp256k1 key string should success\", async (t) => {\n  const { bob, pkContract } = t.context.accounts;\n  let r = await bob.callRaw(pkContract, \"test_add_secp256k1_key_string\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"add invalid key should error\", async (t) => {\n  const { bob, pkContract } = t.context.accounts;\n  let r = await bob.callRaw(pkContract, \"add_invalid_public_key\", \"\");\n  t.is(r.result.status.SuccessValue, undefined);\n  t.is(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError,\n    \"VM Logic provided an invalid public key\"\n  );\n});\n\ntest(\"curve type check should success\", async (t) => {\n  const { carl, pkContract } = t.context.accounts;\n  let r = await carl.callRaw(pkContract, \"curve_type\", \"\");\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"create invalid curve type should fail\", async (t) => {\n  const { carl, pkContract } = t.context.accounts;\n  let r = await carl.callRaw(pkContract, \"create_invalid_curve_type\", \"\");\n  t.is(r.result.status.SuccessValue, undefined);\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Unknown curve\"\n    )\n  );\n});\n\ntest(\"create invalid length should fail\", async (t) => {\n  const { carl, pkContract } = t.context.accounts;\n  let r = await carl.callRaw(pkContract, \"create_invalid_length\", \"\");\n  t.is(r.result.status.SuccessValue, undefined);\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Invalid length\"\n    )\n  );\n});\n\ntest(\"create invalid base58 should fail\", async (t) => {\n  const { carl, pkContract } = t.context.accounts;\n  let r = await carl.callRaw(pkContract, \"create_from_invalid_base58\", \"\");\n  t.is(r.result.status.SuccessValue, undefined);\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Base58 error\"\n    )\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/test_alt_bn128_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const altBn128ApiContract = await root.devDeploy(\"build/alt_bn128_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, altBn128ApiContract, ali };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"test_alt_bn128_g1_sum\", async (t) => {\n  const { ali, altBn128ApiContract } = t.context.accounts;\n  let r = await ali.callRaw(altBn128ApiContract, \"test_alt_bn128_g1_sum\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      11, 49, 94, 29, 152, 111, 116, 138, 248, 2, 184, 8, 159, 80, 169, 45, 149,\n      48, 32, 49, 37, 6, 133, 105, 171, 194, 120, 44, 195, 17, 180, 35, 137,\n      154, 4, 192, 211, 244, 93, 200, 2, 44, 0, 64, 26, 108, 139, 147, 88, 235,\n      242, 23, 253, 52, 110, 236, 67, 99, 176, 2, 186, 198, 228, 25,\n    ])\n  );\n});\n\ntest(\"test_alt_bn128_g1_multiexp\", async (t) => {\n  const { ali, altBn128ApiContract } = t.context.accounts;\n  let r = await ali.callRaw(\n    altBn128ApiContract,\n    \"test_alt_bn128_g1_multiexp\",\n    \"\"\n  );\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      150, 94, 159, 52, 239, 226, 181, 150, 77, 86, 90, 186, 102, 219, 243, 204,\n      36, 128, 164, 209, 106, 6, 62, 124, 235, 104, 223, 195, 30, 204, 42, 20,\n      13, 158, 14, 197, 133, 73, 43, 171, 28, 68, 82, 116, 244, 164, 36, 251,\n      244, 8, 234, 40, 118, 55, 216, 187, 242, 39, 213, 160, 192, 184, 28, 23,\n    ])\n  );\n});\n\ntest(\"test_alt_bn128_pairing_check\", async (t) => {\n  const { ali, altBn128ApiContract } = t.context.accounts;\n  let r = await ali.call(\n    altBn128ApiContract,\n    \"test_alt_bn128_pairing_check_valid\",\n    {}\n  );\n  t.is(r, true);\n\n  r = await ali.call(\n    altBn128ApiContract,\n    \"test_alt_bn128_pairing_check_invalid\",\n    {}\n  );\n  t.is(r, false);\n});\n"
  },
  {
    "path": "tests/__tests__/test_context_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const contextApiContract = await root.devDeploy(\"build/context_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, contextApiContract, ali, bob, carl };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"get current account id correct\", async (t) => {\n  const { ali, contextApiContract } = t.context.accounts;\n  let r = await ali.call(contextApiContract, \"get_current_account_id\", \"\");\n  t.is(r, contextApiContract.accountId);\n});\n\ntest(\"get signer account id correct\", async (t) => {\n  const { ali, contextApiContract } = t.context.accounts;\n  let r = await ali.call(contextApiContract, \"get_signer_account_id\", \"\");\n  t.is(r, ali.accountId);\n});\n\ntest(\"get predecessor account id correct\", async (t) => {\n  const { ali, contextApiContract } = t.context.accounts;\n  let r = await ali.call(contextApiContract, \"get_predecessor_account_id\", \"\");\n  t.is(r, ali.accountId);\n});\n\ntest(\"get signer account pk correct\", async (t) => {\n  const { ali, contextApiContract } = t.context.accounts;\n  let r = await ali.callRaw(contextApiContract, \"get_signer_account_pk\", \"\");\n  // the prefixing byte 0 indicates it's a ED25519 PublicKey, see how PublicKey is serialized in nearcore\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.concat([\n      Buffer.from([0]),\n      Buffer.from((await ali.getKey(ali.accountId)).getPublicKey().data),\n    ])\n  );\n});\n\ntest(\"get input correct\", async (t) => {\n  const { bob, contextApiContract } = t.context.accounts;\n  let r = await bob.callRaw(\n    contextApiContract,\n    \"get_input\",\n    new Uint8Array([0, 1, 255])\n  );\n  t.is(\n    r.result.status.SuccessValue,\n    Buffer.from(new Uint8Array([0, 1, 255])).toString(\"base64\")\n  );\n});\n\ntest(\"get storage usage\", async (t) => {\n  const { carl, contextApiContract } = t.context.accounts;\n  let r = await carl.call(contextApiContract, \"get_storage_usage\", \"\", {\n    gas: \"10 TGas\",\n  });\n  t.is(r > 0, true);\n});\n\ntest(\"get block height\", async (t) => {\n  const { bob, contextApiContract } = t.context.accounts;\n  let r = await bob.call(contextApiContract, \"get_block_height\", \"\");\n  t.is(r > 0, true);\n});\n\ntest(\"get block timestamp\", async (t) => {\n  let time = new Date().getTime() * 1e6;\n  const { bob, contextApiContract } = t.context.accounts;\n  let r = await bob.call(contextApiContract, \"get_block_timestamp\", \"\");\n  t.is(r > time, true);\n});\n\ntest(\"get epoch height\", async (t) => {\n  const { bob, contextApiContract } = t.context.accounts;\n  let r = await bob.call(contextApiContract, \"get_epoch_height\", \"\");\n  t.is(r, 1);\n});\n\ntest(\"get attached deposit\", async (t) => {\n  const { carl, contextApiContract } = t.context.accounts;\n  let r = await carl.call(contextApiContract, \"get_attached_deposit\", \"\", {\n    attachedDeposit: 3,\n  });\n  t.is(r, \"3\");\n\n  for (let i = 1; i <= 10; i++) {\n    // 1 NEAR, 2 NEAR, ..., 10 NEAR\n    let r = await carl.call(\n      contextApiContract,\n      \"get_attached_deposit\",\n      {},\n      { attachedDeposit: i.toString() + \"000000000000000000000000\" }\n    );\n    t.is(r, i.toString() + \"000000000000000000000000\");\n  }\n});\n\ntest(\"get prepaid gas\", async (t) => {\n  const { carl, contextApiContract } = t.context.accounts;\n  let r = await carl.call(contextApiContract, \"get_prepaid_gas\", \"\", {\n    gas: \"10 TGas\",\n  });\n  t.is(r, 10000000000000);\n});\n\ntest(\"get used gas\", async (t) => {\n  const { carl, contextApiContract } = t.context.accounts;\n  let r = await carl.call(contextApiContract, \"get_used_gas\", \"\", {\n    gas: \"10 TGas\",\n  });\n  t.is(r > 0, true);\n  t.is(r < 10000000000000, true);\n});\n\ntest(\"get random seed\", async (t) => {\n  const { carl, contextApiContract } = t.context.accounts;\n  let r = await carl.callRaw(contextApiContract, \"get_random_seed\", \"\");\n  t.is(Buffer.from(r.result.status.SuccessValue, \"base64\").length, 32);\n});\n\ntest(\"get validator stake test\", async (t) => {\n  const { carl, contextApiContract, root } = t.context.accounts;\n  let r = await carl.call(contextApiContract, \"get_validator_stake\", \"\");\n  t.is(r, 0);\n  r = await root.callRaw(contextApiContract, \"get_validator_stake\", \"\");\n  t.is(\n    Buffer.from(r.result.status.SuccessValue, \"base64\").toString(\"ascii\"),\n    \"50000000000000000000000000000000\"\n  );\n  r = await contextApiContract.viewRaw(\"get_total_stake\", \"\");\n  t.is(\n    Buffer.from(r.result).toString(\"ascii\"),\n    \"50000000000000000000000000000000\"\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/test_highlevel_promise.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  const highlevelPromise = await root.createSubAccount(\"highlevel-promise\", {\n    initialBalance: \"100100N\",\n  });\n  await highlevelPromise.deploy(\"build/highlevel-promise.wasm\");\n\n  // Create and deploy callee contract\n  const calleeContract = await root.createSubAccount(\"callee-contract\");\n  await calleeContract.deploy(\"build/promise_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    highlevelPromise,\n    ali,\n    bob,\n    carl,\n    calleeContract,\n  };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"highlevel promise create account, transfer\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n\n  let r = await bob.callRaw(\n    highlevelPromise,\n    \"test_promise_batch_create_transfer\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    highlevelPromise.getSubAccount(\"a\").accountId\n  );\n  t.is(r.result.receipts_outcome[1].outcome.status.SuccessValue, \"\");\n\n  let balance = await highlevelPromise.getSubAccount(\"a\").balance();\n  t.is(balance.total.toString(), \"10000000000000000000000000\");\n});\n\ntest(\"highlevel promise stake\", async (t) => {\n  const { highlevelPromise } = t.context.accounts;\n  await highlevelPromise.callRaw(\n    highlevelPromise,\n    \"test_promise_batch_stake\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  let balance = await highlevelPromise.balance();\n  t.is(balance.staked.toString(), \"100000000000000000000000000000\");\n});\n\ntest(\"highlevel promise add full access key\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n  let r = await bob.callRaw(\n    highlevelPromise,\n    \"test_promise_add_full_access_key\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"highlevel promise add function call key\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n  let r = await bob.callRaw(\n    highlevelPromise,\n    \"test_promise_add_function_call_access_key\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"highlevel promise delete account\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n  let r = await bob.callRaw(highlevelPromise, \"test_delete_account\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  t.is(r.result.status.SuccessValue, \"\");\n  t.is(await highlevelPromise.getSubAccount(\"e\").exists(), false);\n});\n\ntest(\"cross contract call panic\", async (t) => {\n  const { ali, highlevelPromise } = t.context.accounts;\n  let r = await ali.callRaw(highlevelPromise, \"callee_panic\", \"\", {\n    gas: \"70 Tgas\",\n  });\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Smart contract panicked: it just panic\"\n    )\n  );\n});\n\ntest(\"before and after cross contract call panic\", async (t) => {\n  const { carl, highlevelPromise } = t.context.accounts;\n  let r = await carl.callRaw(\n    highlevelPromise,\n    \"before_and_after_callee_panic\",\n    \"\",\n    {\n      gas: \"70 Tgas\",\n    }\n  );\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Smart contract panicked: it just panic\"\n    )\n  );\n  // full transaction is revert, no log\n  t.deepEqual(r.result.transaction_outcome.outcome.logs, []);\n});\n\ntest(\"cross contract call panic then callback another contract method\", async (t) => {\n  const { carl, highlevelPromise } = t.context.accounts;\n  let r = await carl.callRaw(highlevelPromise, \"callee_panic_then\", \"\", {\n    gas: \"70 Tgas\",\n  });\n  // promise then will continue, even though the promise before promise.then failed\n  t.is(r.result.status.SuccessValue, \"\");\n  let state = await highlevelPromise.viewStateRaw();\n  t.is(state.length, 4);\n});\n\ntest(\"cross contract call panic and cross contract call success then callback another contract method\", async (t) => {\n  const { carl, highlevelPromise, calleeContract } = t.context.accounts;\n  let r = await carl.callRaw(highlevelPromise, \"callee_panic_and\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  // promise `and` promise `then` continues, even though one of two promise and was failed. Entire transaction also success\n  t.is(r.result.status.SuccessValue, \"\");\n  let state = await calleeContract.viewStateRaw();\n  t.is(state.length, 3);\n  state = await highlevelPromise.viewStateRaw();\n  t.is(state.length, 4);\n});\n\ntest(\"cross contract call success then call a panic method\", async (t) => {\n  const { carl, highlevelPromise, calleeContract } = t.context.accounts;\n  let r = await carl.callRaw(\n    highlevelPromise,\n    \"callee_success_then_panic\",\n    \"\",\n    {\n      gas: \"100 Tgas\",\n    }\n  );\n  // the last promise fail, cause the transaction fail\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"Smart contract panicked: it just panic\"\n    )\n  );\n  // but the first success cross contract call won't revert, the state is persisted\n  let state = await calleeContract.viewStateRaw();\n  t.is(state.length, 3);\n});\n\ntest(\"handling error in promise then\", async (t) => {\n  const { carl, highlevelPromise } = t.context.accounts;\n  let r = await carl.callRaw(\n    highlevelPromise,\n    \"handle_error_in_promise_then\",\n    \"\",\n    {\n      gas: \"70 Tgas\",\n    }\n  );\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"caught error in the callback: \"\n    )\n  );\n});\n\ntest(\"handling error in promise then after promise and\", async (t) => {\n  const { carl, highlevelPromise } = t.context.accounts;\n  let r = await carl.callRaw(\n    highlevelPromise,\n    \"handle_error_in_promise_then_after_promise_and\",\n    \"\",\n    {\n      gas: \"100 Tgas\",\n    }\n  );\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.includes(\n      \"caught error in the callback: \"\n    )\n  );\n});\n\ntest(\"highlevel promise then\", async (t) => {\n  const { ali, highlevelPromise, calleeContract } = t.context.accounts;\n  let r = await ali.callRaw(highlevelPromise, \"test_promise_then\", \"\", {\n    gas: \"70 Tgas\",\n  });\n  // call the callee\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[1].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: highlevelPromise.accountId,\n      input: \"abc\",\n    }\n  );\n\n  // the callback scheduled by promise_then\n  t.is(\n    r.result.receipts_outcome[3].outcome.executor_id,\n    highlevelPromise.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[3].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: highlevelPromise.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: highlevelPromise.accountId,\n      input: '{\"callbackArg1\":\"def\"}',\n      promiseResults: [\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: highlevelPromise.accountId,\n          input: \"abc\",\n        }),\n      ],\n      callbackArg1: \"def\",\n    }\n  );\n});\n\ntest(\"highlevel promise and\", async (t) => {\n  const { ali, highlevelPromise, calleeContract } = t.context.accounts;\n  let r = await ali.callRaw(highlevelPromise, \"test_promise_and\", \"\", {\n    gas: \"150 Tgas\",\n  });\n\n  // console.log(JSON.stringify(r, null, 2))\n  // promise and schedule to call the callee\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[1].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: highlevelPromise.accountId,\n      input: \"abc\",\n    }\n  );\n\n  // promise and schedule to call the callee, with different args\n  t.is(\n    r.result.receipts_outcome[3].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[3].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: highlevelPromise.accountId,\n      input: \"def\",\n    }\n  );\n\n  // the callback scheduled by promise_then on the promise created by promise_and\n  t.is(\n    r.result.receipts_outcome[5].outcome.executor_id,\n    highlevelPromise.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[5].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: highlevelPromise.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: highlevelPromise.accountId,\n      input: '{\"callbackArg1\":\"ghi\"}',\n      promiseResults: [\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: highlevelPromise.accountId,\n          input: \"abc\",\n        }),\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: highlevelPromise.accountId,\n          input: \"def\",\n        }),\n      ],\n      callbackArg1: \"ghi\",\n    }\n  );\n});\n\ntest(\"highlevel promise not build and not return\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n\n  let r = await bob.callRaw(highlevelPromise, \"not_return_not_build\", \"\", {\n    gas: \"100 Tgas\",\n  });\n\n  try {\n    let balance = await highlevelPromise.getSubAccount(\"b\").balance();\n  } catch (e) {\n    t.is(e.type, \"AccountDoesNotExist\");\n  }\n});\n\ntest(\"highlevel promise build and not return\", async (t) => {\n  const { bob, highlevelPromise } = t.context.accounts;\n\n  let r = await bob.callRaw(highlevelPromise, \"build_not_return\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    highlevelPromise.getSubAccount(\"b\").accountId\n  );\n  t.is(r.result.receipts_outcome[1].outcome.status.SuccessValue, \"\");\n\n  let balance = await highlevelPromise.getSubAccount(\"b\").balance();\n  t.is(balance.total.toString(), \"10000000000000000000000000\");\n});\n"
  },
  {
    "path": "tests/__tests__/test_log_panic_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const testContract = await root.devDeploy(\"build/log_panic_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, testContract, ali };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Log expected types work\", async (t) => {\n  const { ali, testContract } = t.context.accounts;\n\n  let r = await ali.callRaw(testContract, \"log_expected_input_tests\", \"\");\n  t.deepEqual(r.result.receipts_outcome[0].outcome.logs, [\n    \"abc\",\n    \"水\",\n    \"333\",\n    '{\"0\":0,\"1\":1,\"2\":255}',\n    '{\"0\":230,\"1\":176,\"2\":180}',\n    \"水\",\n    \"水\",\n  ]);\n});\n\ntest(\"Log invalid utf-8 sequence panic\", async (t) => {\n  const { ali, testContract } = t.context.accounts;\n\n  let r = await ali.callRaw(testContract, \"log_invalid_utf8_sequence_test\", \"\");\n  // console.log(JSON.stringify(r, null, 2))\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-8 sequence.\"\n  );\n});\n\ntest(\"Log invalid utf-16 sequence panic\", async (t) => {\n  const { ali, testContract } = t.context.accounts;\n\n  let r = await ali.callRaw(\n    testContract,\n    \"log_invalid_utf16_sequence_test\",\n    \"\"\n  );\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-16 sequence.\"\n  );\n});\n\ntest(\"panic tests\", async (t) => {\n  const { ali, testContract } = t.context.accounts;\n  let r = await ali.callRaw(testContract, \"panic_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /^Smart contract panicked:*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panic_ascii_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /^Smart contract panicked: abc*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panic_js_number\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /^Smart contract panicked: 356*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panic_js_undefined\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /^Smart contract panicked:*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panic_js_null\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /^Smart contract panicked: null*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panic_utf8_test\", \"\");\n  t.assert(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.match(\n      /Smart contract panicked: 水*/\n    )\n  );\n\n  r = await ali.callRaw(testContract, \"panicUtf8_valid_utf8_sequence\", \"\");\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"Smart contract panicked: 水\"\n  );\n\n  r = await ali.callRaw(testContract, \"panicUtf8_invalid_utf8_sequence\", \"\");\n  t.deepEqual(\n    r.result.receipts_outcome[0].outcome.status.Failure.ActionError.kind\n      .FunctionCallError.ExecutionError,\n    \"String encoding is bad UTF-8 sequence.\"\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/test_math_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const mathApiContract = await root.devDeploy(\"build/math_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, mathApiContract, ali };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"sha256\", async (t) => {\n  const { ali, mathApiContract } = t.context.accounts;\n  let r = await ali.callRaw(mathApiContract, \"test_sha256\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      18, 176, 115, 156, 45, 100, 241, 132, 180, 134, 77, 42, 105, 111, 199,\n      127, 118, 112, 92, 255, 88, 43, 83, 147, 122, 55, 26, 36, 42, 156, 160,\n      158,\n    ])\n  );\n});\n\ntest(\"keccak256\", async (t) => {\n  const { ali, mathApiContract } = t.context.accounts;\n  let r = await ali.callRaw(mathApiContract, \"test_keccak256\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      104, 110, 58, 122, 230, 181, 215, 145, 231, 229, 49, 162, 123, 167, 177,\n      58, 26, 142, 129, 173, 7, 37, 9, 26, 233, 115, 64, 102, 61, 85, 10, 159,\n    ])\n  );\n});\n\ntest(\"keccak512\", async (t) => {\n  const { ali, mathApiContract } = t.context.accounts;\n  let r = await ali.callRaw(mathApiContract, \"test_keccak512\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      55, 134, 96, 137, 168, 122, 187, 95, 67, 76, 18, 122, 146, 11, 225, 106,\n      117, 194, 154, 157, 48, 160, 90, 146, 104, 209, 118, 126, 222, 230, 200,\n      125, 48, 73, 197, 236, 123, 173, 192, 197, 90, 153, 167, 121, 100, 88,\n      209, 240, 137, 86, 239, 41, 87, 128, 219, 249, 136, 203, 220, 109, 46,\n      168, 234, 190,\n    ])\n  );\n});\n\ntest(\"ripemd160\", async (t) => {\n  const { ali, mathApiContract } = t.context.accounts;\n  let r = await ali.callRaw(mathApiContract, \"test_ripemd160\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      21, 102, 156, 115, 232, 3, 58, 215, 35, 84, 129, 30, 143, 86, 212, 104,\n      70, 97, 14, 225,\n    ])\n  );\n});\n\ntest(\"ecrecover\", async (t) => {\n  const { ali, mathApiContract } = t.context.accounts;\n  let r = await ali.callRaw(mathApiContract, \"test_ecrecover\", \"\");\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([\n      227, 45, 244, 40, 101, 233, 113, 53, 172, 251, 101, 243, 186, 231, 27,\n      220, 134, 244, 212, 145, 80, 173, 106, 68, 11, 111, 21, 135, 129, 9, 136,\n      10, 10, 43, 38, 103, 247, 231, 37, 206, 234, 112, 198, 115, 9, 59, 246,\n      118, 99, 224, 49, 38, 35, 200, 224, 145, 177, 60, 242, 192, 241, 30, 246,\n      82,\n    ])\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/test_promise_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Create and deploy caller contract\n  const callerContract = await root.createSubAccount(\"caller-contract\");\n  await callerContract.deploy(\"build/promise_api.wasm\");\n\n  // Create and deploy callee contract\n  const calleeContract = await root.createSubAccount(\"callee-contract\");\n  await calleeContract.deploy(\"build/promise_api.wasm\");\n\n  // Create and deploy caller2 contract\n  const caller2Contract = await root.createSubAccount(\"caller2\", {\n    initialBalance: \"100100N\",\n  });\n  await caller2Contract.deploy(\"build/promise_batch_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = {\n    root,\n    callerContract,\n    calleeContract,\n    ali,\n    bob,\n    caller2Contract,\n  };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"promise create\", async (t) => {\n  const { ali, callerContract, calleeContract } = t.context.accounts;\n  // default is 30 TGas, sufficient when the callee contract method is trivial\n  let r = await ali.callRaw(callerContract, \"test_promise_create\", \"\", {\n    gas: \"40 Tgas\",\n  });\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    Buffer.from(\n      r.result.receipts_outcome[1].outcome.status.SuccessValue,\n      \"base64\"\n    ),\n    Buffer.from(\n      JSON.stringify({\n        currentAccountId: calleeContract.accountId,\n        signerAccountId: ali.accountId,\n        predecessorAccountId: callerContract.accountId,\n        input: \"abc\",\n      })\n    )\n  );\n});\n\ntest(\"promise then\", async (t) => {\n  const { ali, callerContract, calleeContract } = t.context.accounts;\n  let r = await ali.callRaw(callerContract, \"test_promise_then\", \"\", {\n    gas: \"70 Tgas\",\n  });\n  // console.log(JSON.stringify(r, null, 2))\n  // call the callee\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[1].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: callerContract.accountId,\n      input: \"abc\",\n    }\n  );\n\n  // the callback scheduled by promise_then\n  t.is(\n    r.result.receipts_outcome[3].outcome.executor_id,\n    callerContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[3].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: callerContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: callerContract.accountId,\n      input: \"def\",\n      promiseResults: [\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: callerContract.accountId,\n          input: \"abc\",\n        }),\n      ],\n    }\n  );\n});\n\ntest(\"promise and\", async (t) => {\n  const { ali, callerContract, calleeContract } = t.context.accounts;\n  let r = await ali.callRaw(callerContract, \"test_promise_and\", \"\", {\n    gas: \"150 Tgas\",\n  });\n  // console.log(JSON.stringify(r, null, 2))\n  // promise and schedule to call the callee\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[1].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: callerContract.accountId,\n      input: \"abc\",\n    }\n  );\n\n  // promise and schedule to call the callee, with different args\n  t.is(\n    r.result.receipts_outcome[3].outcome.executor_id,\n    calleeContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[3].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: calleeContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: callerContract.accountId,\n      input: \"def\",\n    }\n  );\n\n  // the callback scheduled by promise_then on the promise created by promise_and\n  t.is(\n    r.result.receipts_outcome[5].outcome.executor_id,\n    callerContract.accountId\n  );\n  t.deepEqual(\n    JSON.parse(\n      Buffer.from(\n        r.result.receipts_outcome[5].outcome.status.SuccessValue,\n        \"base64\"\n      )\n    ),\n    {\n      currentAccountId: callerContract.accountId,\n      signerAccountId: ali.accountId,\n      predecessorAccountId: callerContract.accountId,\n      input: \"ghi\",\n      promiseResults: [\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: callerContract.accountId,\n          input: \"abc\",\n        }),\n        JSON.stringify({\n          currentAccountId: calleeContract.accountId,\n          signerAccountId: ali.accountId,\n          predecessorAccountId: callerContract.accountId,\n          input: \"def\",\n        }),\n      ],\n    }\n  );\n});\n\ntest(\"promise batch create account, transfer\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n\n  let r = await bob.callRaw(\n    caller2Contract,\n    \"test_promise_batch_create_transfer\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(\n    r.result.receipts_outcome[1].outcome.executor_id,\n    caller2Contract.getSubAccount(\"a\").accountId\n  );\n  t.is(r.result.receipts_outcome[1].outcome.status.SuccessValue, \"\");\n\n  let balance = await caller2Contract.getSubAccount(\"a\").balance();\n  t.is(balance.total.toString(), \"10000000000000000000000000\");\n});\n\ntest(\"promise batch deploy contract and call\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n\n  let r = await bob.callRaw(\n    caller2Contract,\n    \"test_promise_batch_deploy_call\",\n    \"\",\n    { gas: \"300 Tgas\" }\n  );\n\n  let deployed = caller2Contract.getSubAccount(\"b\");\n  t.deepEqual(JSON.parse(Buffer.from(r.result.status.SuccessValue, \"base64\")), {\n    currentAccountId: deployed.accountId,\n    signerAccountId: bob.accountId,\n    predecessorAccountId: caller2Contract.accountId,\n    input: \"abc\",\n  });\n});\n\ntest(\"promise batch stake\", async (t) => {\n  const { caller2Contract } = t.context.accounts;\n  await caller2Contract.callRaw(\n    caller2Contract,\n    \"test_promise_batch_stake\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  let balance = await caller2Contract.balance();\n  t.is(balance.staked.toString(), \"100000000000000000000000000000\");\n});\n\ntest(\"promise batch add full access key\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n  let r = await bob.callRaw(\n    caller2Contract,\n    \"test_promise_add_full_access_key\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"promise batch add function call key\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n  let r = await bob.callRaw(\n    caller2Contract,\n    \"test_promise_add_function_call_access_key\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.is(r.result.status.SuccessValue, \"\");\n});\n\ntest(\"promise delete account\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n  let r = await bob.callRaw(caller2Contract, \"test_delete_account\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  t.is(r.result.status.SuccessValue, \"\");\n  t.is(await caller2Contract.getSubAccount(\"e\").exists(), false);\n});\n\ntest(\"promise batch function call weight\", async (t) => {\n  const { ali, caller2Contract } = t.context.accounts;\n  let r = await ali.callRaw(\n    caller2Contract,\n    \"test_promise_batch_call_weight\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.assert(r.result.status.SuccessValue);\n});\n\ntest(\"promise batch transfer overflow\", async (t) => {\n  const { bob, caller2Contract } = t.context.accounts;\n  let r = await bob.callRaw(caller2Contract, \"test_transfer_overflow\", \"\", {\n    gas: \"100 Tgas\",\n  });\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Expect Uint128 for amount\"\n    )\n  );\n});\n\ntest(\"promise create gas overflow\", async (t) => {\n  const { ali, callerContract } = t.context.accounts;\n  let r = await ali.callRaw(\n    callerContract,\n    \"test_promise_create_gas_overflow\",\n    \"\",\n    { gas: \"100 Tgas\" }\n  );\n  t.assert(\n    r.result.status.Failure.ActionError.kind.FunctionCallError.ExecutionError.startsWith(\n      \"Smart contract panicked: Expect Uint64 for gas\"\n    )\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/test_storage_api.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Use beforeEach instead of before to start from scratch state for each test\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const storageApiContract = await root.devDeploy(\"build/storage_api.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, storageApiContract, ali };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"storage read write\", async (t) => {\n  const { ali, storageApiContract } = t.context.accounts;\n\n  let exist = await ali.call(storageApiContract, \"test_storage_write\", \"\");\n  t.is(exist, false);\n  let r = await storageApiContract.viewRaw(\"test_storage_read\", \"\");\n  t.deepEqual(r.result, [0, 1, 255]);\n  exist = await ali.call(storageApiContract, \"test_storage_write\", \"\");\n  t.is(exist, true);\n});\n\ntest(\"storage remove\", async (t) => {\n  const { ali, storageApiContract } = t.context.accounts;\n  let hasKey = await storageApiContract.view(\"test_storage_has_key\", \"\");\n  t.is(hasKey, false);\n  let exist = await ali.call(storageApiContract, \"test_storage_remove\", \"\");\n  t.is(exist, false);\n\n  await ali.call(storageApiContract, \"test_storage_write\", \"\");\n\n  hasKey = await storageApiContract.view(\"test_storage_has_key\", \"\");\n  t.is(hasKey, true);\n  exist = await ali.call(storageApiContract, \"test_storage_remove\", \"\");\n  t.is(exist, true);\n});\n\ntest(\"storage get evicted\", async (t) => {\n  const { ali, storageApiContract } = t.context.accounts;\n\n  let r = await ali.callRaw(storageApiContract, \"test_storage_get_evicted\", \"\");\n  console.log(JSON.stringify(r, null, 2));\n  t.deepEqual(\n    Buffer.from(r.result.status.SuccessValue, \"base64\"),\n    Buffer.from([0, 1, 255])\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/typescript.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.before(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const typescriptContract = await root.devDeploy(\"build/typescript.wasm\");\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, typescriptContract, ali };\n});\n\ntest.after.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"bigint\", async (t) => {\n  const { typescriptContract } = t.context.accounts;\n  let r = await typescriptContract.view(\"bigint\", \"\");\n  t.is(r, \"3\");\n});\n"
  },
  {
    "path": "tests/__tests__/unordered-map.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const unorderedMapContract = await root.createSubAccount(\n    \"unordered-map-contract\"\n  );\n  await unorderedMapContract.deploy(\"build/unordered-map.wasm\");\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, unorderedMapContract, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"UnorderedMap is empty by default\", async (t) => {\n  const { unorderedMapContract } = t.context.accounts;\n  const result = await unorderedMapContract.view(\"len\", {});\n  t.is(result, 0);\n});\n\ntest(\"UnorderedMap set() get()\", async (t) => {\n  const { ali, unorderedMapContract } = t.context.accounts;\n  t.is(await unorderedMapContract.view(\"get\", { key: \"hello\" }), null);\n\n  await ali.call(unorderedMapContract, \"set\", { key: \"hello\", value: \"world\" });\n\n  t.is(await unorderedMapContract.view(\"get\", { key: \"hello\" }), \"world\");\n});\n\ntest(\"UnorderedMap insert, update, len and iterate\", async (t) => {\n  const { ali, unorderedMapContract } = t.context.accounts;\n\n  t.is(await unorderedMapContract.view(\"len\", {}), 0);\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), []);\n\n  await ali.call(unorderedMapContract, \"set\", { key: \"hello\", value: \"world\" });\n  await ali.call(unorderedMapContract, \"set\", {\n    key: \"hello1\",\n    value: \"world0\",\n  });\n  t.is(await unorderedMapContract.view(\"len\", {}), 2);\n\n  // update a value, len shouldn't change\n  await ali.call(unorderedMapContract, \"set\", {\n    key: \"hello1\",\n    value: \"world1\",\n  });\n  t.is(await unorderedMapContract.view(\"len\", {}), 2);\n  // update should have effect\n  t.is(await unorderedMapContract.view(\"get\", { key: \"hello1\" }), \"world1\");\n\n  await ali.call(unorderedMapContract, \"set\", {\n    key: \"hello2\",\n    value: \"world2\",\n  });\n  t.is(await unorderedMapContract.view(\"len\", {}), 3);\n\n  // Try to set a key with same value, len shouldn't change\n  await ali.call(unorderedMapContract, \"set\", {\n    key: \"hello2\",\n    value: \"world2\",\n  });\n  t.is(await unorderedMapContract.view(\"len\", {}), 3);\n\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), [\n    [\"hello\", \"world\"],\n    [\"hello1\", \"world1\"],\n    [\"hello2\", \"world2\"],\n  ]);\n});\n\ntest(\"UnorderedMap extend, remove, clear\", async (t) => {\n  const { ali, unorderedMapContract } = t.context.accounts;\n\n  await ali.call(unorderedMapContract, \"extend\", {\n    kvs: [\n      [\"hello\", \"world\"],\n      [\"hello1\", \"world1\"],\n      [\"hello2\", \"world2\"],\n    ],\n  });\n\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), [\n    [\"hello\", \"world\"],\n    [\"hello1\", \"world1\"],\n    [\"hello2\", \"world2\"],\n  ]);\n\n  // remove non existing element should not error\n  await ali.call(unorderedMapContract, \"remove_key\", { key: \"hello3\" });\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), [\n    [\"hello\", \"world\"],\n    [\"hello1\", \"world1\"],\n    [\"hello2\", \"world2\"],\n  ]);\n\n  // remove not the last one should work\n  await ali.call(unorderedMapContract, \"remove_key\", { key: \"hello\" });\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), [\n    [\"hello2\", \"world2\"],\n    [\"hello1\", \"world1\"],\n  ]);\n\n  // remove the last one should work\n  await ali.call(unorderedMapContract, \"remove_key\", { key: \"hello1\" });\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), [\n    [\"hello2\", \"world2\"],\n  ]);\n\n  // remove when length is 1 should work\n  t.is(await unorderedMapContract.view(\"len\", {}), 1);\n  t.is(await unorderedMapContract.view(\"isEmpty\", {}), false);\n  await ali.call(unorderedMapContract, \"remove_key\", { key: \"hello2\" });\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), []);\n  t.is(await unorderedMapContract.view(\"isEmpty\", {}), true);\n\n  await ali.call(unorderedMapContract, \"extend\", {\n    kvs: [\n      [\"hello\", \"world\"],\n      [\"hello1\", \"world1\"],\n      [\"hello2\", \"world2\"],\n    ],\n  });\n  t.is(await unorderedMapContract.view(\"isEmpty\", {}), false);\n  await ali.call(unorderedMapContract, \"clear\", {});\n\n  t.deepEqual(await unorderedMapContract.view(\"toArray\", {}), []);\n  t.is(await unorderedMapContract.view(\"isEmpty\", {}), true);\n});\n\ntest(\"UnorderedMap set get object\", async (t) => {\n  const { ali, unorderedMapContract } = t.context.accounts;\n  await ali.call(unorderedMapContract, \"add_house\", {});\n  t.is(\n    await unorderedMapContract.view(\"get_house\", {}),\n    \"house house1 has 2 rooms. room room1 is 200sqft.\"\n  );\n});\n\ntest(\"UnorderedMap enumeration and pagination of keys\", async (t) => {\n  const { bob, unorderedMapContract } = t.context.accounts;\n  await bob.call(unorderedMapContract, \"extend\", {\n    kvs: [\n      [\"aaa\", \"world\"],\n      [\"bbb\", \"world1\"],\n      [\"ccc\", \"world2\"],\n      [\"ddd\", \"world3\"],\n    ],\n  });\n\n  t.deepEqual(await unorderedMapContract.view(\"keys\", {}), [\n    \"aaa\",\n    \"bbb\",\n    \"ccc\",\n    \"ddd\",\n  ]);\n\n  t.deepEqual(await unorderedMapContract.view(\"keys\", { start: 1 }), [\n    \"bbb\",\n    \"ccc\",\n    \"ddd\",\n  ]);\n\n  t.deepEqual(await unorderedMapContract.view(\"keys\", { limit: 2 }), [\n    \"aaa\",\n    \"bbb\",\n  ]);\n\n  t.deepEqual(await unorderedMapContract.view(\"keys\", { start: 1, limit: 2 }), [\n    \"bbb\",\n    \"ccc\",\n  ]);\n});\n"
  },
  {
    "path": "tests/__tests__/unordered-set.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const unorderedSetContract = await root.createSubAccount(\n    \"unordered-set-contract\"\n  );\n  await unorderedSetContract.deploy(\"build/unordered-set.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, unorderedSetContract, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"UnorderedSet is empty by default\", async (t) => {\n  const { unorderedSetContract } = t.context.accounts;\n  const result = await unorderedSetContract.view(\"len\", {});\n  t.is(result, 0);\n  t.is(await unorderedSetContract.view(\"isEmpty\", {}), true);\n});\n\ntest(\"UnorderedSet set() contains()\", async (t) => {\n  const { ali, unorderedSetContract } = t.context.accounts;\n  t.is(\n    await unorderedSetContract.view(\"contains\", { element: \"hello\" }),\n    false\n  );\n\n  await ali.call(unorderedSetContract, \"set\", { element: \"hello\" });\n\n  t.is(await unorderedSetContract.view(\"contains\", { element: \"hello\" }), true);\n});\n\ntest(\"UnorderedSet insert, len and iterate\", async (t) => {\n  const { ali, unorderedSetContract } = t.context.accounts;\n\n  t.is(await unorderedSetContract.view(\"len\", {}), 0);\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), []);\n\n  await ali.call(unorderedSetContract, \"set\", { element: \"hello\" });\n  t.is(await unorderedSetContract.view(\"len\", {}), 1);\n  await ali.call(unorderedSetContract, \"set\", { element: \"hello1\" });\n  t.is(await unorderedSetContract.view(\"len\", {}), 2);\n\n  // insert the same value, len shouldn't change\n  await ali.call(unorderedSetContract, \"set\", { element: \"hello1\" });\n  t.is(await unorderedSetContract.view(\"len\", {}), 2);\n\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"hello1\",\n  ]);\n});\n\ntest(\"UnorderedSet extend, remove, clear\", async (t) => {\n  const { ali, unorderedSetContract } = t.context.accounts;\n\n  await ali.callRaw(unorderedSetContract, \"extend\", {\n    elements: [\"hello\", \"world\", \"hello1\"],\n  });\n\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"world\",\n    \"hello1\",\n  ]);\n\n  // remove non existing element should not error\n  await ali.call(unorderedSetContract, \"remove_key\", { element: \"hello3\" });\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"world\",\n    \"hello1\",\n  ]);\n\n  // remove not the last one should work\n  await ali.call(unorderedSetContract, \"remove_key\", { element: \"hello\" });\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\n    \"hello1\",\n    \"world\",\n  ]);\n\n  // remove the last one should work\n  await ali.call(unorderedSetContract, \"remove_key\", { element: \"world\" });\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\"hello1\"]);\n\n  // remove when length is 1 should work\n  t.is(await unorderedSetContract.view(\"len\", {}), 1);\n  t.is(await unorderedSetContract.view(\"isEmpty\", {}), false);\n  await ali.call(unorderedSetContract, \"remove_key\", { element: \"hello1\" });\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), []);\n  t.is(await unorderedSetContract.view(\"isEmpty\", {}), true);\n\n  await ali.call(unorderedSetContract, \"extend\", {\n    elements: [\"hello\", \"world\", \"hello1\"],\n  });\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"world\",\n    \"hello1\",\n  ]);\n  t.is(await unorderedSetContract.view(\"isEmpty\", {}), false);\n  // clear should work\n  await ali.call(unorderedSetContract, \"clear\", {});\n  t.deepEqual(await unorderedSetContract.view(\"toArray\", {}), []);\n  t.is(await unorderedSetContract.view(\"isEmpty\", {}), true);\n});\n\ntest(\"Add and check exist of object\", async (t) => {\n  const { ali, unorderedSetContract } = t.context.accounts;\n  let houseSpec = { name: \"a\", rooms: [{ name: \"bedroom\", size: \"300sqft\" }] };\n  t.is(await unorderedSetContract.view(\"house_exist\", houseSpec), false);\n  await ali.call(unorderedSetContract, \"add_house\", houseSpec);\n  t.is(await unorderedSetContract.view(\"house_exist\", houseSpec), true);\n});\n\ntest(\"Enumerate and pagination of elements\", async (t) => {\n  const { bob, unorderedSetContract } = t.context.accounts;\n\n  await bob.callRaw(unorderedSetContract, \"extend\", {\n    elements: [\"aaa\", \"bbb\", \"ccc\", \"ddd\"],\n  });\n\n  t.deepEqual(await unorderedSetContract.view(\"elements\", {}), [\n    \"aaa\",\n    \"bbb\",\n    \"ccc\",\n    \"ddd\",\n  ]);\n\n  t.deepEqual(await unorderedSetContract.view(\"elements\", { start: 1 }), [\n    \"bbb\",\n    \"ccc\",\n    \"ddd\",\n  ]);\n\n  t.deepEqual(await unorderedSetContract.view(\"elements\", { limit: 2 }), [\n    \"aaa\",\n    \"bbb\",\n  ]);\n\n  t.deepEqual(\n    await unorderedSetContract.view(\"elements\", { start: 1, limit: 2 }),\n    [\"bbb\", \"ccc\"]\n  );\n});\n"
  },
  {
    "path": "tests/__tests__/vector.ava.js",
    "content": "import { Worker } from \"near-workspaces\";\nimport test from \"ava\";\n\ntest.beforeEach(async (t) => {\n  // Init the worker and start a Sandbox server\n  const worker = await Worker.init();\n\n  // Prepare sandbox for tests, create accounts, deploy contracts, etx.\n  const root = worker.rootAccount;\n\n  // Deploy the test contract.\n  const vectorContract = await root.devDeploy(\"build/vector.wasm\");\n\n  // Test users\n  const ali = await root.createSubAccount(\"ali\");\n  const bob = await root.createSubAccount(\"bob\");\n  const carl = await root.createSubAccount(\"carl\");\n\n  // Save state for test runs\n  t.context.worker = worker;\n  t.context.accounts = { root, vectorContract, ali, bob, carl };\n});\n\ntest.afterEach.always(async (t) => {\n  await t.context.worker.tearDown().catch((error) => {\n    console.log(\"Failed to tear down the worker:\", error);\n  });\n});\n\ntest(\"Vector is empty by default\", async (t) => {\n  const { vectorContract } = t.context.accounts;\n  let result = await vectorContract.view(\"len\", {});\n  t.is(result, 0);\n  t.is(await vectorContract.view(\"isEmpty\", {}), true);\n});\n\ntest(\"Vector push, get, pop, replace\", async (t) => {\n  const { ali, vectorContract } = t.context.accounts;\n  await ali.call(vectorContract, \"push\", { value: \"hello\" });\n  await ali.call(vectorContract, \"push\", { value: \"world\" });\n  await ali.call(vectorContract, \"push\", { value: \"aaa\" });\n  let result = await vectorContract.view(\"len\", {});\n  t.is(result, 3);\n  t.is(await vectorContract.view(\"get\", { index: 0 }), \"hello\");\n  t.is(await vectorContract.view(\"get\", { index: 2 }), \"aaa\");\n  t.is(await vectorContract.view(\"get\", { index: 3 }), null);\n\n  await ali.call(vectorContract, \"pop\", {});\n  (result = await vectorContract.view(\"len\", {})), t.is(result, 2);\n  t.is(await vectorContract.view(\"get\", { index: 2 }), null);\n  t.is(await vectorContract.view(\"get\", { index: 1 }), \"world\");\n  await ali.call(vectorContract, \"replace\", { index: 1, value: \"aaa\" });\n  t.is(await vectorContract.view(\"get\", { index: 1 }), \"aaa\");\n});\n\ntest(\"Vector extend, toArray, swapRemove, clear\", async (t) => {\n  const { ali, vectorContract } = t.context.accounts;\n\n  await ali.call(vectorContract, \"extend\", { kvs: [\"hello\", \"world\", \"aaa\"] });\n\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"world\",\n    \"aaa\",\n  ]);\n\n  // swapRemove non existing element should error\n  const error1 = await t.throwsAsync(() =>\n    ali.call(vectorContract, \"swapRemove\", { index: 3 })\n  );\n  t.assert(error1.message.includes(`Index out of bounds`));\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), [\n    \"hello\",\n    \"world\",\n    \"aaa\",\n  ]);\n\n  // swapRemove not the last one should work\n  await ali.call(vectorContract, \"swapRemove\", { index: 0 });\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), [\"aaa\", \"world\"]);\n\n  // swapRemove the last one should work\n  await ali.call(vectorContract, \"swapRemove\", { index: 1 });\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), [\"aaa\"]);\n\n  // swapRemove when length is 1 should work\n  t.is(await vectorContract.view(\"len\", {}), 1);\n  t.is(await vectorContract.view(\"isEmpty\", {}), false);\n  await ali.call(vectorContract, \"swapRemove\", { index: 0 });\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), []);\n  t.is(await vectorContract.view(\"isEmpty\", {}), true);\n\n  await ali.call(vectorContract, \"extend\", { kvs: [\"hello\", \"world\", \"aaa\"] });\n  t.is(await vectorContract.view(\"isEmpty\", {}), false);\n  await ali.call(vectorContract, \"clear\", {});\n\n  t.deepEqual(await vectorContract.view(\"toArray\", {}), []);\n  t.is(await vectorContract.view(\"isEmpty\", {}), true);\n});\n\ntest(\"Vector add and get object\", async (t) => {\n  const { ali, vectorContract } = t.context.accounts;\n  await ali.call(vectorContract, \"add_house\", {});\n  let result = await vectorContract.view(\"get_house\", {});\n  t.deepEqual(result, {\n    name: \"house1\",\n    rooms: [\n      {\n        name: \"room1\",\n        size: \"200sqft\",\n      },\n      {\n        name: \"room2\",\n        size: \"300sqft\",\n      },\n    ],\n  });\n});\n"
  },
  {
    "path": "tests/ava.config.cjs",
    "content": "require(\"util\").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth\n\nmodule.exports = {\n  timeout: \"300000\",\n  files: [\"**/*.ava.js\"],\n  failWithoutAssertions: false,\n  extensions: [\"js\"],\n};\n"
  },
  {
    "path": "tests/jsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"experimentalDecorators\": true\n  },\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "tests/package.json",
    "content": "{\n  \"name\": \"tests\",\n  \"version\": \"1.0.0\",\n  \"description\": \"near-sdk-js tests\",\n  \"main\": \"index.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"run-s build:*\",\n    \"build:context-api\": \"near-sdk-js build src/context_api.js build/context_api.wasm\",\n    \"build:math-api\": \"near-sdk-js build src/math_api.js build/math_api.wasm\",\n    \"build:storage-api\": \"near-sdk-js build src/storage_api.js build/storage_api.wasm\",\n    \"build:log-panic-api\": \"near-sdk-js build src/log_panic_api.js build/log_panic_api.wasm\",\n    \"build:promise-api\": \"near-sdk-js build src/promise_api.js build/promise_api.wasm\",\n    \"build:promise-batch-api\": \"near-sdk-js build src/promise_batch_api.js build/promise_batch_api.wasm\",\n    \"build:highlevel-promise\": \"near-sdk-js build src/highlevel-promise.js build/highlevel-promise.wasm\",\n    \"build:function-params\": \"near-sdk-js build src/function-params.js build/function-params.wasm\",\n    \"build:lookup-map\": \"near-sdk-js build src/lookup-map.js build/lookup-map.wasm\",\n    \"build:lookup-set\": \"near-sdk-js build src/lookup-set.js build/lookup-set.wasm\",\n    \"build:unordered-map\": \"near-sdk-js build src/unordered-map.js build/unordered-map.wasm\",\n    \"build:unordered-set\": \"near-sdk-js build src/unordered-set.js build/unordered-set.wasm\",\n    \"build:vector\": \"near-sdk-js build src/vector.js build/vector.wasm\",\n    \"build:bytes\": \"near-sdk-js build src/bytes.js build/bytes.wasm\",\n    \"build:typescript\": \"near-sdk-js build src/typescript.ts build/typescript.wasm\",\n    \"build:public-key\": \"near-sdk-js build src/public-key.js build/public-key.wasm\",\n    \"build:near-bindgen\": \"near-sdk-js build src/decorators/require_init_true.ts build/require_init_true.wasm && near-sdk-js build src/decorators/require_init_false.ts build/require_init_false.wasm\",\n    \"build:payable\": \"near-sdk-js build src/decorators/payable.ts build/payable.wasm\",\n    \"build:private\": \"near-sdk-js build src/decorators/private.ts build/private.wasm\",\n    \"build:bigint-serialization\": \"near-sdk-js build src/bigint-serialization.ts build/bigint-serialization.wasm\",\n    \"build:date-serialization\": \"near-sdk-js build src/date-serialization.ts build/date-serialization.wasm\",\n    \"build:middlewares\": \"near-sdk-js build src/middlewares.ts build/middlewares.wasm\",\n    \"build:migrate\": \"near-sdk-js build src/migrate.ts build/migrate.wasm\",\n    \"build:alt-bn128-api\": \"near-sdk-js build src/alt_bn128_api.js build/alt_bn128_api.wasm\",\n    \"test\": \"ava\",\n    \"test:context-api\": \"ava __tests__/test_context_api.ava.js\",\n    \"test:math-api\": \"ava __tests__/test_math_api.ava.js\",\n    \"test:storage-api\": \"ava __tests__/test_storage_api.ava.js\",\n    \"test:log-panic-api\": \"ava __tests__/test_log_panic_api.ava.js\",\n    \"test:promise-api\": \"ava __tests__/test_promise_api.ava.js\",\n    \"test:highlevel-promise\": \"ava __tests__/test_highlevel_promise.ava.js\",\n    \"test:function-params\": \"ava __tests__/function-params.ava.js\",\n    \"test:lookup-map\": \"ava __tests__/lookup-map.ava.js\",\n    \"test:lookup-set\": \"ava __tests__/lookup-set.ava.js\",\n    \"test:unordered-set\": \"ava __tests__/unordered-set.ava.js\",\n    \"test:unordered-map\": \"ava __tests__/unordered-map.ava.js\",\n    \"test:vector\": \"ava __tests__/vector.ava.js\",\n    \"test:bytes\": \"ava __tests__/bytes.ava.js\",\n    \"test:typescript\": \"ava __tests__/typescript.ava.js\",\n    \"test:public-key\": \"ava __tests__/test-public-key.ava.js\",\n    \"test:near-bindgen\": \"ava __tests__/decorators/near_bindgen.ava.js\",\n    \"test:payable\": \"ava __tests__/decorators/payable.ava.js\",\n    \"test:private\": \"ava __tests__/decorators/private.ava.js\",\n    \"test:bigint-serialization\": \"ava __tests__/test-bigint-serialization.ava.js\",\n    \"test:date-serialization\": \"ava __tests__/test-date-serialization.ava.js\",\n    \"test:serialization\": \"ava __tests__/test-serialization.ava.js\",\n    \"test:constructor-validation\": \"ava __tests__/constructor_validation.ava.js\",\n    \"test:migrate\": \"ava __tests__/decorators/migrate.ava.js\",\n    \"test:middlewares\": \"ava __tests__/test-middlewares.ava.js\",\n    \"test:abi\": \"ava __tests__/abi/abi.ava.js\",\n    \"test:alt-bn128-api\": \"ava __tests__/test_alt_bn128_api.ava.js\"\n  },\n  \"author\": \"Near Inc <hello@nearprotocol.com>\",\n  \"license\": \"Apache-2.0\",\n  \"devDependencies\": {\n    \"ava\": \"4.3.3\",\n    \"near-workspaces\": \"4.0.0\",\n    \"npm-run-all\": \"4.1.5\"\n  },\n  \"dependencies\": {\n    \"typescript\": \"4.7.4\",\n    \"near-sdk-js\": \"workspace:*\"\n  }\n}\n"
  },
  {
    "path": "tests/src/alt_bn128_api.js",
    "content": "import { near, bytes } from \"near-sdk-js\";\n\n// Functions consumed by the altBn128PairingCheck tests\n\nexport function test_alt_bn128_g1_sum() {\n  // Originated from https://github.com/near/nearcore/blob/8cd095ffc98a6507ed2d2a8982a6a3e42ebc1b62/runtime/near-test-contracts/estimator-contract/src/lib.rs#L557-L720\n  let buffer = new Uint8Array([\n    0, 11, 49, 94, 29, 152, 111, 116, 138, 248, 2, 184, 8, 159, 80, 169, 45,\n    149, 48, 32, 49, 37, 6, 133, 105, 171, 194, 120, 44, 195, 17, 180, 35, 137,\n    154, 4, 192, 211, 244, 93, 200, 2, 44, 0, 64, 26, 108, 139, 147, 88, 235,\n    242, 23, 253, 52, 110, 236, 67, 99, 176, 2, 186, 198, 228, 25,\n  ]);\n  near.valueReturnRaw(near.altBn128G1Sum(buffer));\n}\n\nexport function test_alt_bn128_g1_multiexp() {\n  // Originated from https://github.com/near/nearcore/blob/8cd095ffc98a6507ed2d2a8982a6a3e42ebc1b62/runtime/near-test-contracts/estimator-contract/src/lib.rs#L557-L720\n  let buffer = new Uint8Array([\n    16, 238, 91, 161, 241, 22, 172, 158, 138, 252, 202, 212, 136, 37, 110, 231,\n    118, 220, 8, 45, 14, 153, 125, 217, 227, 87, 238, 238, 31, 138, 226, 8, 238,\n    185, 12, 155, 93, 126, 144, 248, 200, 177, 46, 245, 40, 162, 169, 80, 150,\n    211, 157, 13, 10, 36, 44, 232, 173, 32, 32, 115, 123, 2, 9, 47, 190, 148,\n    181, 91, 69, 6, 83, 40, 65, 222, 251, 70, 81, 73, 60, 142, 130, 217, 176,\n    20, 69, 75, 40, 167, 41, 180, 244, 5, 142, 215, 135, 35,\n  ]);\n  near.valueReturnRaw(near.altBn128G1Multiexp(buffer));\n}\n\nexport function test_alt_bn128_pairing_check_valid() {\n  // Taken from https://github.com/near/nearcore/blob/8cd095ffc98a6507ed2d2a8982a6a3e42ebc1b62/runtime/near-vm-runner/src/logic/tests/alt_bn128.rs#L239-L250\n  let valid_pair = new Uint8Array([\n    117, 10, 217, 99, 113, 78, 234, 67, 183, 90, 26, 58, 200, 86, 195, 123, 42,\n    184, 213, 88, 224, 248, 18, 200, 108, 6, 181, 6, 28, 17, 99, 7, 36, 134, 53,\n    115, 192, 180, 3, 113, 76, 227, 174, 147, 50, 174, 79, 74, 151, 195, 172,\n    10, 211, 210, 26, 92, 117, 246, 65, 237, 168, 104, 16, 4, 1, 26, 3, 219, 6,\n    13, 193, 115, 77, 230, 27, 13, 242, 214, 195, 9, 213, 99, 135, 12, 160, 202,\n    114, 135, 175, 42, 116, 172, 79, 234, 26, 41, 212, 111, 192, 129, 124, 112,\n    57, 107, 38, 244, 230, 222, 240, 36, 65, 238, 133, 188, 19, 43, 148, 59,\n    205, 40, 161, 179, 173, 228, 88, 169, 231, 29, 17, 67, 163, 51, 165, 187,\n    101, 44, 250, 24, 68, 101, 92, 128, 203, 190, 51, 85, 9, 43, 58, 136, 68,\n    180, 92, 110, 185, 168, 107, 129, 45, 30, 187, 22, 100, 17, 75, 93, 216,\n    125, 23, 212, 11, 186, 199, 204, 1, 140, 133, 11, 82, 44, 65, 222, 20, 26,\n    48, 26, 132, 220, 25, 213, 93, 25, 79, 176, 4, 149, 151, 243, 11, 131, 253,\n    233, 121, 38, 222, 15, 118, 117, 200, 214, 175, 233, 130, 181, 193, 167,\n    255, 153, 169, 240, 207, 235, 28, 31, 83, 74, 69, 179, 6, 150, 72, 67, 74,\n    166, 130, 83, 82, 115, 123, 111, 208, 221, 64, 43, 237, 213, 186, 235, 7,\n    56, 251, 179, 95, 233, 159, 23, 109, 173, 85, 103, 8, 165, 235, 226, 218,\n    79, 72, 120, 172, 251, 20, 83, 121, 201, 140, 98, 170, 246, 121, 218, 19,\n    115, 42, 135, 60, 239, 30, 32, 49, 170, 171, 204, 196, 197, 160, 158, 168,\n    47, 23, 110, 139, 123, 222, 222, 245, 98, 125, 208, 70, 39, 110, 186, 146,\n    254, 66, 185, 118, 3, 78, 32, 47, 179, 197, 93, 79, 240, 204, 78, 236, 133,\n    213, 173, 117, 94, 63, 154, 68, 89, 236, 138, 0, 247, 242, 212, 245, 33,\n    249, 0, 35, 246, 233, 0, 124, 86, 198, 162, 201, 54, 19, 26, 196, 75, 254,\n    71, 70, 238, 51, 2, 23, 185, 152, 139, 134, 65, 107, 129, 114, 244, 47, 251,\n    240, 80, 193, 23,\n  ]);\n  near.valueReturn(near.altBn128PairingCheck(valid_pair));\n}\n\nexport function test_alt_bn128_pairing_check_invalid() {\n  // Taken from https://github.com/near/nearcore/blob/8cd095ffc98a6507ed2d2a8982a6a3e42ebc1b62/runtime/near-vm-runner/src/logic/tests/alt_bn128.rs#L254-L265\n  let invalid_pair = new Uint8Array([\n    117, 10, 217, 99, 113, 78, 234, 67, 183, 90, 26, 58, 200, 86, 195, 123, 42,\n    184, 213, 88, 224, 248, 18, 200, 108, 6, 181, 6, 28, 17, 99, 7, 36, 134, 53,\n    115, 192, 180, 3, 113, 76, 227, 174, 147, 50, 174, 79, 74, 151, 195, 172,\n    10, 211, 210, 26, 92, 117, 246, 65, 237, 168, 104, 16, 4, 1, 26, 3, 219, 6,\n    13, 193, 115, 77, 230, 27, 13, 242, 214, 195, 9, 213, 99, 135, 12, 160, 202,\n    114, 135, 175, 42, 116, 172, 79, 234, 26, 41, 212, 111, 192, 129, 124, 112,\n    57, 107, 38, 244, 230, 222, 240, 36, 65, 238, 133, 188, 19, 43, 148, 59,\n    205, 40, 161, 179, 173, 228, 88, 169, 231, 29, 17, 67, 163, 51, 165, 187,\n    101, 44, 250, 24, 68, 101, 92, 128, 203, 190, 51, 85, 9, 43, 58, 136, 68,\n    180, 92, 110, 185, 168, 107, 129, 45, 30, 187, 22, 100, 17, 75, 93, 216,\n    125, 23, 212, 11, 186, 199, 204, 1, 140, 133, 11, 82, 44, 65, 222, 20, 26,\n    48, 26, 132, 220, 25, 213, 93, 25, 117, 10, 217, 99, 113, 78, 234, 67, 183,\n    90, 26, 58, 200, 86, 195, 123, 42, 184, 213, 88, 224, 248, 18, 200, 108, 6,\n    181, 6, 28, 17, 99, 7, 36, 134, 53, 115, 192, 180, 3, 113, 76, 227, 174,\n    147, 50, 174, 79, 74, 151, 195, 172, 10, 211, 210, 26, 92, 117, 246, 65,\n    237, 168, 104, 16, 4, 109, 173, 85, 103, 8, 165, 235, 226, 218, 79, 72, 120,\n    172, 251, 20, 83, 121, 201, 140, 98, 170, 246, 121, 218, 19, 115, 42, 135,\n    60, 239, 30, 32, 49, 170, 171, 204, 196, 197, 160, 158, 168, 47, 23, 110,\n    139, 123, 222, 222, 245, 98, 125, 208, 70, 39, 110, 186, 146, 254, 66, 185,\n    118, 3, 78, 32, 47, 179, 197, 93, 79, 240, 204, 78, 236, 133, 213, 173, 117,\n    94, 63, 154, 68, 89, 236, 138, 0, 247, 242, 212, 245, 33, 249, 0, 35, 246,\n    233, 0, 124, 86, 198, 162, 201, 54, 19, 26, 196, 75, 254, 71, 70, 238, 51,\n    2, 23, 185, 152, 139, 134, 65, 107, 129, 114, 244, 47, 251, 240, 80, 193,\n    23,\n  ]);\n  near.valueReturn(near.altBn128PairingCheck(invalid_pair));\n}\n"
  },
  {
    "path": "tests/src/bigint-serialization.ts",
    "content": "import { near, NearBindgen, call, view } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `bigintField`.\n * - Includes methods:\n *  - `getBigintField()` - returns the current `bigintField` value.\n *  - `setBigintField(args: { bigintField })` - used to change the current `bigintField` value.\n *  - `increment()` - increases the `bigintField` value by `1n`.\n * @param bigintField - Simple bigint used for testing.\n */\n@NearBindgen({})\nexport class BigIntSerializationTest {\n  bigintField: bigint;\n\n  constructor() {\n    this.bigintField = 1n;\n  }\n\n  @view({})\n  getBigintField(): bigint {\n    near.log(`getBigintField: ${this.bigintField}`);\n    return this.bigintField;\n  }\n\n  @call({})\n  setBigintField(args: { bigintField: bigint }): void {\n    const bigintField = BigInt(args.bigintField);\n    near.log(`setBigintField: ${bigintField}`);\n    this.bigintField = bigintField;\n  }\n\n  @call({})\n  increment(): void {\n    this.bigintField += 1n;\n    near.log(`increment: ${this.bigintField}`);\n  }\n}\n"
  },
  {
    "path": "tests/src/bytes.js",
    "content": "import { near, bytes, str, encode, decode, assert } from \"near-sdk-js\";\n\n// Functions consumed by the bytes tests\n\nexport function log_expected_input_tests() {\n  // log ascii string\n  near.log(\"abc\");\n  // log string with utf-8 chars\n  near.log(\"水\"); // Buffer([0xe6, 0xb0, 0xb4])\n  // log number\n  near.log(333);\n  // log aribrary byte sequence\n  near.log(\"\\x00\\x01\\xff\");\n  // log valid utf8 seqence\n  near.log(\"\\xe6\\xb0\\xb4\");\n\n  // log valid utf8 sequence\n  near.logUtf8(bytes(\"\\xe6\\xb0\\xb4\"));\n  // log valid utf16 sequence\n  near.logUtf16(bytes(\"\\x34\\x6c\"));\n}\n\nexport function log_unexpected_input_tests() {\n  // log non-bytes with logUtf8\n  near.logUtf8(\"水\");\n  // log non-bytes with logUtf16\n  near.logUtf16(\"水\");\n}\n\nexport function log_invalid_utf8_sequence_test() {\n  near.logUtf8(bytes(\"\\x00\\x01\\xff\"));\n}\n\nexport function log_invalid_utf16_sequence_test() {\n  near.logUtf16(bytes(\"\\x00\\x01\\xff\"));\n}\n\nexport function storage_write_bytes() {\n  near.storageWriteRaw(bytes(\"abc\"), bytes(\"def\"));\n  near.storageWriteRaw(bytes(\"\\x00\\x01\\xff\"), bytes(\"\\xe6\\xb0\\xb4\"));\n  near.storageWriteRaw(bytes(\"\\xe6\\xb0\\xb4\"), bytes(\"\\x00ab\"));\n}\n\nexport function storage_write_utf8() {\n  near.storageWrite(\"水\", \"😂\");\n}\n\nexport function storage_read_utf8() {\n  near.valueReturn(near.storageRead(\"水\"));\n}\n\nexport function storage_read_ascii_bytes() {\n  near.valueReturn(near.storageRead(\"abc\"));\n}\n\nexport function storage_read_arbitrary_bytes_key_utf8_sequence_bytes_value() {\n  near.valueReturnRaw(near.storageReadRaw(bytes(\"\\x00\\x01\\xff\")));\n}\n\nexport function storage_read_utf8_sequence_bytes_key_arbitrary_bytes_value() {\n  near.valueReturnRaw(near.storageReadRaw(bytes(\"\\xe6\\xb0\\xb4\")));\n}\n\nexport function panic_test() {\n  throw Error();\n}\n\nexport function panic_ascii_test() {\n  throw Error(\"abc\");\n}\n\nexport function panic_js_number() {\n  throw Error(356);\n}\n\nexport function panic_js_undefined() {\n  throw Error(undefined);\n}\n\nexport function panic_js_null() {\n  throw Error(null);\n}\n\nexport function panic_utf8_test() {\n  throw Error(\"水\");\n}\n\nexport function panicUtf8_valid_utf8_sequence() {\n  near.panicUtf8(bytes(\"\\xe6\\xb0\\xb4\"));\n}\n\nexport function panicUtf8_invalid_utf8_sequence() {\n  near.panicUtf8(bytes(\"\\x00\\x01\\xff\"));\n}\n\nconst areEqual = (first, second) =>\n  first.length === second.length &&\n  first.every((value, index) => value === second[index]);\n\nexport function utf8_string_to_uint8array_tests() {\n  let utf8chars = \"水😂\";\n  let withUtf8CharCodeSeq = \"\\xe6\\xb0\\xb4\";\n  let withArbitraryLatinSeq = \"\\x00\\x01\\xff\";\n\n  assert(\n    areEqual(\n      encode(utf8chars),\n      new Uint8Array([230, 176, 180, 240, 159, 152, 130])\n    )\n  );\n  assert(\n    areEqual(\n      encode(withUtf8CharCodeSeq),\n      new Uint8Array([195, 166, 194, 176, 194, 180])\n    )\n  );\n  assert(\n    areEqual(encode(withArbitraryLatinSeq), new Uint8Array([0, 1, 195, 191]))\n  );\n\n  assert(decode(encode(utf8chars)) == utf8chars);\n  assert(decode(encode(withUtf8CharCodeSeq)) == withUtf8CharCodeSeq);\n  assert(decode(encode(withArbitraryLatinSeq)) == withArbitraryLatinSeq);\n}\n\nexport function uint8array_to_utf8_string_tests() {\n  let validUtf8SeqArray = new Uint8Array([230, 176, 180, 240, 159, 152, 130]);\n  let escapedUtf8SeqArray = new Uint8Array([195, 166, 194, 176, 194, 180]);\n  let invalidUtf8Seq = new Uint8Array([0, 1, 255]);\n\n  assert(decode(validUtf8SeqArray) == \"水😂\");\n  assert(decode(escapedUtf8SeqArray) == \"\\xe6\\xb0\\xb4\");\n  // same behavior as nodejs\n  assert(decode(invalidUtf8Seq) == \"\\x00\\x01\\ufffd\");\n\n  assert(areEqual(encode(decode(validUtf8SeqArray)), validUtf8SeqArray));\n  assert(areEqual(encode(decode(escapedUtf8SeqArray)), escapedUtf8SeqArray));\n  // same behavior as nodejs\n  assert(\n    areEqual(\n      encode(decode(invalidUtf8Seq)),\n      new Uint8Array([0, 1, 239, 191, 189])\n    )\n  );\n}\n\nexport function uint8array_to_latin1_string_tests() {\n  let happensToBeUtf8Seq = new Uint8Array([230, 176, 180]);\n  let validLatin1InvalidUtf8 = new Uint8Array([0, 1, 255]);\n  let ascii = new Uint8Array([65, 66, 67]);\n\n  assert(str(happensToBeUtf8Seq) == \"\\xe6\\xb0\\xb4\");\n  assert(str(validLatin1InvalidUtf8) == \"\\x00\\x01\\xff\");\n  assert(str(ascii) == \"\\x41\\x42\\x43\");\n\n  assert(areEqual(bytes(str(happensToBeUtf8Seq)), happensToBeUtf8Seq));\n  assert(areEqual(bytes(str(validLatin1InvalidUtf8)), validLatin1InvalidUtf8));\n  assert(areEqual(bytes(str(ascii)), ascii));\n}\n"
  },
  {
    "path": "tests/src/constructor-validation/1-parameter-not-set-in-constructor.ts",
    "content": "import { NearBindgen, LookupMap } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class ConstructorValidation {\n  map: LookupMap<string>;\n  name: string;\n  constructor() {\n    this.map = new LookupMap<string>(\"a\");\n  }\n}\n"
  },
  {
    "path": "tests/src/constructor-validation/all-parameters-set-in-constructor.ts",
    "content": "import { NearBindgen, LookupMap, call } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class ConstructorValidation {\n  map: LookupMap<string>;\n  name: string;\n  constructor() {\n    this.map = new LookupMap<string>(\"a\");\n    this.name = \"\";\n  }\n\n  @call({})\n  get() {\n    return { status: \"ok\" };\n  }\n}\n"
  },
  {
    "path": "tests/src/constructor-validation/no-constructor.ts",
    "content": "import { NearBindgen, LookupMap } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class ConstructorValidation {\n  map: LookupMap<string>;\n  name: string;\n}\n"
  },
  {
    "path": "tests/src/constructor-validation/no-parameters-set-in-constructor.ts",
    "content": "import { NearBindgen, LookupMap } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class ConstructorValidation {\n  map: LookupMap<string>;\n  name: string;\n  constructor() {\n    //\n  }\n}\n"
  },
  {
    "path": "tests/src/context_api.js",
    "content": "import { near, bytes } from \"near-sdk-js\";\n\n// Functions consumed by the context api tests\n\nexport function get_current_account_id() {\n  near.valueReturn(near.currentAccountId());\n}\n\nexport function get_signer_account_id() {\n  near.valueReturn(near.signerAccountId());\n}\n\nexport function get_predecessor_account_id() {\n  near.valueReturn(near.predecessorAccountId());\n}\n\nexport function get_signer_account_pk() {\n  near.valueReturnRaw(near.signerAccountPk());\n}\n\nexport function get_input() {\n  near.valueReturnRaw(near.inputRaw());\n}\n\nexport function get_storage_usage() {\n  near.valueReturn(near.storageUsage().toString());\n}\n\nexport function get_block_height() {\n  near.valueReturn(near.blockHeight().toString());\n}\n\nexport function get_block_timestamp() {\n  near.valueReturn(near.blockTimestamp().toString());\n}\n\nexport function get_epoch_height() {\n  near.valueReturn(near.epochHeight().toString());\n}\n\nexport function get_attached_deposit() {\n  near.valueReturn(JSON.stringify(near.attachedDeposit().toString()));\n}\n\nexport function get_prepaid_gas() {\n  near.valueReturn(near.prepaidGas().toString());\n}\n\nexport function get_used_gas() {\n  near.valueReturn(near.usedGas().toString());\n}\n\nexport function get_random_seed() {\n  near.valueReturnRaw(near.randomSeed());\n}\n\nexport function get_validator_stake() {\n  near.valueReturn(near.validatorStake(near.signerAccountId()).toString());\n}\n\nexport function get_total_stake() {\n  near.valueReturn(near.validatorTotalStake().toString());\n}\n"
  },
  {
    "path": "tests/src/date-serialization.ts",
    "content": "import { near, NearBindgen, call, view } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `dateField`.\n * - Includes methods:\n *  - `getDateField()` - returns the current `dateField` value.\n *  - `setDateField(args: { dateField })` - used to change the current `dateField` value.\n *  - `getDateFieldAsMilliseconds()` - returns the `dateField` value in milliseconds.\n * @param dateField - Simple `Date` used for testing.\n */\n@NearBindgen({})\nexport class DateSerializationTest {\n  dateField: Date;\n\n  constructor() {\n    this.dateField = new Date(0);\n  }\n\n  @view({})\n  getDateField(): Date {\n    near.log(`getDateField: ${this.dateField}`);\n    return this.dateField;\n  }\n\n  @call({})\n  setDateField(args: { dateField: Date }): void {\n    const dateField = new Date(args.dateField);\n    near.log(`setDateField: ${dateField}`);\n    this.dateField = dateField;\n  }\n\n  @view({})\n  getDateFieldAsMilliseconds(): number {\n    near.log(`getDateFieldAsMilliseconds: ${this.dateField.getTime()}`);\n    return this.dateField.getTime();\n  }\n}\n"
  },
  {
    "path": "tests/src/decorators/payable.ts",
    "content": "import { near, NearBindgen, call, view } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `@call` decorator method with `option.payableFunction`,\n * which identifies whether the function can accept an attached deposit.\n *  - `option.payableFunction` set to `true`\n *  - `option.payableFunction` set to `false`\n * - Includes methods:\n *  - `setValueWithPayableFunction({ value })` - used to change the current value and can accept an attached deposit.\n *  - `setValueWithNotPayableFunction({ value })` - used to change the current value and cannot accept an attached deposit.\n *  - `setValueWithNotPayableFunctionByDefault({ value })` - used to change the current value and cannot accept an attached deposit,\n * default behavior.\n *  - `getValue()` - returns the current value\n * @param value - Simple string used for testing.\n */\n@NearBindgen({})\nexport class PayableTest {\n  value: string;\n\n  constructor() {\n    this.value = \"\";\n  }\n\n  @call({ payableFunction: true })\n  setValueWithPayableFunction({ value }: { value: string }): void {\n    near.log(`payableFunction: ${value}`);\n    this.value = value;\n  }\n\n  @call({ payableFunction: false })\n  setValueWithNotPayableFunction({ value }: { value: string }): void {\n    near.log(`notPayableFunction: ${value}`);\n    this.value = value;\n  }\n\n  @call({})\n  setValueWithNotPayableFunctionByDefault({ value }: { value: string }): void {\n    near.log(`notPayableFunctionDefault: ${value}`);\n    this.value = value;\n  }\n\n  @view({})\n  getValue(): string {\n    return this.value;\n  }\n}\n"
  },
  {
    "path": "tests/src/decorators/private.ts",
    "content": "import { near, NearBindgen, call, view } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `@call` decorator method with `option.privateFunction`,\n * which identifies whether the function can be called by other contracts.\n *  - `option.privateFunction` set to `true`\n *  - `option.privateFunction` set to `false`\n * - Includes methods:\n *  - `setValueWithPrivateFunction({ value })` - used to change the current value and cannot be called by other contracts.\n *  - `setValueWithNotPrivateFunction({ value })` - used to change the current value and can be called by other contracts.\n *  - `setValueWithNotPrivateFunctionByDefault({ value })` - used to change the current value and can be called by other contracts,\n * default behavior.\n *  - `getValue()` - returns the current value\n * @param value - Simple string used for testing.\n */\n@NearBindgen({})\nexport class PrivateTest {\n  value: string;\n\n  constructor() {\n    this.value = \"\";\n  }\n\n  @call({ privateFunction: true })\n  setValueWithPrivateFunction({ value }: { value: string }): void {\n    near.log(`setValueWithPrivateFunction: ${value}`);\n    this.value = value;\n  }\n\n  @call({ privateFunction: false })\n  setValueWithNotPrivateFunction({ value }: { value: string }): void {\n    near.log(`setValueWithNotPrivateFunction: ${value}`);\n    this.value = value;\n  }\n\n  @call({})\n  setValueWithNotPrivateFunctionByDefault({ value }: { value: string }): void {\n    near.log(`setValueWithNotPrivateFunctionByDefault: ${value}`);\n    this.value = value;\n  }\n\n  @view({})\n  getValue(): string {\n    return this.value;\n  }\n}\n"
  },
  {
    "path": "tests/src/decorators/require_init_false.ts",
    "content": "import { near, NearBindgen, call, view, initialize } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `NearBindgen` decorator with `option.requireInit`,\n * which identifies whether the contract requires initialization or not.\n *  - `option.requireInit` set to `false` - Contract does not require initialization.\n * - Includes methods:\n *  - `init()` - used for initializing the class\n *  - `getStatus()` - used to get the current status param\n *  - `setStatus()` - used to change the current status\n * @param status - Simple string used for testing.\n */\n@NearBindgen({ requireInit: false })\nexport class NBTest {\n  status: string;\n\n  constructor() {\n    this.status = \"\";\n  }\n\n  @initialize({})\n  init({ status }: { status: string }): void {\n    near.log(`init: ${status}`);\n    this.status = status;\n  }\n\n  @view({})\n  getStatus(): string {\n    near.log(`getStatus: ${this.status}`);\n    return this.status;\n  }\n\n  @call({})\n  setStatus({ status }: { status: string }): void {\n    near.log(`setStatus: ${status}`);\n    this.status = status;\n  }\n}\n"
  },
  {
    "path": "tests/src/decorators/require_init_true.ts",
    "content": "import { near, NearBindgen, call, view, initialize } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing of the `NearBindgen` decorator with `option.requireInit`,\n * which identifies whether the contract requires initialization or not.\n *  - `option.requireInit` set to `true` - Contract requires initialization.\n * - Includes methods:\n *  - `init()` - used for initializing the class\n *  - `getStatus()` - used to get the current status param\n *  - `setStatus()` - used to change the current status\n * @param status - Simple string used for testing.\n */\n@NearBindgen({ requireInit: true })\nexport class NBTest {\n  status: string;\n\n  constructor() {\n    this.status = \"\";\n  }\n\n  @initialize({})\n  init({ status }: { status: string }): void {\n    near.log(`init: ${status}`);\n    this.status = status;\n  }\n\n  @view({})\n  getStatus(): string {\n    near.log(`getStatus: ${this.status}`);\n    return this.status;\n  }\n\n  @call({})\n  setStatus({ status }: { status: string }): void {\n    near.log(`setStatus: ${status}`);\n    this.status = status;\n  }\n}\n"
  },
  {
    "path": "tests/src/function-params.js",
    "content": "import { NearBindgen, call, view, near } from \"near-sdk-js\";\n\n/**\n * Simple contract used to test function params.\n * - Includes methods:\n *  - `set_values({ param1, param2, param3 })` - change all the values.\n *  - `get_values()` - returns an object containing all the values.\n * @param val1 - Simple string used for testing.\n * @param val2 - Simple string used for testing.\n * @param val3 - Simple string used for testing.\n */\n@NearBindgen({})\nexport class FunctionParamsTestContract {\n  constructor() {\n    this.val1 = \"default1\";\n    this.val2 = \"default2\";\n    this.val3 = \"default3\";\n  }\n\n  @call({})\n  set_values({ param1, param2, param3 }) {\n    near.log(JSON.stringify({ param1, param2, param3 }));\n    this.val1 = param1;\n    this.val2 = param2;\n    this.val3 = param3;\n  }\n\n  @view({})\n  get_values() {\n    return { val3: this.val3, val2: this.val2, val1: this.val1 };\n  }\n}\n"
  },
  {
    "path": "tests/src/highlevel-promise.js",
    "content": "import { NearBindgen, call, NearPromise, near } from \"near-sdk-js\";\nimport { PublicKey } from \"near-sdk-js\";\n\nfunction callingData() {\n  return {\n    currentAccountId: near.currentAccountId(),\n    signerAccountId: near.signerAccountId(),\n    predecessorAccountId: near.predecessorAccountId(),\n    input: near.input(),\n  };\n}\n\nfunction arrayN(n) {\n  return [...Array(Number(n)).keys()];\n}\n\n/**\n * More information about this class, can be found in - benchmark/README.md/Highlevel collection\n */\n@NearBindgen({})\nexport class HighlevelPromiseContract {\n  @call({})\n  test_promise_batch_stake() {\n    let promise = NearPromise.new(\"highlevel-promise.test.near\").stake(\n      100000000000000000000000000000n,\n      new PublicKey(near.signerAccountPk())\n    );\n\n    return promise;\n  }\n\n  @call({})\n  test_promise_batch_create_transfer() {\n    let promise = NearPromise.new(\"a.highlevel-promise.test.near\")\n      .createAccount()\n      .transfer(10000000000000000000000000n);\n    return promise;\n  }\n\n  @call({})\n  test_promise_add_full_access_key() {\n    let promise = NearPromise.new(\"c.highlevel-promise.test.near\")\n      .createAccount()\n      .transfer(10000000000000000000000000n)\n      .addFullAccessKey(new PublicKey(near.signerAccountPk()));\n    return promise;\n  }\n\n  @call({})\n  test_promise_add_function_call_access_key() {\n    let promise = NearPromise.new(\"d.highlevel-promise.test.near\")\n      .createAccount()\n      .transfer(10000000000000000000000000n)\n      .addAccessKey(\n        new PublicKey(near.signerAccountPk()),\n        250000000000000000000000n,\n        \"highlevel-promise.test.near\",\n        \"test_promise_batch_create_transfer\"\n      );\n    return promise;\n  }\n\n  @call({})\n  test_delete_account() {\n    let promise = NearPromise.new(\"e.highlevel-promise.test.near\")\n      .createAccount()\n      .transfer(10000000000000000000000000n)\n      .deleteAccount(near.signerAccountId());\n    return promise;\n  }\n\n  @call({})\n  test_promise_then() {\n    let promise = NearPromise.new(\"callee-contract.test.near\")\n      .functionCall(\"cross_contract_callee\", \"abc\", 0, 2 * Math.pow(10, 13))\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"cross_contract_callback\",\n          JSON.stringify({ callbackArg1: \"def\" }),\n          0,\n          2 * Math.pow(10, 13)\n        )\n      );\n    return promise;\n  }\n\n  @call({})\n  test_promise_and() {\n    let promise = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"cross_contract_callee\",\n      \"abc\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    let promise2 = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"cross_contract_callee\",\n      \"def\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    let retPromise = promise\n      .and(promise2)\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"cross_contract_callback\",\n          JSON.stringify({ callbackArg1: \"ghi\" }),\n          0,\n          3 * Math.pow(10, 13)\n        )\n      );\n\n    return retPromise;\n  }\n\n  @call({})\n  cross_contract_callback({ callbackArg1 }) {\n    near.log(\"in callback\");\n    return {\n      ...callingData(),\n      promiseResults: arrayN(near.promiseResultsCount()).map((i) =>\n        near.promiseResult(i)\n      ),\n      callbackArg1,\n    };\n  }\n\n  @call({})\n  cross_contract_callback_write_state() {\n    // Attempt to write something in state. If this one is successfully executed and not revoked, these should be in state\n    near.storageWrite(\"aaa\", \"bbb\");\n    near.storageWrite(\"ccc\", \"ddd\");\n    near.storageWrite(\"eee\", \"fff\");\n  }\n\n  @call({})\n  callee_panic() {\n    let promise = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"just_panic\",\n      \"\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    return promise;\n  }\n\n  @call({})\n  before_and_after_callee_panic() {\n    near.log(\"log before call the callee\");\n    let promise = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"just_panic\",\n      \"\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    near.log(\"log after call the callee\");\n    return promise;\n  }\n\n  @call({})\n  callee_panic_then() {\n    let promise = NearPromise.new(\"callee-contract.test.near\")\n      .functionCall(\"just_panic\", \"\", 0, 2 * Math.pow(10, 13))\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"cross_contract_callback_write_state\",\n          \"\",\n          0,\n          2 * Math.pow(10, 13)\n        )\n      );\n    return promise;\n  }\n\n  @call({})\n  callee_panic_and() {\n    let promise = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"just_panic\",\n      \"\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    let promise2 = NearPromise.new(\"callee-contract.test.near\").functionCall(\n      \"write_some_state\",\n      \"\",\n      0,\n      2 * Math.pow(10, 13)\n    );\n    let retPromise = promise\n      .and(promise2)\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"cross_contract_callback_write_state\",\n          \"\",\n          0,\n          3 * Math.pow(10, 13)\n        )\n      );\n\n    return retPromise;\n  }\n\n  @call({})\n  callee_success_then_panic() {\n    let promise = NearPromise.new(\"callee-contract.test.near\")\n      .functionCall(\"write_some_state\", \"abc\", 0, 2 * Math.pow(10, 13))\n      .then(\n        NearPromise.new(\"callee-contract.test.near\").functionCall(\n          \"just_panic\",\n          \"\",\n          0,\n          2 * Math.pow(10, 13)\n        )\n      );\n    near.storageWrite(\"aaa\", \"bbb\");\n    return promise;\n  }\n\n  @call({})\n  handler({ promiseId }) {\n    // example to catch and handle one given promiseId. This is to simulate when you know some\n    // promiseId can be possibly fail and some promiseId can never fail. If more than one promiseId\n    // can be failed. a similar approach can be applied to all promiseIds.\n    let res;\n    try {\n      res = near.promiseResult(promiseId);\n    } catch (e) {\n      throw new Error(\"caught error in the callback: \" + e.toString());\n    }\n    return \"callback got \" + res;\n  }\n\n  @call({})\n  handle_error_in_promise_then() {\n    let promise = NearPromise.new(\"callee-contract.test.near\")\n      .functionCall(\"just_panic\", \"\", 0, 2 * Math.pow(10, 13))\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"handler\",\n          JSON.stringify({ promiseId: 0 }),\n          0,\n          2 * Math.pow(10, 13)\n        )\n      );\n    return promise;\n  }\n\n  @call({})\n  handle_error_in_promise_then_after_promise_and() {\n    let promise = NearPromise.new(\"callee-contract.test.near\")\n      .functionCall(\"cross_contract_callee\", \"abc\", 0, 2 * Math.pow(10, 13))\n      .and(\n        NearPromise.new(\"callee-contract.test.near\").functionCall(\n          \"just_panic\",\n          \"\",\n          0,\n          2 * Math.pow(10, 13)\n        )\n      )\n      .then(\n        NearPromise.new(\"highlevel-promise.test.near\").functionCall(\n          \"handler\",\n          JSON.stringify({ promiseId: 1 }),\n          0,\n          2 * Math.pow(10, 13)\n        )\n      );\n    return promise;\n  }\n\n  @call({})\n  not_return_not_build() {\n    // let promise = NearPromise.new(\"b.highlevel-promise.test.near\")\n    //   .createAccount()\n    //   .transfer(10000000000000000000000000n);\n    // nothing happens\n  }\n\n  @call({})\n  build_not_return() {\n    let promise = NearPromise.new(\"b.highlevel-promise.test.near\")\n      .createAccount()\n      .transfer(10000000000000000000000000n);\n    promise.build();\n    // doesn't return the promise, but promise should be created and executed\n  }\n}\n"
  },
  {
    "path": "tests/src/log_panic_api.js",
    "content": "import { near, bytes } from \"near-sdk-js\";\n\n// Functions consumed by the log panic tests\n\nexport function log_expected_input_tests() {\n  // log ascii string\n  near.log(\"abc\");\n  // log string with utf-8 chars\n  near.log(\"水\");\n  // log number\n  near.log(333);\n  // log aribrary byte sequence\n  near.log(bytes(\"\\x00\\x01\\xff\"));\n  // log valid utf8 seqence\n  near.log(bytes(\"\\xe6\\xb0\\xb4\"));\n\n  // log valid utf8 sequence\n  near.logUtf8(bytes(\"\\xe6\\xb0\\xb4\"));\n  // log valid utf16 sequence\n  near.logUtf16(bytes(\"\\x34\\x6c\"));\n}\n\nexport function log_invalid_utf8_sequence_test() {\n  near.logUtf8(bytes(\"\\x00\\x01\\xff\"));\n}\n\nexport function log_invalid_utf16_sequence_test() {\n  near.logUtf16(bytes(\"\\x00\\x01\\xff\"));\n}\n\nexport function panic_test() {\n  throw Error();\n}\n\nexport function panic_ascii_test() {\n  throw Error(\"abc\");\n}\n\nexport function panic_js_number() {\n  throw Error(356);\n}\n\nexport function panic_js_undefined() {\n  throw Error(undefined);\n}\n\nexport function panic_js_null() {\n  throw Error(null);\n}\n\nexport function panic_utf8_test() {\n  throw Error(\"水\");\n}\n\nexport function panicUtf8_valid_utf8_sequence() {\n  near.panicUtf8(bytes(\"\\xe6\\xb0\\xb4\"));\n}\n\nexport function panicUtf8_invalid_utf8_sequence() {\n  near.panicUtf8(bytes(\"\\x00\\x01\\xff\"));\n}\n"
  },
  {
    "path": "tests/src/lookup-map.js",
    "content": "import { NearBindgen, call, view, LookupMap } from \"near-sdk-js\";\nimport { House, Room } from \"./model.js\";\n\n/**\n * Simple contract used to test `lookupMap` functionality.\n * - Includes methods:\n *  - `get({ key })` - Get the data stored at the provided key.\n *  - `containsKey({ key })` - Checks whether the collection contains the value.\n *  - `set({ key, value })` - Store a new value at the provided key.\n *  - `remove_key({ key })` - Removes and retrieves the element with the provided key.\n *  - `extend({ kvs })` - Extends the current collection with the passed in array of key-value pairs.\n *  - `add_house()` - Adds a test `House` object in the `lookupMap`.\n *  - `get_house()` - Returns a `string` containing the `house.describe()` + `room.describe()` results.\n * @param lookupMap - Simple `LookupMap` used for testing.\n */\n@NearBindgen({})\nexport class LookupMapTestContract {\n  constructor() {\n    this.lookupMap = new LookupMap(\"a\");\n  }\n\n  @view({})\n  get({ key }) {\n    return this.lookupMap.get(key);\n  }\n\n  @view({})\n  containsKey({ key }) {\n    return this.lookupMap.containsKey(key);\n  }\n\n  @call({})\n  set({ key, value }) {\n    this.lookupMap.set(key, value);\n  }\n\n  @call({})\n  remove_key({ key }) {\n    this.lookupMap.remove(key);\n  }\n\n  @call({})\n  extend({ kvs }) {\n    this.lookupMap.extend(kvs);\n  }\n\n  @call({})\n  add_house() {\n    this.lookupMap.set(\n      \"house1\",\n      new House(\"house1\", [\n        new Room(\"room1\", \"200sqft\"),\n        new Room(\"room2\", \"300sqft\"),\n      ])\n    );\n  }\n\n  @view({})\n  get_house() {\n    const houseObject = this.lookupMap.get(\"house1\");\n    // restore class object from serialized data\n    const house = new House(houseObject.name, houseObject.rooms);\n    const roomObject = house.rooms[0];\n    const room = new Room(roomObject.name, roomObject.size);\n    return house.describe() + room.describe();\n  }\n}\n"
  },
  {
    "path": "tests/src/lookup-set.js",
    "content": "import { NearBindgen, call, view, LookupSet } from \"near-sdk-js\";\nimport { House, Room } from \"./model.js\";\n\n/**\n * Simple contract used to test `lookupSet` functionality.\n * - Includes methods:\n *  - `contains({ key })` - Checks whether the value is present in the set.\n *  - `set({ key })` - f the set did not have this value present, `true` is returned. If the set did have this value present, `false` is returned.\n *  - `remove_key({ key })` - Removes and retrieves the element with the provided key.\n *  - `extend({ keys })` - Extends the current collection with the passed array of elements.\n *  - `add_house({ name, rooms })` - Adds a test `House` object in the `lookupSet`.\n *  - `house_exist({ name, rooms })` - Checks whether the value is present in the set, `true` if present, `false` if not.\n * @param lookupSet - Simple `LookupSet` used for testing.\n */\n@NearBindgen({})\nexport class LookupSetTestContract {\n  constructor() {\n    this.lookupSet = new LookupSet(\"a\");\n  }\n\n  @view({})\n  contains({ key }) {\n    return this.lookupSet.contains(key);\n  }\n\n  @call({})\n  set({ key }) {\n    this.lookupSet.set(key);\n  }\n\n  @call({})\n  remove_key({ key }) {\n    this.lookupSet.remove(key);\n  }\n\n  @call({})\n  extend({ keys }) {\n    this.lookupSet.extend(keys);\n  }\n\n  @call({})\n  add_house({ name, rooms }) {\n    let house = new House(name, []);\n    for (let r of rooms) {\n      house.rooms.push(new Room(r.name, r.size));\n    }\n    this.lookupSet.set(house);\n  }\n\n  @view({})\n  house_exist({ name, rooms }) {\n    let house = new House(name, []);\n    for (let r of rooms) {\n      house.rooms.push(new Room(r.name, r.size));\n    }\n    return this.lookupSet.contains(house);\n  }\n}\n"
  },
  {
    "path": "tests/src/math_api.js",
    "content": "import { near, bytes } from \"near-sdk-js\";\n\n// Functions consumed by the math api tests\n\nexport function test_sha256() {\n  near.valueReturnRaw(near.sha256(bytes(\"tesdsst\")));\n}\n\nexport function test_keccak256() {\n  near.valueReturnRaw(near.keccak256(bytes(\"tesdsst\")));\n}\n\nexport function test_keccak512() {\n  near.valueReturnRaw(near.keccak512(bytes(\"tesdsst\")));\n}\n\nexport function test_ripemd160() {\n  near.valueReturnRaw(near.ripemd160(bytes(\"tesdsst\")));\n}\n\nexport function test_ecrecover() {\n  let hash = new Uint8Array([\n    206, 6, 119, 187, 48, 186, 168, 207, 6, 124, 136, 219, 152, 17, 244, 51, 61,\n    19, 27, 248, 188, 241, 47, 231, 6, 93, 33, 29, 206, 151, 16, 8,\n  ]);\n  let sign = new Uint8Array([\n    144, 242, 123, 139, 72, 141, 176, 11, 0, 96, 103, 150, 210, 152, 127, 106,\n    95, 89, 174, 98, 234, 5, 239, 254, 132, 254, 245, 184, 176, 229, 73, 152,\n    74, 105, 17, 57, 173, 87, 163, 240, 185, 6, 99, 118, 115, 170, 47, 99, 209,\n    245, 92, 177, 166, 145, 153, 212, 0, 158, 234, 35, 206, 173, 220, 147,\n  ]);\n  let v = 1;\n  let malleabilityFlag = 1;\n  let ret = near.ecrecover(hash, sign, v, malleabilityFlag);\n  near.valueReturnRaw(ret);\n}\n"
  },
  {
    "path": "tests/src/middlewares.ts",
    "content": "import {\n  NearBindgen,\n  near,\n  call,\n  view,\n  initialize,\n  middleware,\n} from \"near-sdk-js\";\n\n/**\n * Simple contract used for testing the `@middleware` decorator.\n * The method that gets called with the same arguments that are passed to the function it is wrapping.\n * @param args - Arguments that will be passed to the function - immutable.\n */\n@NearBindgen({ requireInit: true })\nexport class Contract {\n  @initialize({})\n  @middleware((...args) => near.log(`Log from middleware: ${args}`))\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  init({ randomData: _ }: { randomData: string }) {}\n\n  @call({})\n  @middleware((...args) => near.log(`Log from middleware: ${args}`))\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  add({ id: _, text: _t }: { id: string; text: string }) {}\n\n  @view({})\n  @middleware((...args) => near.log(`Log from middleware: ${args}`))\n  get({ id, accountId }: { id: string; accountId: string }): {\n    id: string;\n    accountId: string;\n  } {\n    return { id: accountId, accountId: id };\n  }\n\n  @view({})\n  @middleware(\n    (...args) => near.log(`Log from middleware: ${args}`),\n    () => near.log(\"Second log!\")\n  )\n  get_two({ id, accountId }: { id: string; accountId: string }): {\n    id: string;\n    accountId: string;\n  } {\n    return { id: accountId, accountId: id };\n  }\n\n  @view({})\n  get_private(): { id: string; accountId: string } {\n    return this.getFromPrivate({ id: \"test\", accountId: \"tset\" });\n  }\n\n  @middleware((args) => near.log(`Log from middleware: ${args}`))\n  getFromPrivate({ id, accountId }: { id: string; accountId: string }): {\n    id: string;\n    accountId: string;\n  } {\n    return { id, accountId };\n  }\n}\n"
  },
  {
    "path": "tests/src/migrate.ts",
    "content": "import { NearBindgen, near, call, view, migrate } from \"near-sdk-js\";\n\n/**\n * Simple class used for testing.\n *  - `option.requireInit` set to `true` - Contract requires initialization.\n * - Includes methods:\n *  - `increase({ n })` - increases the count with the given `n`\n *  - `getCount()` - get the current count\n *  - `migrFuncValueTo18()` - set the current count to `18`\n * @param count - Simple number used for testing.\n */\n@NearBindgen({})\nexport class Counter {\n  count = 0;\n\n  @call({})\n  increase({ n = 1 }: { n: number }) {\n    this.count += n;\n    near.log(`Counter increased to ${this.count}`);\n  }\n\n  @view({})\n  getCount(): number {\n    return this.count;\n  }\n\n  @migrate({})\n  migrFuncValueTo18(): void {\n    near.log(\"Count: \" + this.count); // expected to be 0\n    this.count = 18;\n  }\n}\n"
  },
  {
    "path": "tests/src/model.js",
    "content": "/**\n * Simple model used for testing.\n * - Includes methods:\n *  - `describe()` - returns a string `house ${this.name} has ${this.rooms.length} rooms.`\n * @param name - Simple `string` used for testing.\n * @param rooms - Simple `Room[]` used for testing.\n */\nexport class House {\n  constructor(name, rooms) {\n    this.name = name;\n    this.rooms = rooms;\n  }\n\n  describe() {\n    return `house ${this.name} has ${this.rooms.length} rooms. `;\n  }\n}\n\n/**\n * Simple model used for testing.\n * - Includes methods:\n *  - `describe()` - returns a string `room ${this.name} is ${this.size}.`\n * @param name - Simple `string` used for testing.\n * @param size - Simple `number` used for testing.\n */\nexport class Room {\n  constructor(name, size) {\n    this.name = name;\n    this.size = size;\n  }\n\n  describe() {\n    return `room ${this.name} is ${this.size}.`;\n  }\n}\n"
  },
  {
    "path": "tests/src/promise_api.js",
    "content": "import { near } from \"near-sdk-js\";\n\n// Functions consumed by the promise api tests\n\nfunction arrayN(n) {\n  return [...Array(Number(n)).keys()];\n}\n\nexport function just_panic() {\n  throw new Error(\"it just panic\");\n}\n\nexport function write_some_state() {\n  // Attempt to write something in state. If this one is successfully executed and not revoked, these should be in state\n  near.storageWrite(\"aaa\", \"bbb\");\n  near.storageWrite(\"ccc\", \"ddd\");\n  near.storageWrite(\"eee\", \"fff\");\n}\n\nfunction callingData() {\n  return {\n    currentAccountId: near.currentAccountId(),\n    signerAccountId: near.signerAccountId(),\n    predecessorAccountId: near.predecessorAccountId(),\n    input: near.input(),\n  };\n}\n\nexport function cross_contract_callee() {\n  near.valueReturn(JSON.stringify(callingData()));\n}\n\nexport function cross_contract_call_gas() {\n  near.valueReturn(near.prepaidGas().toString());\n}\n\nexport function cross_contract_callback() {\n  near.valueReturn(\n    JSON.stringify({\n      ...callingData(),\n      promiseResults: arrayN(near.promiseResultsCount()).map((i) =>\n        near.promiseResult(i)\n      ),\n    })\n  );\n}\n\nexport function test_promise_create() {\n  near.promiseCreate(\n    \"callee-contract.test.near\",\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n}\n\nexport function test_promise_create_gas_overflow() {\n  near.promiseCreate(\n    \"callee-contract.test.near\",\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    BigInt(2) ** BigInt(64)\n  );\n}\n\nexport function test_promise_then() {\n  let promiseId = near.promiseCreate(\n    \"callee-contract.test.near\",\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n  near.promiseThen(\n    promiseId,\n    \"caller-contract.test.near\",\n    \"cross_contract_callback\",\n    \"def\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n}\n\nexport function test_promise_and() {\n  let promiseId = near.promiseCreate(\n    \"callee-contract.test.near\",\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n  let promiseId2 = near.promiseCreate(\n    \"callee-contract.test.near\",\n    \"cross_contract_callee\",\n    \"def\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n  let promiseIdAnd = near.promiseAnd(promiseId, promiseId2);\n  near.promiseThen(\n    promiseIdAnd,\n    \"caller-contract.test.near\",\n    \"cross_contract_callback\",\n    \"ghi\",\n    0,\n    3 * Math.pow(10, 13)\n  );\n}\n"
  },
  {
    "path": "tests/src/promise_batch_api.js",
    "content": "import { near, includeBytes } from \"near-sdk-js\";\n\n// Functions consumed by the promise batch api tests\n\nexport function test_promise_batch_stake() {\n  let promiseId = near.promiseBatchCreate(\"caller2.test.near\");\n  near.promiseBatchActionStake(\n    promiseId,\n    100000000000000000000000000000n,\n    near.signerAccountPk()\n  );\n  near.promiseReturn(promiseId);\n}\n\nexport function test_transfer_overflow() {\n  let promiseId = near.promiseBatchCreate(\"c.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, BigInt(2) ** BigInt(128));\n  near.promiseReturn(promiseId);\n}\n\nexport function test_promise_add_full_access_key() {\n  let promiseId = near.promiseBatchCreate(\"c.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseBatchActionAddKeyWithFullAccess(\n    promiseId,\n    near.signerAccountPk(),\n    1n\n  );\n  near.promiseReturn(promiseId);\n}\n\nexport function test_delete_account() {\n  let promiseId = near.promiseBatchCreate(\"e.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseBatchActionDeleteAccount(promiseId, near.signerAccountId());\n  near.promiseReturn(promiseId);\n}\n\nexport function test_promise_add_function_call_access_key() {\n  let promiseId = near.promiseBatchCreate(\"d.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseBatchActionAddKeyWithFunctionCall(\n    promiseId,\n    near.signerAccountPk(),\n    1n,\n    250000000000000000000000n,\n    \"caller2.test.near\",\n    \"test_promise_batch_create_transfer\"\n  );\n  near.promiseReturn(promiseId);\n}\n\nexport function test_promise_batch_create_transfer() {\n  let promiseId = near.promiseBatchCreate(\"a.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseReturn(promiseId);\n}\n\nexport function test_promise_batch_call_weight() {\n  let promiseId = near.promiseBatchCreate(\"callee-contract.test.near\");\n  near.promiseBatchActionFunctionCallWeight(\n    promiseId,\n    \"cross_contract_call_gas\",\n    \"abc\",\n    0,\n    0,\n    1\n  );\n  near.promiseReturn(promiseId);\n}\n\nexport function test_promise_batch_deploy_call() {\n  let promiseId = near.promiseBatchCreate(\"b.caller2.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  // deploy content of promise_api.wasm to `b.caller2.test.near`\n  near.promiseBatchActionDeployContract(\n    promiseId,\n    includeBytes(\"../build/promise_api.wasm\")\n  );\n  near.promiseBatchActionFunctionCall(\n    promiseId,\n    \"cross_contract_callee\",\n    \"abc\",\n    0,\n    2 * Math.pow(10, 13)\n  );\n  near.promiseReturn(promiseId);\n}\n"
  },
  {
    "path": "tests/src/public-key.js",
    "content": "import { near } from \"near-sdk-js\";\nimport { CurveType, PublicKey } from \"near-sdk-js\";\nimport { assert } from \"near-sdk-js\";\n\n// Functions consumed by the public key tests\n\nfunction runtime_validate_public_key(prefix, public_key) {\n  let promiseId = near.promiseBatchCreate(prefix + \".pk.test.near\");\n  near.promiseBatchActionCreateAccount(promiseId);\n  near.promiseBatchActionTransfer(promiseId, 10000000000000000000000000n);\n  near.promiseBatchActionAddKeyWithFullAccess(promiseId, public_key, 1n);\n  near.promiseReturn(promiseId);\n}\n\nexport function test_add_signer_key() {\n  runtime_validate_public_key(\"aa\", near.signerAccountPk());\n}\n\nexport function test_add_ed25519_key_bytes() {\n  let pk = new PublicKey(\n    new Uint8Array([\n      // CurveType.ED25519 = 0\n      0,\n      // ED25519 PublicKey data\n      186, 44, 216, 49, 157, 48, 151, 47, 23, 244, 137, 69, 78, 150, 54, 42, 30,\n      248, 110, 26, 205, 18, 137, 154, 10, 208, 26, 183, 65, 166, 223, 18,\n    ])\n  );\n  runtime_validate_public_key(\"a\", pk.data);\n}\n\nexport function test_add_ed25519_key_string() {\n  let k = \"ed25519:DXkVZkHd7WUUejCK7i74uAoZWy1w9AZqshhTHxhmqHuB\";\n  let pk = PublicKey.fromString(k);\n  runtime_validate_public_key(\"b\", pk.data);\n}\n\nexport function test_add_secp256k1_key_bytes() {\n  let pk = new PublicKey(\n    new Uint8Array([\n      // CurveType.SECP256K1 = 1\n      1,\n      // SECP256K1 PublicKey data\n      242, 86, 198, 230, 200, 11, 33, 63, 42, 160, 176, 23, 68, 35, 93, 81, 92,\n      89, 68, 53, 190, 101, 27, 21, 136, 58, 16, 221, 71, 47, 166, 70, 206, 98,\n      234, 243, 103, 13, 197, 203, 145, 0, 160, 202, 42, 85, 178, 193, 71, 193,\n      233, 163, 140, 228, 40, 135, 142, 125, 70, 225, 251, 113, 74, 153,\n    ])\n  );\n  runtime_validate_public_key(\"c\", pk.data);\n}\n\nexport function test_add_secp256k1_key_string() {\n  let k =\n    \"secp256k1:5r22SrjrDvgY3wdQsnjgxkeAbU1VcM71FYvALEQWihjM3Xk4Be1CpETTqFccChQr4iJwDroSDVmgaWZv2AcXvYeL\";\n  let pk = PublicKey.fromString(k);\n  runtime_validate_public_key(\"d\", pk.data);\n}\n\nexport function add_invalid_public_key() {\n  runtime_validate_public_key(\n    \"e\",\n    new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n  );\n}\n\nexport function curve_type() {\n  assert(\n    new PublicKey(near.signerAccountPk()).curveType() == CurveType.ED25519\n  );\n}\n\nexport function create_invalid_curve_type() {\n  new PublicKey(new Uint8Array([2, 1]));\n}\n\nexport function create_invalid_length() {\n  new PublicKey(new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));\n}\n\nexport function create_from_invalid_base58() {\n  PublicKey.fromString(\"ed25519:!@#$%^&*\");\n}\n"
  },
  {
    "path": "tests/src/storage_api.js",
    "content": "import { near, bytes } from \"near-sdk-js\";\n\n// Functions consumed by the storage api tests\n\nexport function test_storage_write() {\n  near.valueReturnRaw(\n    bytes(\n      near\n        .storageWriteRaw(bytes(\"\\x00tesdsst\\xff\"), bytes(\"\\x00\\x01\\xff\"))\n        .toString()\n    )\n  );\n}\n\nexport function test_storage_read() {\n  near.valueReturnRaw(near.storageReadRaw(bytes(\"\\x00tesdsst\\xff\")));\n}\n\nexport function test_storage_remove() {\n  near.valueReturnRaw(\n    bytes(near.storageRemoveRaw(bytes(\"\\x00tesdsst\\xff\")).toString())\n  );\n}\n\nexport function test_storage_has_key() {\n  near.valueReturnRaw(\n    bytes(near.storageHasKeyRaw(bytes(\"\\x00tesdsst\\xff\")).toString())\n  );\n}\n\nexport function test_storage_get_evicted() {\n  near.storageWriteRaw(bytes(\"\\x00tesdsst\\xff\"), bytes(\"\\x00\\x01\\xff\"));\n  near.storageWriteRaw(bytes(\"\\x00tesdsst\\xff\"), bytes(\"\\x03\\x01\\xee\"));\n  near.valueReturnRaw(near.storageGetEvictedRaw());\n}\n"
  },
  {
    "path": "tests/src/typescript.ts",
    "content": "import { NearBindgen, view } from \"near-sdk-js\";\n\n@NearBindgen({})\nexport class TypeScriptTestContract {\n  @view({})\n  bigint() {\n    // JSON.stringify cannot seriaize a BigInt, need manually toString\n    return (1n + 2n).toString();\n  }\n}\n"
  },
  {
    "path": "tests/src/unordered-map.js",
    "content": "import { NearBindgen, call, view, UnorderedMap } from \"near-sdk-js\";\nimport { House, Room } from \"./model.js\";\n\n/**\n * Simple contract used for testing the `unorderedMap`.\n * - Includes methods:\n *  - `len()` - Returns the current number of elements present in the map.\n *  - `isEmpty()` - Checks whether the collection is empty.\n *  - `get({ key })` - Get the data stored at the provided key.\n *  - `set({ key, value })` - Store a new value at the provided key.\n *  - `remove_key({ key })` - Removes and retrieves the element with the provided key.\n *  - `clear()` - Remove all of the elements stored within the collection.\n *  - `toArray()` - Return a JavaScript array of the data stored within the collection.\n *  - `extend({ kvs })` - Extends the current collection with the passed in array of key-value pairs.\n *  - `add_house()` - Store a new `House` object in the `unorderedMap` instance.\n *  - `get_house()` - Retrieves the current `House` object from the `unorderedMap` and returns a string `house.describe() + room.describe()`\n *  - `keys({ start, limit })` - Converts the deserialized data from storage to a JavaScript instance of the collection.\n * @param unorderedMap - Simple `UnorderedMap` used for testing.\n */\n@NearBindgen({})\nexport class UnorderedMapTestContract {\n  constructor() {\n    this.unorderedMap = new UnorderedMap(\"a\");\n  }\n\n  @view({})\n  len() {\n    return this.unorderedMap.length;\n  }\n\n  @view({})\n  isEmpty() {\n    return this.unorderedMap.isEmpty();\n  }\n\n  @view({})\n  get({ key }) {\n    return this.unorderedMap.get(key);\n  }\n\n  @call({})\n  set({ key, value }) {\n    this.unorderedMap.set(key, value);\n  }\n\n  @call({})\n  remove_key({ key }) {\n    this.unorderedMap.remove(key);\n  }\n\n  @call({})\n  clear() {\n    this.unorderedMap.clear();\n  }\n\n  @view({})\n  toArray() {\n    return this.unorderedMap.toArray();\n  }\n\n  @call({})\n  extend({ kvs }) {\n    this.unorderedMap.extend(kvs);\n  }\n\n  @call({})\n  add_house() {\n    this.unorderedMap.set(\n      \"house1\",\n      new House(\"house1\", [\n        new Room(\"room1\", \"200sqft\"),\n        new Room(\"room2\", \"300sqft\"),\n      ])\n    );\n  }\n\n  @view({})\n  get_house() {\n    const house = this.unorderedMap.get(\"house1\", {\n      reconstructor: (rawHouse) =>\n        new House(\n          rawHouse.name,\n          rawHouse.rooms.map((rawRoom) => new Room(rawRoom.name, rawRoom.size))\n        ),\n    });\n    const room = house.rooms[0];\n    return house.describe() + room.describe();\n  }\n\n  @view({})\n  keys({ start, limit }) {\n    return this.unorderedMap.keys({ start, limit });\n  }\n}\n"
  },
  {
    "path": "tests/src/unordered-set.js",
    "content": "import { NearBindgen, call, view, UnorderedSet } from \"near-sdk-js\";\nimport { House, Room } from \"./model.js\";\n\n/**\n * Simple contract used for testing the `unorderedSet`.\n * - Includes methods:\n *  - `len()` - Returns the current number of elements present in the set.\n *  - `isEmpty()` - Checks whether the collection is empty.\n *  - `contains({ element })` - Checks whether the collection contains the value.\n *  - `set({ element }) ` - Store a new value at the provided key.\n *  - `remove_key({ element })` - Removes and retrieves the element.\n *  - `clear()` - Remove all of the elements stored within the collection.\n *  - `toArray()` - Return a JavaScript array of the data stored within the collection.\n *  - `elements({ start, limit })` - Converts the deserialized data from storage to a JavaScript instance of the collection.\n *  - `extend({ elements })` - Extends the current collection with the passed in array of elements.\n *  - `add_house({ name, rooms })` - Store a new `House` object in the `unorderedMap` instance.\n *  - `house_exist({ name, rooms })` - Checks whether the collection contains the passed `House` object.\n * @param unorderedSet - Simple `UnorderedSet` used for testing.\n */\n@NearBindgen({})\nexport class UnorderedSetTestContract {\n  constructor() {\n    this.unorderedSet = new UnorderedSet(\"a\");\n  }\n\n  @view({})\n  len() {\n    return this.unorderedSet.length;\n  }\n\n  @view({})\n  isEmpty() {\n    return this.unorderedSet.isEmpty();\n  }\n\n  @view({})\n  contains({ element }) {\n    return this.unorderedSet.contains(element);\n  }\n\n  @call({})\n  set({ element }) {\n    this.unorderedSet.set(element);\n  }\n\n  @call({})\n  remove_key({ element }) {\n    this.unorderedSet.remove(element);\n  }\n\n  @call({})\n  clear() {\n    this.unorderedSet.clear();\n  }\n\n  @view({})\n  toArray() {\n    const res = this.unorderedSet.toArray();\n    return res;\n  }\n\n  @view({})\n  elements({ start, limit }) {\n    return this.unorderedSet.elements({ start, limit });\n  }\n\n  @call({})\n  extend({ elements }) {\n    this.unorderedSet.extend(elements);\n  }\n\n  @call({})\n  add_house({ name, rooms }) {\n    let house = new House(name, []);\n    for (let r of rooms) {\n      house.rooms.push(new Room(r.name, r.size));\n    }\n    this.unorderedSet.set(house);\n  }\n\n  @view({})\n  house_exist({ name, rooms }) {\n    let house = new House(name, []);\n    for (let r of rooms) {\n      house.rooms.push(new Room(r.name, r.size));\n    }\n    return this.unorderedSet.contains(house);\n  }\n}\n"
  },
  {
    "path": "tests/src/vector.js",
    "content": "import { NearBindgen, call, view, Vector } from \"near-sdk-js\";\nimport { House, Room } from \"./model.js\";\n\n/**\n * Simple contract used for testing the `vector`.\n * - Includes methods:\n *  - `len()` - Returns the current number of elements.\n *  - `isEmpty()` - Checks whether the collection is empty.\n *  - `get({ index })` - Get the value at the current index.\n *  - `push({ value })` - Adds data to the collection.\n *  - `pop()` - Removes and retrieves the element with the highest index..\n *  - `clear()` - Remove all of the elements stored within the collection.\n *  - `toArray()` - Return a JavaScript array of the data stored within the collection.\n *  - `extend({ kvs })` - Extends the current collection with the passed in array of elements.\n *  - `replace({ index, value })` - Replaces the data stored at the provided index with the provided data and returns the previously stored data.\n *  - `swapRemove({ index })` - Removes an element from the vector and returns it in serialized form.\n * The removed element is replaced by the last element of the vector.\n * Does not preserve ordering, but is `O(1)`.\n *  - `add_house()` - Store a new `House` object in the `unorderedMap` instance.\n *  - `get_house()` - Returns the `House` object at index `0`.\n * @param vector - Simple `Vector` used for testing.\n */\n@NearBindgen({})\nexport class VectorTestContract {\n  constructor() {\n    this.vector = new Vector(\"a\");\n  }\n\n  @view({})\n  len() {\n    return this.vector.length;\n  }\n\n  @view({})\n  isEmpty() {\n    return this.vector.isEmpty();\n  }\n\n  @view({})\n  get({ index }) {\n    return this.vector.get(index);\n  }\n\n  @call({})\n  push({ value }) {\n    this.vector.push(value);\n  }\n\n  @call({})\n  pop() {\n    this.vector.pop();\n  }\n\n  @call({})\n  clear() {\n    this.vector.clear();\n  }\n\n  @view({})\n  toArray() {\n    return this.vector.toArray();\n  }\n\n  @call({})\n  extend({ kvs }) {\n    this.vector.extend(kvs);\n  }\n\n  @call({})\n  replace({ index, value }) {\n    this.vector.replace(index, value);\n  }\n\n  @call({})\n  swapRemove({ index }) {\n    this.vector.swapRemove(index);\n  }\n\n  @call({})\n  add_house() {\n    this.vector.push(\n      new House(\"house1\", [\n        new Room(\"room1\", \"200sqft\"),\n        new Room(\"room2\", \"300sqft\"),\n      ])\n    );\n  }\n\n  @view({})\n  get_house() {\n    return this.vector.get(0);\n  }\n}\n"
  },
  {
    "path": "tests/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"moduleResolution\": \"node\",\n    \"experimentalDecorators\": true,\n    \"target\": \"es2020\",\n    \"noEmit\": true\n  },\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "turbo.json",
    "content": "{\n  \"$schema\": \"https://turborepo.org/schema.json\",\n  \"pipeline\": {\n    \"tests#build\":{\n    },\n    \"bench#build\":{\n      \"dependsOn\": [\"tests#build\"]\n    },\n    \"examples#build\":{\n    },\n    \"near-sdk-js#build\":{\n    },\n    \"near-contract-standards#build\":{\n    },\n    \"test\": {\n      \"inputs\": [],\n      \"outputs\": []\n    },\n    \"lint\": {\n      \"inputs\": [],\n      \"outputs\": []\n    },\n    \"format\": {\n      \"inputs\": [],\n      \"outputs\": []\n    }\n  }\n}\n"
  },
  {
    "path": "typedoc.json",
    "content": "{\n  \"includeVersion\": true,\n  \"entryPoints\": [\n      \"packages/near-sdk-js\"\n  ],\n  \"entryPointStrategy\": \"packages\",\n  \"githubPages\": true,\n  \"validation\": {\n      \"notExported\": false\n  },\n  \"out\": \"docs\",\n  \"readme\": \"./README.md\"\n}\n"
  }
]