# 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