NEAR Public Goods - JS Tooling
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # NEAR-JS Interface This is a brainstorming document for improving the near-api-js / @near-js interface ## Goals We aim to implement three layers of improvements: - improve existing core interface - remove friction points such as setting up an account to make a view call - reviewing general DevX for opportunities to simplify or make calls more ergonomic - create generic TS abstraction layer - provides helpful higher level functionality such as fetching account balance, interacting with different NEP functions, etc - compatible with wide range of TS environments, browser and backend - React hooks interface - thin layer over generic abstraction layer to expose functionality as React hooks ### Additional Considerations - tree shaking - ## near-cli-rs example interface Export of all actions from near-cli-rs to use as inspiration ### Account | Action | Description | | -------- | -------- | | view-account-summary | View properties for an account | | import-account | Import existing account (a.k.a. "sign in") | | export-account | Export existing account | | create-account | Create a new account | | update-social-profile | Update NEAR Social profile | | delete-account | Delete an account | | list-keys | View a list of access keys of an account | | add-key | Add an access key to an account | | delete-keys | Delete access keys from an account | | manage-storage-deposit | Storage management for contract: deposit, withdrawal, balance review | ### Tokens | Action | Description | | -------- | -------- | | send-near | The transfer is carried out in NEAR tokens | | send-ft | The transfer is carried out in FT tokens | | send-nft | The transfer is carried out in NFT tokens | | view-near-balance | View the balance of Near tokens | | view-ft-balance | View the balance of FT tokens | | view-nft-assets | View the balance of NFT tokens | ### Staking | Action | Description | | -------- | -------- | | validator-list | View the list of validators to delegate | | delegation | Delegation management | ### Contract | Action | Description | | -------- | -------- | | call-function | Execute function (contract method) | | deploy | Add a contract code | | inspect | Get a list of available function names | | download-abi | Download contract ABI | | download-wasm | Download wasm | | view-storage | View contract storage state | ### Transaction | Action | Description | | -------- | -------- | | view-status | Execute function (contract method) | | reconstruct-transaction | Use any existing transaction from the chain to construct NEAR CLI command (helpful tool for re-submitting |similar transactions) | construct-transaction | Construct a new transaction | | sign-transaction | Sign previously prepared unsigned transaction | | print-transaction | Print previously prepared unsigned transaction without modification | | send-signed-transaction | Send a signed transaction | | send-meta-transaction | Act as a relayer to send a signed delegate action (meta-transaction) | ### Config | Action | Description | | -------- | -------- | | show-connections | Show a list of network connections | | add-connection | Add a network connection | | delete-connection | Delete a network connection | ## Additional Actions / Notes - interface for all NEP functions e.g. `StorageManagement.storage_balance_of()` separated into modules - configure client with ABI? could use https://github.com/1Password/typeshare for Rust structs → TS types - we could mirror the fetch interface i.e. `sendTransaction(contract, {options})` or `axios.create` for a reusable instance targeted at a specific contract - priority on the most intuitive TypeScript library which has familiar patterns for TS devs, but share patterns with other ecosystem tooling where possible and it does not degrade TS ergonomics - how much work needs to be done on the underlying @near-js modules in order for our interface to be tree shakeable - tree shaking influences the design quite a bit. everything you want to be tree shakeable has to be a separate export. This may make a fluent api design a non-starter # Brainstorming ## How would you expect calling a function to look? calling from alice to bob ```ts sendTransaction(`alice.near`, { from: `bob.near`, type: `call_function`, method: `foo`, data : { ... } }) sendTransaction({ from: `bob.near`, to: `alice.near`, type: `call_function`, method: `foo` data : { ... } }) sendTransaction(`bob.near`, `alice.near`, `call_function`, `foo`); from(`bob.near`).sendTransaction(`alice.near`, { data : { ... } }) callFunction(`alice.near`, `foo`, { from: `bob.near`, data : { ... } }) as(`bob.near`).callFunction(`alice.near`, `foo`, { data : { ... } }) const bob = acct(`bob.near`, KEY); bob.callFunction(`alice.near`, `foo`, { data : { ... } }) const bob = acct(`bob.near`, KEY); callFunction(bob, `alice.near`, `foo`, { data : { ... } }); ``` ### View function View functions require an RPC provider to make readonly requests. `near-api-js` exposes a `viewFunction` method (used in the code snippet below) on the `Account` class, which is more or less the most straightforward way of making view calls currently. The proposed implementation reduces the amount of initialization overhead and provides a function with clear parameters. **Current implementation** ```ts import { Account, Connection, providers } from 'near-api-js'; (async function () { const account = new Account(Connection.fromConfig({ networkId: 'testnet', provider: new providers.JsonRpcProvider({ url: 'https://rpc.testnet.near.org' }), signer: {}, // signer not needed here but an object must be passed }), 'dontcare'); // required but not used; most string values should work here const app = await account.viewFunction({ contractId: 'v1.chain-hosted-ui.testnet', methodName: 'get_application', args: { application: 'react-vite-example', account_id: 'tuster.testnet' }, }); console.log(app); }()); ``` **Potential implementations** ```ts import { getProvider, view } from './client'; (async function () { const app = await view( 'v1.chain-hosted-ui.testnet', 'get_application', { application: 'react-vite-example', account_id: 'tuster.testnet' }, { provider: getProvider('testnet') } ); console.log(app); }()); ``` ### Call function Call functions... The proposed implementation ... **Current implementation** ```ts= import { Account, Connection, InMemorySigner, keyStores, KeyPair, providers, } from 'near-api-js'; import { SIGNER, SIGNER_KEY } from './constants'; (async function () { const keyStore = new keyStores.InMemoryKeyStore(); await keyStore.setKey( 'testnet', SIGNER, KeyPair.fromString(SIGNER_KEY) ); const account = new Account(Connection.fromConfig({ networkId: 'testnet', provider: new providers.JsonRpcProvider({ url: 'https://rpc.testnet.near.org' }), signer: new InMemorySigner(keyStore), }), SIGNER); const outcome = await account.functionCall({ contractId: 'v1.chain-hosted-ui.testnet', methodName: 'get_application', args: { application: 'react-vite-example', account_id: 'tuster.testnet' }, gas: 300000000000000n, }); console.log(providers.getTransactionLastResult(outcome)); }()); ``` **Potential implementations** ```ts import { call, getMaxGas, getRpcProvider, getSignerFromPrivateKey } from './client'; import { SIGNER, SIGNER_KEY } from './constants'; (async function () { const signer = await getSignerFromPrivateKey(SIGNER, 'testnet', SIGNER_KEY); const provider = getRpcProvider('testnet'); const result = await call( 'v1.chain-hosted-ui.testnet', 'get_application', { application: 'react-vite-example', account_id: 'tuster.testnet' }, { sender: SIGNER, signer, provider, gas: getMaxGas() }, ); console.log(result); }()); ``` ### Create account Account creation... The proposed implementation ... **Current implementation** ```ts import { Account, Connection, InMemorySigner, KeyPair, keyStores, providers, utils, } from 'near-api-js'; import { SIGNER, SIGNER_KEY } from './constants'; (async function () { const keyStore = new keyStores.InMemoryKeyStore(); await keyStore.setKey( 'testnet', SIGNER, KeyPair.fromString(SIGNER_KEY) ); const keyPair = utils.KeyPairEd25519.fromRandom(); const publicKey = keyPair.publicKey.toString(); const config = Connection.fromConfig({ networkId: 'testnet', provider: new providers.JsonRpcProvider({ url: 'https://rpc.testnet.near.org' }), signer: new InMemorySigner(keyStore), }); const creatorAccount = new Account(config, SIGNER); const newAccountId = `new-account-${Date.now().valueOf()}.testnet`; await creatorAccount.functionCall({ contractId: 'testnet', methodName: 'create_account', args: { new_account_id: newAccountId, new_public_key: publicKey, }, gas: 300000000000000n, attachedDeposit: 100n, }); console.log(await (new Account(config, newAccountId).state())); }()); ``` **Potential implementations** ```ts import { KeyPairEd25519 } from '@near-js/crypto'; import { createAccount, getMaxGas, getRpcProvider, getSignerFromPrivateKey, viewAccount } from './client'; import { SIGNER, SIGNER_KEY } from './constants'; (async function () { const provider = getRpcProvider('testnet'); const signer = await getSignerFromPrivateKey(SIGNER, 'testnet', SIGNER_KEY); const keyPair = KeyPairEd25519.fromRandom(); const publicKey = keyPair.publicKey; const newAccountId = `new-account-${Date.now().valueOf()}.testnet`; const result = await createAccount(newAccountId, publicKey, 'testnet', { provider, signer, sender: SIGNER, gas: getMaxGas(), attachedDeposit: 100n, }); console.log(await viewAccount(newAccountId, { provider })); }()); ``` ### Individual Methods Exporting individual methods provides consumers a way to easily identify a piece of behavior to include in their app (e.g. `import { getAccountBalance }`). This approach takes advantage of tree shaking, ensuring that a client bundle only includes the dependencies required for its subset of imported methods. The tradeoff is providing the same interface on every method; e.g. `getAccountBalance` would need to take a client instance or configuration object along with its inherent parameters of `accountId`, etc. So `getAccountBalance` becomes ```ts interface ViewRpcOptions { rpcUrl: string; } function getAccountBalance(accountId: string, options: ViewRpcOptions) { ... } await getAccountBalance('acc.near', { rpcUrl }); // alternatively const provider = new JsonRpcProvider({ rpcUrl }); await getAccountBalance('acc.near', { provider }); ``` This approach will work well for many methods, in particular pre-defined view and call methods whose behavior is easily encapsulated. More complex workflows such as building/signing transactions are not as well-suited to this approach as their parameters tend to be more complex, undermining the benefit of simple imports. We should identify the methods best-suited for this implementation and expose them at the root of the new client package. These methods will invariably duplicate logic available in other places (e.g. `Account` methods); the existing call sites should eventually be updated to use the new methods, assuming they are not deprecated first. # NEAR-JS General Improvements - **modularize packages to enable tree shaking** to simplify usage and compatibility with modern frameworks // TODO group remaining by where they complement other goals - **break out packages from `@near-js/accounts`** `runtime` and `contracts` - **add more signers** for ledger, 1Password, etc. and deprecate the localstorage keystore - **deprecate older modules** (e.g. `wallet-account` package, `Account2FA` class) - **add more JS/TS packages under `@near-js`** (e.g. JS CLI, Ledger, Wallet Selector) to streamline releases - **encourage usage of the new client library over `near-api-js`**, which has a confusing and limiting structure ## Call brainstorming Partials > config ```ts async function callFunction(contract, method, args); async function myContract(method, args) { callFunction('mycontract', method, args) } async function my const myContractCall = _.partial(callFunction, 'myContract'); async function createCallerFunction(contractName) { return _.partial(callFunction, 'myContract'); } ``` ```ts class Account { const address; callFunction: (method, args) => callFunction(this.address, method, args) } ``` would be really useful long term to have a type-safe way to interact with all your contract methods but this would likely be best accomplished with a build step which creates TypeScript definitions based off your ABI # Current friction - view calls - storage_balance_of - various transaction signing, pulling signing out of transactions - level-setting: example code of friction points above and common flows - call function - calling storage_deposit - basic acct management - create account - propose new interface for these examples view call calling function creating account ## Deliverables 1. Single page overview of changes needed to @near-js modules to enable tree shaking and at the same time remove overhead of class instantiation, view calls, etc. To be delivered via TG to get first round of feedback, but should be opinionated and communicate necessity of tree-shaking as acceptance criteria 2. Modules overview for abstraction layer: friendly lib for common actions - check account balance - module for each NEP - wallet standard functionality e.g. verify a `signMessage` payload - https://docs.google.com/document/d/1xDrVQYgm7EniRwdSeEu3vef4f_ZDbrPu99uocMuu8nk/edit#heading=h.vodztrn9r4j0 # Assumptions / Questions How do we expose functions which require indexer data while minimizing our role as gatekeeper of indexers? Discuss with indexer groups in order to establish expected relationship with them # Deliverable 1 - Single page overview for community Hi all The Public Goods team at Pagoda is currently focused on improving the state of TS/JS packages for interacting with NEAR (`near-api-js`/`@near-js`) We plan to implement three layers of changes: - improve existing core interface - deliver new `@near-js/client` interface - remove friction points such as: - unnecessarily setting up an account to make a view call - poor ergonomics of signers and keystores - non-obvious composition between modules necessary to complete an action - refactor existing modules to support tree-shaking as expected by modern TS/JS best practices — switching to top level function exports instead of JS classes - will be released as opt-in, making rollout non-breaking - those who continue to use `class` pattern will not benefit from tree-shaking, so documentation will guide users towards new interface patterns - create generic TS abstraction layer - provide helpful higher level functionality - modules with dedicated functions for interacting with contract standards (e.g. NFT, FT, StorageManagement) - (under consideration) offer functions that rely on indexer data - compatible with wide range of TS environments, browser and backend - React hooks interface - thin layer over above abstraction layer to expose functionality as React hooks - serve as example for other framework-specific interfaces ## Call for feedback We're looking to collect impressions of the current state of `near-aip-js`/`@near-js`, please share any thoughts here: https://github.com/near/near-api-js/discussions/1368 We will also be leveraging GitHub Discussions on that repo for suggesting and weighing specific implementation options. Feel free to follow along and chime in on any upcoming threads

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully