Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@near-js/client package #1351

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions packages/accounts/src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
parseResultError,
DEFAULT_FUNCTION_CALL_GAS,
printTxOutcomeLogsAndFailures,
parseBalance,
} from '@near-js/utils';

import { Connection } from './connection';
Expand Down Expand Up @@ -553,17 +554,13 @@ export class Account implements IntoConnection {
const protocolConfig = await this.connection.provider.experimental_protocolConfig({ finality: 'final' });
const state = await this.state();

const costPerByte = BigInt(protocolConfig.runtime_config.storage_amount_per_byte);
const stateStaked = BigInt(state.storage_usage) * costPerByte;
const staked = BigInt(state.locked);
const totalBalance = BigInt(state.amount) + staked;
const availableBalance = totalBalance - (staked > stateStaked ? staked : stateStaked);
const { available, staked, stateStaked, total } = parseBalance(state, protocolConfig);

return {
total: totalBalance.toString(),
total: total.toString(),
stateStaked: stateStaked.toString(),
staked: staked.toString(),
available: availableBalance.toString()
available: available.toString()
};
}

Expand Down
19 changes: 19 additions & 0 deletions packages/client/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
env:
es6: true
node: true
extends:
- 'eslint:recommended'
- 'plugin:@typescript-eslint/eslint-recommended'
- 'plugin:@typescript-eslint/recommended'
parser: '@typescript-eslint/parser'
rules:
no-inner-declarations: off
indent:
- error
- 2
- SwitchCase: 1
'@typescript-eslint/no-explicit-any': off

parserOptions:
ecmaVersion: 2018
sourceType: module
112 changes: 112 additions & 0 deletions packages/client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# @near-js/client

Functions and classes for working with Near Protocol at a high level.

### Near Client
The `NearClient` class encapsulates common operations:
```ts
import { NearClient } from '@near-js/client';

const near = new NearClient(); // defaults to mainnet network
const testnetClient = new NearClient({ network: 'testnet' });
```

Instances have access to a `Viewer` instance, permitting `view` method calls with an RPC provider. Common view methods (e.g. account/contract) have dedicated methods:
```ts
const keys = await near.viewer.accessKeys('viewer.near');
const alsoKeys = await near.view('viewer.near', 'view_access_key_list'); // equivalent to above
```

Instances can be configured to sign messages intuitively, without extraneous imports:
```ts
near
.withUnencryptedFilesystemKeystore() // defaults to Near CLI path
.withSigningAccount('me.near');

await near.sendNear('you.near', 1000n);
```

Helper methods on the instance simplify common operations:
```ts
const accountResult = await near.createAccount('new-account.near', publicKey); // requires signer
const { available, staked, totalStaked, total } = await near.getBalance('me.near');
const block = await near.getBlock();
```

### TransactionComposer
The `TransactionComposer` class simplifies working with `@near-js/transactions` Transactions:

```ts
import { TransactionComposer } from '@near-js/client';
...
const transaction = new TransactionComposer({
receiver: 'me.near',
sender: 'me.near',
blockHash,
nonce,
publicKey,
})
.deployContract(code)
.addFullAccessKey(PublicKey.from('...'))
.deleteKey(oldPublicKey)
.functionCall('update', { x: 100 })
.toTransaction();
```

### Examples
This API can be used to trivially implement cookbook examples:

#### create-testnet-account.js
```ts
import { NearClient } from '@near-js/client';
import { KeyPairEd25519 } from '@near-js/crypto';

await new NearClient({ network: 'testnet' })
.withUnencryptedFilesystemKeystore()
.withSigningAccount(creatorAccountId)
.createAccount(newAccountId, KeyPairEd25519.fromRandom());
```

#### batch-transactions.js
```ts
import { NearClient } from '@near-js/client';

const near = await new NearClient()
.withUnencryptedFilesystemKeystore()
.withSigningAccount(contractName);

const transaction = near
.initTransaction(contractName)
.deployContract(fs.readFileSync(WASM_PATH))
.functionCall('new', newArgs)
.toTransaction();

const { signedTx } = await near.signTransaction(transaction);
await near.sendTransaction(signedTx);
```

#### meta-transaction.js
```ts
import { NearClient } from '@near-js/client';

const sender = new NearClient()
.withUnencryptedFilesystemKeystore()
.withSigningAccount('sender.near');

const delegateAction = (await sender.initTransaction())
.transfer('receiver.near', 1000n)
.toMetaTransaction();

const { signedDelegateAction } = await sender.signDelegateAction(delegateAction);

const relayer = new NearClient()
.withUnencryptedFilesystemKeystore()
.withSigningAccount('signer.near');

const transaction = (await relayer.initTransaction())
.delegateAction(delegateAction)
.toTransaction();

const { signedTx } = await near.signTransaction(transaction);
await near.sendTransaction(signedTx);
```
28 changes: 28 additions & 0 deletions packages/client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@near-js/client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc -p ./tsconfig.json"
},
"dependencies": {
"@near-js/accounts": "workspace:*",
"@near-js/crypto": "workspace:*",
"@near-js/keystores-node": "workspace:*",
"@near-js/providers": "workspace:*",
"@near-js/signers": "workspace:*",
"@near-js/transactions": "workspace:*",
"@near-js/types": "workspace:*",
"@near-js/utils": "workspace:*",
"@noble/hashes": "1.3.3",
"sha256": "link:@noble/hashes/sha256"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "18.11.18",
"typescript": "5.4.5"
}
}
Loading
Loading