From 0be6c4209f56c0595bf66e217b7ac01444981b99 Mon Sep 17 00:00:00 2001 From: Den <41162202+denbite@users.noreply.github.com> Date: Tue, 28 Nov 2023 13:32:24 +0200 Subject: [PATCH 1/4] feat: Retry RPC requests on 408 HTTP error (#1205) --- .changeset/healthy-bees-shout.md | 5 +++++ packages/providers/src/fetch_json.ts | 3 +++ 2 files changed, 8 insertions(+) create mode 100644 .changeset/healthy-bees-shout.md diff --git a/.changeset/healthy-bees-shout.md b/.changeset/healthy-bees-shout.md new file mode 100644 index 0000000000..9ba24588aa --- /dev/null +++ b/.changeset/healthy-bees-shout.md @@ -0,0 +1,5 @@ +--- +"@near-js/providers": patch +--- + +retry RPC request on 408 HTTP error diff --git a/packages/providers/src/fetch_json.ts b/packages/providers/src/fetch_json.ts index bef1a029dc..57ee7a9766 100644 --- a/packages/providers/src/fetch_json.ts +++ b/packages/providers/src/fetch_json.ts @@ -38,6 +38,9 @@ export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, js if (response.status === 503) { logWarning(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`); return null; + } else if (response.status === 408) { + logWarning(`Retrying HTTP request for ${connectionInfo.url} as the previous connection was unused for some time`); + return null; } throw createError(response.status, await response.text()); } From 6e5e41e76c2d3914b2734e703c69882a7af50eda Mon Sep 17 00:00:00 2001 From: gagdiez Date: Thu, 30 Nov 2023 19:06:37 +0100 Subject: [PATCH 2/4] Add: Typedocs (#1208) * feat: add typedoc + change tsconfig.base * feat: add typedoc action * feat: temporary disable release action * feat: update typedoc generator action * feat: update typedoc generator action to support pnpm * feat: update action logic for testing purposes * feat: configure pnpm back to version 7 * feat: update action configuration * feat: change action configuration * feat: update build documentation action * feat: minor changes * feat: update tsconfig.base.json * feat: update typedoc action * feat: add readme option * feat: update entryPoints * feat: update entryPoints * feat: change entryPoints to near-api-js * feat: add package entrypointstrategy * feat: fix adding modules content on typedoc generated documentation * feat: update tsconfig.base.json * feat: update tsconfig * feat: update tsconfig files for each package * feat: add custom-theme * feat: add custom-theme * feat: testing configuration * feat: add externalSymbolLinkMappings * feat: add typedoc-theme * feat: update readme files links * feat: update typedoc options * feat: update tsconfig * feat: update out folder * feat: update typedoc-generator * feat: add target-folder option to typedoc-generator action * feat: update typedoc docs generator to allow linking README files to packages files * feat: minor changes * feat: update typedoc action * feat: elete tsconfig.json * feat: make changes to the step Update gh-pages Branch * feat: update typedoc-generator steps * feat: update action * feat: add user/email * feat: add tsconfig.json.local * feat: add write permissions * feat: github action small change * feat: fix divergent changes on action * feat: small changes * feat: add action that syncs branches * feat: fix permission issues * feat: created generated-documentation folder * feat: add folder * feat: clean code * feat: change action configuration * feat: change out folder to build * feat: enable target-folder * feat: update build destination folder * feat: change action logic * feat: update action * feat: disable pull-request action * feat: clean docs folder * feat: remove lfs: true * feat: update action * feat: add concurrency handler * feat: remove clean option * feat: revert to gh-pages root * feat: enable pull-request.action * feat: add near-api-js package to docs job * feat: disable jekyll * feat: update links on README_TYPEDOC.md * feat: migrate typedoc.json to javascript to handle github full path * feat: delete typedoc.json * feat: fix @link on account.ts * feat: update near-api-js tsconfig * feat: tsconfig test for near-api-js * feat: add lib and text to exclude option * feat: remove @link tag on unresolved link RequestSignTransactionsOptions * feat: add typedoc-plugin-merge-modules * feat: update tsconfig.base * feat: update pnpm-lock * feat: delete tsconfig.json * feat: remove plugin typedoc-plugin-merge-modules * feat: disable old docs-generator action * feat: update near-api-js tsconfig * feat: updtae tsconfig.base * feat: update action * feat: update action * feat: fix failed to resolve link warning * feat: fix not included in the documentation warning * feat: delete typedoc.json file * feat: typedoc update * feat: test @link tag * feat: @link wip * feat: @link change * feat: fix @link near.ts * feat: near.ts @link * feat: change near.ts * feat: update @link * feat: update @link tag * feat: readme.md file update * feat: enable release action * feat: update githubpages option * refactor: update typedoc-generator * fix: fixed all links in docs * fix: updated action * fix: docs * feat: added near-api-js to typedocs * fix: output dir for typedocs * fix: non-overlapping name for action --------- Co-authored-by: few-sw <149263800+few-sw@users.noreply.github.com> --- .github/workflows/docs-generator-trigger.yml | 31 ---- .github/workflows/typedoc-generator.yml | 46 ++++++ .gitignore | 2 + README.md | 2 +- docs/README.md | 10 -- docs/README_TYPEDOC.md | 25 ++- package.json | 4 +- packages/accounts/README.md | 16 +- packages/accounts/src/account.ts | 62 ++++--- packages/accounts/src/account_2fa.ts | 2 +- packages/accounts/src/contract.ts | 4 +- packages/accounts/typedoc.json | 9 ++ packages/biometric-ed25519/tsconfig.json | 2 +- packages/biometric-ed25519/typedoc.json | 9 ++ packages/cookbook/tsconfig.json | 11 ++ packages/crypto/README.md | 10 +- packages/crypto/tsconfig.json | 2 +- packages/crypto/typedoc.json | 9 ++ packages/iframe-rpc/typedoc.json | 9 ++ packages/keystores-browser/README.md | 2 +- .../src/browser_local_storage_key_store.ts | 6 +- packages/keystores-browser/typedoc.json | 9 ++ packages/keystores-node/README.md | 2 +- .../src/unencrypted_file_system_keystore.ts | 6 +- packages/keystores-node/typedoc.json | 9 ++ packages/keystores/README.md | 6 +- packages/keystores/src/in_memory_key_store.ts | 8 +- packages/keystores/src/keystore.ts | 5 +- packages/keystores/src/merge_key_store.ts | 6 +- packages/keystores/typedoc.json | 9 ++ packages/near-api-js/src/browser-connect.ts | 4 +- packages/near-api-js/src/connect.ts | 10 +- packages/near-api-js/typedoc.json | 9 ++ packages/providers/README.md | 8 +- packages/providers/src/json-rpc-provider.ts | 6 +- packages/providers/typedoc.json | 9 ++ packages/signers/README.md | 4 +- packages/signers/typedoc.json | 9 ++ packages/transactions/README.md | 10 +- packages/transactions/typedoc.json | 9 ++ packages/types/typedoc.json | 9 ++ packages/utils/README.md | 8 +- packages/utils/typedoc.json | 9 ++ packages/wallet-account/README.md | 4 +- packages/wallet-account/src/near.ts | 26 +-- packages/wallet-account/src/wallet_account.ts | 11 +- packages/wallet-account/typedoc.json | 9 ++ pnpm-lock.yaml | 153 +++++++++++++----- tsconfig.base.json | 1 + tsconfig.node.json | 2 +- typedoc.json | 26 +++ 51 files changed, 451 insertions(+), 218 deletions(-) delete mode 100644 .github/workflows/docs-generator-trigger.yml create mode 100644 .github/workflows/typedoc-generator.yml delete mode 100644 docs/README.md create mode 100644 packages/accounts/typedoc.json create mode 100644 packages/biometric-ed25519/typedoc.json create mode 100644 packages/cookbook/tsconfig.json create mode 100644 packages/crypto/typedoc.json create mode 100644 packages/iframe-rpc/typedoc.json create mode 100644 packages/keystores-browser/typedoc.json create mode 100644 packages/keystores-node/typedoc.json create mode 100644 packages/keystores/typedoc.json create mode 100644 packages/near-api-js/typedoc.json create mode 100644 packages/providers/typedoc.json create mode 100644 packages/signers/typedoc.json create mode 100644 packages/transactions/typedoc.json create mode 100644 packages/types/typedoc.json create mode 100644 packages/utils/typedoc.json create mode 100644 packages/wallet-account/typedoc.json create mode 100644 typedoc.json diff --git a/.github/workflows/docs-generator-trigger.yml b/.github/workflows/docs-generator-trigger.yml deleted file mode 100644 index fb45598532..0000000000 --- a/.github/workflows/docs-generator-trigger.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Docs Generator trigger - -on: - workflow_run: - workflows: [Release] - types: [completed] - branches: [master] - -concurrency: - group: "docs" - cancel-in-progress: true - -jobs: - trigger-generator: - runs-on: ubuntu-latest - if: ${{ github.event.workflow_run.conclusion == 'success' }} - environment: DOCS - steps: - - name: Trigger generator - run: | - curl -i -v --location --request POST 'https://docs-bot.vercel.app/api/on-release' \ - --header 'bot-auth: ${{ secrets.DOCS_BOT_SECRET }}' \ - --header 'Content-Type: application/json' \ - --data-raw '{ - "event_type": "release-publish", - "client_payload": { - "source_repo": "near/near-api-js", - "builder_name": "near-api-js", - "release_version": "${{ github.ref_name }}" - } - }' \ No newline at end of file diff --git a/.github/workflows/typedoc-generator.yml b/.github/workflows/typedoc-generator.yml new file mode 100644 index 0000000000..a3d7b03d62 --- /dev/null +++ b/.github/workflows/typedoc-generator.yml @@ -0,0 +1,46 @@ +name: Deploy TypeDoc on GitHub pages + +on: + push: + branches: + master + +env: + NODE_VERSION: 18.x + ENTRY_FILE: 'packages' + CONFIG_PATH: 'tsconfig.base.json' + USES_PNPM: 'true' + DESTINATION_FOLDER: "docs" + +jobs: + deploy: + concurrency: ci-${{ github.ref }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v3 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: Setup pnpm + uses: pnpm/action-setup@v2.2.2 + with: + version: 7 + + - name: Install dependencies + run: pnpm install + + - name: Build project + run: pnpm build + + - name: Build documentation + run: pnpm docs:generate + + - name: Deploy to GitHub pages + uses: JamesIves/github-pages-deploy-action@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + branch: gh-pages + folder: ${{ env.DESTINATION_FOLDER }} + clean: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index c6cd4ab017..94f660ac1a 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,5 @@ lib/ test-keys/ .turbo + +typedoc-docs/ \ No newline at end of file diff --git a/README.md b/README.md index 6623dccfe4..c15d539ea8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NEAR JavaScript API -[![Build Status](https://travis-ci.com/near/near-api-js.svg?branch=master)](https://travis-ci.com/near/near-api-js) +[![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear%2Fnear-api-js%2Fbadge&style=flat&label=Build)](https://actions-badge.atrox.dev/near/near-api-js/goto) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-api-js) NEAR JavaScript API is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index da3dfb4148..0000000000 --- a/docs/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# `near-api-js` documentation - -Docs for this project are generated with an external generator: - -[https://github.com/near/docs-generator](https://github.com/near/docs-generator) - -- A GitHub [workflow](../.github/workflows/docs-generator-trigger.yml) is triggered upon every `near-api-js` release. -- It invokes a lister on a GitHub App installed on @near/docs (deployed on Vercel). - -See [https://github.com/near/docs-generator](https://github.com/near/docs-generator) to learn more. diff --git a/docs/README_TYPEDOC.md b/docs/README_TYPEDOC.md index a5de69b51d..3d3924a7ce 100644 --- a/docs/README_TYPEDOC.md +++ b/docs/README_TYPEDOC.md @@ -18,28 +18,27 @@ NEAR JavaScript API is a complete library to interact with the NEAR blockchain. ### Connect to NEAR -- [From the browser](modules/browserConnect.html) -- [From Node.js](modules/connect.html) +- [From the browser](modules/near_api_js.browserConnect.html) +- [From Node.js](modules/near_api_js.connect.html) ### Managing Accounts -- Class [`Account`](classes/account.Account.html) -- Module [`walletAccount`](modules/walletAccount.html) -- Class [`Contract`](classes/contract.Contract.html) +- Class [`Account`](classes/_near_js_accounts.account.Account.html) +- Module [`walletAccount`](modules/_near_js_wallet_account.walletAccount.html) +- Class [`Contract`](classes/_near_js_accounts.contract.Contract.html) ### Managing Keys -- Module [`utils/key_pair`](modules/utils_key_pair.html) -- Class [`BrowserLocalStorageKeyStore`](classes/key_stores_browser_local_storage_key_store.BrowserLocalStorageKeyStore.html) -- Class [`InMemoryKeyStore`](classes/key_stores_in_memory_key_store.InMemoryKeyStore.html) -- Class [`UnencryptedFileSystemKeyStore`](classes/key_stores_unencrypted_file_system_keystore.UnencryptedFileSystemKeyStore.html) -- Class [`MergeKeyStore`](classes/key_stores_merge_key_store.MergeKeyStore.html) +- Module [`utils/key_pair`](modules/near_api_js.utils_key_pair.html) +- Class [`InMemoryKeyStore`](classes/_near_js_keystores.in_memory_key_store.InMemoryKeyStore.html) +- Class [`UnencryptedFileSystemKeyStore`](classes/_near_js_keystores_node.unencrypted_file_system_keystore.UnencryptedFileSystemKeyStore.html) +- Class [`MergeKeyStore`](classes/_near_js_keystores.merge_key_store.MergeKeyStore.html) ### RPC -- [Request and Response Types](modules/providers_provider.html) -- [Client](classes/providers_json_rpc_provider.JsonRpcProvider.html) +- [Request and Response Types](modules/_near_js_types.provider.html) +- [Client](classes/_near_js_providers.json_rpc_provider.JsonRpcProvider.html) ### Utils -- [Formatting utils](modules/utils_format.html) +- [Formatting utils](modules/_near_js_utils.format.html) diff --git a/package.json b/package.json index 20440336c0..498fb55ac5 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "autoclave": "rimraf packages/**/dist && rimraf packages/**/lib && rimraf packages/**/node_modules && rimraf packages/**/coverage && rimraf packages/**/.turbo && rm -rf node_modules", "test": "turbo run test", "release": "changeset publish", - "prepare": "husky install" + "prepare": "husky install", + "docs:generate": "typedoc" }, "devDependencies": { "@changesets/changelog-github": "^0.4.6", @@ -28,6 +29,7 @@ "husky": "^7.0.4", "rimraf": "^3.0.2", "turbo": "^1.4.5", + "typedoc": "^0.25.3", "typescript": "^4.9.4" } } diff --git a/packages/accounts/README.md b/packages/accounts/README.md index 45153e405b..535691282a 100644 --- a/packages/accounts/README.md +++ b/packages/accounts/README.md @@ -4,14 +4,14 @@ A collection of classes, functions, and types for interacting with accounts and ## Modules -- [Account](src/account.ts) a class with methods to transfer NEAR, manage account keys, sign transactions, etc. -- [AccountMultisig](src/account_multisig.ts) a [multisig](https://github.com/near/core-contracts/tree/master/multisig) deployed `Account` requiring multiple keys to sign transactions -- [Account2FA](src/account_2fa.ts) extension of `AccountMultisig` used in conjunction with 2FA provided by [near-contract-helper](https://github.com/near/near-contract-helper) -- [AccountCreator](src/account_creator.ts) classes for creating NEAR accounts -- [Contract](src/contract.ts) represents a deployed smart contract with view and/or change methods -- [Connection](src/connection.ts) a record containing the information required to connect to NEAR RPC -- [Constants](src/constants.ts) account-specific constants -- [Types](src/types.ts) account-specific types +- [Account](https://github.com/near/near-api-js/blob/master/packages/accounts/src/account.ts) a class with methods to transfer NEAR, manage account keys, sign transactions, etc. +- [AccountMultisig](https://github.com/near/near-api-js/blob/master/packages/accounts/src/account_multisig.ts) a [multisig](https://github.com/near/core-contracts/tree/master/multisig) deployed `Account` requiring multiple keys to sign transactions +- [Account2FA](https://github.com/near/near-api-js/blob/master/packages/accounts/src/account_2fa.ts) extension of `AccountMultisig` used in conjunction with 2FA provided by [near-contract-helper](https://github.com/near/near-contract-helper) +- [AccountCreator](https://github.com/near/near-api-js/blob/master/packages/accounts/src/account_creator.ts) classes for creating NEAR accounts +- [Contract](https://github.com/near/near-api-js/blob/master/packages/accounts/src/contract.ts) represents a deployed smart contract with view and/or change methods +- [Connection](https://github.com/near/near-api-js/blob/master/packages/accounts/src/connection.ts) a record containing the information required to connect to NEAR RPC +- [Constants](https://github.com/near/near-api-js/blob/master/packages/accounts/src/constants.ts) account-specific constants +- [Types](https://github.com/near/near-api-js/blob/master/packages/accounts/src/types.ts) account-specific types # License diff --git a/packages/accounts/src/account.ts b/packages/accounts/src/account.ts index 837dca6678..1c462d4202 100644 --- a/packages/accounts/src/account.ts +++ b/packages/accounts/src/account.ts @@ -81,12 +81,12 @@ export interface SignAndSendTransactionOptions { actions: Action[]; /** * Metadata to send the NEAR Wallet if using it to sign transactions. - * @see {@link RequestSignTransactionsOptions} + * @see RequestSignTransactionsOptions */ walletMeta?: string; /** * Callback url to send the NEAR Wallet if using it to sign transactions. - * @see {@link RequestSignTransactionsOptions} + * @see RequestSignTransactionsOptions */ walletCallbackUrl?: string; returnError?: boolean; @@ -94,7 +94,7 @@ export interface SignAndSendTransactionOptions { /** * Options used to initiate a function call (especially a change function call) - * @see {@link account!Account#viewFunction} to initiate a view function call + * @see {@link Account#viewFunction | viewFunction} to initiate a view function call */ export interface FunctionCallOptions { /** The NEAR account id where the contract is deployed */ @@ -122,18 +122,18 @@ export interface FunctionCallOptions { export interface ChangeFunctionCallOptions extends FunctionCallOptions { /** * Metadata to send the NEAR Wallet if using it to sign transactions. - * @see {@link RequestSignTransactionsOptions} + * @see RequestSignTransactionsOptions */ walletMeta?: string; /** * Callback url to send the NEAR Wallet if using it to sign transactions. - * @see {@link RequestSignTransactionsOptions} + * @see RequestSignTransactionsOptions */ walletCallbackUrl?: string; } -export interface ViewFunctionCallOptions extends FunctionCallOptions { - parse?: (response: Uint8Array) => any; - blockQuery?: BlockReference; +export interface ViewFunctionCallOptions extends FunctionCallOptions { + parse?: (response: Uint8Array) => any; + blockQuery?: BlockReference; } interface StakedBalance { @@ -163,11 +163,7 @@ function bytesJsonStringify(input: any): Buffer { } /** - * This class provides common account related RPC calls including signing transactions with a {@link utils/key_pair!KeyPair}. - * - * @hint Use {@link walletAccount!WalletConnection} in the browser to redirect to [NEAR Wallet](https://wallet.near.org/) for Account/key management using the {@link key_stores/browser_local_storage_key_store!BrowserLocalStorageKeyStore}. - * @see [https://docs.near.org/docs/develop/front-end/naj-quick-reference#account](https://docs.near.org/tools/near-api-js/quick-reference#account) - * @see [Account Spec](https://nomicon.io/DataStructures/Account.html) + * This class provides common account related RPC calls including signing transactions with a {@link "@near-js/crypto".key_pair.KeyPair | KeyPair}. */ export class Account { readonly connection: Connection; @@ -194,7 +190,7 @@ export class Account { * Create a signed transaction which can be broadcast to the network * @param receiverId NEAR account receiving the transaction * @param actions list of actions to perform as part of the transaction - * @see {@link providers/json-rpc-provider!JsonRpcProvider#sendTransaction | JsonRpcProvider.sendTransaction} + * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider.sendTransaction | JsonRpcProvider.sendTransaction} */ protected async signTransaction(receiverId: string, actions: Action[]): Promise<[Uint8Array, SignedTransaction]> { const accessKeyInfo = await this.findAccessKey(receiverId, actions); @@ -214,7 +210,7 @@ export class Account { /** * Sign a transaction to preform a list of actions and broadcast it using the RPC API. - * @see {@link providers/json-rpc-provider!JsonRpcProvider#sendTransaction | JsonRpcProvider.sendTransaction} + * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider | JsonRpcProvider } */ async signAndSendTransaction({ receiverId, actions, returnError }: SignAndSendTransactionOptions): Promise { let txHash, signedTx; @@ -248,7 +244,7 @@ export class Account { printTxOutcomeLogsAndFailures({ contractId: signedTx.transaction.receiverId, outcome: result }); // Should be falsy if result.status.Failure is null - if (!returnError && typeof result.status === 'object' && typeof result.status.Failure === 'object' && result.status.Failure !== null) { + if (!returnError && typeof result.status === 'object' && typeof result.status.Failure === 'object' && result.status.Failure !== null) { // if error data has error_message and error_type properties, we consider that node returned an error in the old format if (result.status.Failure.error_message && result.status.Failure.error_type) { throw new TypedError( @@ -266,7 +262,7 @@ export class Account { accessKeyByPublicKeyCache: { [key: string]: AccessKeyView } = {}; /** - * Finds the {@link providers/provider!AccessKeyView} associated with the accounts {@link utils/key_pair!PublicKey} stored in the {@link key_stores/keystore!KeyStore}. + * Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link "@near-js/keystores".keystore.KeyStore | Keystore}. * * @todo Find matching access key based on transaction (i.e. receiverId and actions) * @@ -396,16 +392,16 @@ export class Account { this.validateArgs(args); let functionCallArgs; - if(jsContract){ - const encodedArgs = this.encodeJSContractArgs( contractId, methodName, JSON.stringify(args) ); - functionCallArgs = ['call_js_contract', encodedArgs, gas, attachedDeposit, null, true ]; - } else{ + if (jsContract) { + const encodedArgs = this.encodeJSContractArgs(contractId, methodName, JSON.stringify(args)); + functionCallArgs = ['call_js_contract', encodedArgs, gas, attachedDeposit, null, true]; + } else { const stringifyArg = stringify === undefined ? stringifyJsonOrBytes : stringify; functionCallArgs = [methodName, args, gas, attachedDeposit, stringifyArg, false]; } return this.signAndSendTransaction({ - receiverId: jsContract ? this.connection.jsvmAccountId: contractId, + receiverId: jsContract ? this.connection.jsvmAccountId : contractId, // eslint-disable-next-line prefer-spread actions: [functionCall.apply(void 0, functionCallArgs)], walletMeta, @@ -543,20 +539,20 @@ export class Account { blockQuery = { finality: 'optimistic' } }: ViewFunctionCallOptions): Promise { let encodedArgs; - + this.validateArgs(args); - - if(jsContract){ - encodedArgs = this.encodeJSContractArgs(contractId, methodName, Object.keys(args).length > 0 ? JSON.stringify(args): ''); - } else{ - encodedArgs = stringify(args); + + if (jsContract) { + encodedArgs = this.encodeJSContractArgs(contractId, methodName, Object.keys(args).length > 0 ? JSON.stringify(args) : ''); + } else { + encodedArgs = stringify(args); } const result = await this.connection.provider.query({ request_type: 'call_function', ...blockQuery, account_id: jsContract ? this.connection.jsvmAccountId : contractId, - method_name: jsContract ? 'view_js_contract' : methodName, + method_name: jsContract ? 'view_js_contract' : methodName, args_base64: encodedArgs.toString('base64') }); @@ -575,7 +571,7 @@ export class Account { * @param prefix allows to filter which keys should be returned. Empty prefix means all keys. String prefix is utf-8 encoded. * @param blockQuery specifies which block to query state at. By default returns last "optimistic" block (i.e. not necessarily finalized). */ - async viewState(prefix: string | Uint8Array, blockQuery: BlockReference = { finality: 'optimistic' } ): Promise> { + async viewState(prefix: string | Uint8Array, blockQuery: BlockReference = { finality: 'optimistic' }): Promise> { const { values } = await this.connection.provider.query({ request_type: 'view_state', ...blockQuery, @@ -651,12 +647,12 @@ export class Account { * NOTE: If the tokens are delegated to a staking pool that is currently on pause or does not have enough tokens to participate in validation, they won't be accounted for. * @returns {Promise} */ - async getActiveDelegatedStakeBalance(): Promise { + async getActiveDelegatedStakeBalance(): Promise { const block = await this.connection.provider.block({ finality: 'final' }); const blockHash = block.header.hash; const epochId = block.header.epoch_id; const { current_validators, next_validators, current_proposals } = await this.connection.provider.validators(epochId); - const pools:Set = new Set(); + const pools: Set = new Set(); [...current_validators, ...next_validators, ...current_proposals] .forEach((validator) => pools.add(validator.account_id)); @@ -704,7 +700,7 @@ export class Account { } return result; }, - { stakedValidators: [], failedValidators: [], total: new BN(0) }); + { stakedValidators: [], failedValidators: [], total: new BN(0) }); return { ...summary, diff --git a/packages/accounts/src/account_2fa.ts b/packages/accounts/src/account_2fa.ts index b383bcaeee..a45d3ac0a9 100644 --- a/packages/accounts/src/account_2fa.ts +++ b/packages/accounts/src/account_2fa.ts @@ -46,7 +46,7 @@ export class Account2FA extends AccountMultisig { /** * Sign a transaction to preform a list of actions and broadcast it using the RPC API. - * @see {@link providers/json-rpc-provider!JsonRpcProvider#sendTransaction | JsonRpcProvider.sendTransaction} + * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider.sendTransaction | JsonRpcProvider.sendTransaction} */ async signAndSendTransaction({ receiverId, actions }: SignAndSendTransactionOptions): Promise { await super.signAndSendTransaction({ receiverId, actions }); diff --git a/packages/accounts/src/contract.ts b/packages/accounts/src/contract.ts index 17dd1b0385..77e7982aaf 100644 --- a/packages/accounts/src/contract.ts +++ b/packages/accounts/src/contract.ts @@ -85,14 +85,14 @@ export interface ContractMethods { /** * Methods that change state. These methods cost gas and require a signed transaction. * - * @see {@link account!Account.functionCall} + * @see {@link Account#functionCall} */ changeMethods: string[]; /** * View methods do not require a signed transaction. * - * @see {@link account!Account#viewFunction} + * @see {@link Account#viewFunction} */ viewMethods: string[]; diff --git a/packages/accounts/typedoc.json b/packages/accounts/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/accounts/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/biometric-ed25519/tsconfig.json b/packages/biometric-ed25519/tsconfig.json index b7ae1707b3..548e050249 100644 --- a/packages/biometric-ed25519/tsconfig.json +++ b/packages/biometric-ed25519/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../../tsconfig.browser.json", "compilerOptions": { "outDir": "./lib", - }, + }, "files": [ "src/index.ts", ] diff --git a/packages/biometric-ed25519/typedoc.json b/packages/biometric-ed25519/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/biometric-ed25519/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/cookbook/tsconfig.json b/packages/cookbook/tsconfig.json new file mode 100644 index 0000000000..cddbc6a829 --- /dev/null +++ b/packages/cookbook/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "module": "commonjs", + "allowJs": true, + "outDir": "./dist", + }, + "include": [ + "**/*.js", + "**/*.ts" + ] +} \ No newline at end of file diff --git a/packages/crypto/README.md b/packages/crypto/README.md index 2b21f6c893..8973be12b8 100644 --- a/packages/crypto/README.md +++ b/packages/crypto/README.md @@ -4,11 +4,11 @@ A collection of classes and types for working with cryptographic key pairs. ## Modules -- [PublicKey](src/public_key.ts) representation of a public key capable of verifying signatures -- [KeyPairBase](src/key_pair_base.ts) abstract class representing a key pair -- [KeyPair](src/key_pair.ts) abstract extension of `KeyPairBase` with static methods for parsing and generating key pairs -- [KeyPairEd25519](src/key_pair_ed25519.ts) implementation of `KeyPairBase` using [Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) -- [Constants](src/constants.ts) keypair-specific constants +- [PublicKey](https://github.com/near/near-api-js/blob/master/packages/crypto/src/public_key.ts) representation of a public key capable of verifying signatures +- [KeyPairBase](https://github.com/near/near-api-js/blob/master/packages/crypto/src/key_pair_base.ts) abstract class representing a key pair +- [KeyPair](https://github.com/near/near-api-js/blob/master/packages/crypto/src/key_pair.ts) abstract extension of `KeyPairBase` with static methods for parsing and generating key pairs +- [KeyPairEd25519](https://github.com/near/near-api-js/blob/master/packages/crypto/src/key_pair_ed25519.ts) implementation of `KeyPairBase` using [Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) +- [Constants](https://github.com/near/near-api-js/blob/master/packages/crypto/src/constants.ts) keypair-specific constants # License diff --git a/packages/crypto/tsconfig.json b/packages/crypto/tsconfig.json index ae42955e48..a698689671 100644 --- a/packages/crypto/tsconfig.json +++ b/packages/crypto/tsconfig.json @@ -6,4 +6,4 @@ "files": [ "src/index.ts" ] -} +} \ No newline at end of file diff --git a/packages/crypto/typedoc.json b/packages/crypto/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/crypto/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/iframe-rpc/typedoc.json b/packages/iframe-rpc/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/iframe-rpc/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/keystores-browser/README.md b/packages/keystores-browser/README.md index 8d47cf76a7..94e96fd3ad 100644 --- a/packages/keystores-browser/README.md +++ b/packages/keystores-browser/README.md @@ -4,7 +4,7 @@ A collection of classes for managing keys in a web browser execution context. ## Modules -- [BrowserLocalStorageKeyStore](src/browser_local_storage_key_store.ts) implementation of [KeyStore](../keystores/src/keystore.ts) storing unencrypted keys in browser LocalStorage +- [BrowserLocalStorageKeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores-browser/src/browser_local_storage_key_store.ts) implementation of [KeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/keystore.ts) storing unencrypted keys in browser LocalStorage # License diff --git a/packages/keystores-browser/src/browser_local_storage_key_store.ts b/packages/keystores-browser/src/browser_local_storage_key_store.ts index 0fc42b5221..9472b183b3 100644 --- a/packages/keystores-browser/src/browser_local_storage_key_store.ts +++ b/packages/keystores-browser/src/browser_local_storage_key_store.ts @@ -42,7 +42,7 @@ export class BrowserLocalStorageKeyStore extends KeyStore { } /** - * Stores a {@link utils/key_pair!KeyPair} in local storage. + * Stores a {@link KeyPair} in local storage. * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @param keyPair The key pair to store in local storage @@ -52,7 +52,7 @@ export class BrowserLocalStorageKeyStore extends KeyStore { } /** - * Gets a {@link utils/key_pair!KeyPair} from local storage + * Gets a {@link KeyPair} from local storage * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @returns {Promise} @@ -66,7 +66,7 @@ export class BrowserLocalStorageKeyStore extends KeyStore { } /** - * Removes a {@link utils/key_pair!KeyPair} from local storage + * Removes a {@link KeyPair} from local storage * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair */ diff --git a/packages/keystores-browser/typedoc.json b/packages/keystores-browser/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/keystores-browser/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/keystores-node/README.md b/packages/keystores-node/README.md index f0a935d29a..47267438b7 100644 --- a/packages/keystores-node/README.md +++ b/packages/keystores-node/README.md @@ -4,7 +4,7 @@ A collection of classes and functions for managing keys in NodeJS execution cont ## Modules -- [UnencryptedFileSystemKeyStore](src/unencrypted_file_system_keystore.ts) implementation of [KeyStore](../keystores/src/keystore.ts) storing unencrypted keys on the local filesystem +- [UnencryptedFileSystemKeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores-node/src/unencrypted_file_system_keystore.ts) implementation of [KeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/keystore.ts) storing unencrypted keys on the local filesystem # License diff --git a/packages/keystores-node/src/unencrypted_file_system_keystore.ts b/packages/keystores-node/src/unencrypted_file_system_keystore.ts index c47febb23d..176ff90cc7 100644 --- a/packages/keystores-node/src/unencrypted_file_system_keystore.ts +++ b/packages/keystores-node/src/unencrypted_file_system_keystore.ts @@ -91,7 +91,7 @@ export class UnencryptedFileSystemKeyStore extends KeyStore { } /** - * Store a {@link utils/key_pair!KeyPair} in an unencrypted file + * Store a {@link KeyPair} in an unencrypted file * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @param keyPair The key pair to store in local storage @@ -103,7 +103,7 @@ export class UnencryptedFileSystemKeyStore extends KeyStore { } /** - * Gets a {@link utils/key_pair!KeyPair} from an unencrypted file + * Gets a {@link KeyPair} from an unencrypted file * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @returns {Promise} @@ -118,7 +118,7 @@ export class UnencryptedFileSystemKeyStore extends KeyStore { } /** - * Deletes an unencrypted file holding a {@link utils/key_pair!KeyPair} + * Deletes an unencrypted file holding a {@link KeyPair} * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair */ diff --git a/packages/keystores-node/typedoc.json b/packages/keystores-node/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/keystores-node/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/keystores/README.md b/packages/keystores/README.md index e14707454f..bf486a5fd4 100644 --- a/packages/keystores/README.md +++ b/packages/keystores/README.md @@ -4,9 +4,9 @@ A collection of classes for managing NEAR-compatible cryptographic keys. ## Modules -- [KeyStore](src/keystore.ts) abstract class for managing account keys -- [InMemoryKeyStore](src/in_memory_key_store.ts) implementation of `KeyStore` using an in-memory data structure local to the instance -- [MergeKeyStore](src/merge_key_store.ts) implementation of `KeyStore` aggregating multiple `KeyStore` implementations +- [KeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/keystore.ts) abstract class for managing account keys +- [InMemoryKeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/in_memory_key_store.ts) implementation of `KeyStore` using an in-memory data structure local to the instance +- [MergeKeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/merge_key_store.ts) implementation of `KeyStore` aggregating multiple `KeyStore` implementations # License diff --git a/packages/keystores/src/in_memory_key_store.ts b/packages/keystores/src/in_memory_key_store.ts index c4114e4774..0ffd7478bc 100644 --- a/packages/keystores/src/in_memory_key_store.ts +++ b/packages/keystores/src/in_memory_key_store.ts @@ -38,7 +38,7 @@ export class InMemoryKeyStore extends KeyStore { } /** - * Stores a {@link utils/key_pair!KeyPair} in in-memory storage item + * Stores a {@link KeyPair} in in-memory storage item * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @param keyPair The key pair to store in local storage @@ -48,7 +48,7 @@ export class InMemoryKeyStore extends KeyStore { } /** - * Gets a {@link utils/key_pair!KeyPair} from in-memory storage + * Gets a {@link KeyPair} from in-memory storage * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @returns {Promise} @@ -62,7 +62,7 @@ export class InMemoryKeyStore extends KeyStore { } /** - * Removes a {@link utils/key_pair!KeyPair} from in-memory storage + * Removes a {@link KeyPair} from in-memory storage * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair */ @@ -71,7 +71,7 @@ export class InMemoryKeyStore extends KeyStore { } /** - * Removes all {@link utils/key_pair!KeyPair} from in-memory storage + * Removes all {@link KeyPair} from in-memory storage */ async clear(): Promise { this.keys = {}; diff --git a/packages/keystores/src/keystore.ts b/packages/keystores/src/keystore.ts index 3053e08a89..ad0f88d0e3 100644 --- a/packages/keystores/src/keystore.ts +++ b/packages/keystores/src/keystore.ts @@ -1,10 +1,9 @@ import { KeyPair } from '@near-js/crypto'; /** - * KeyStores are passed to {@link near!Near} via {@link near!NearConfig} - * and are used by the {@link signer!InMemorySigner} to sign transactions. + * KeyStores are passed to {@link "@near-js/wallet-account".near.Near | Near} via {@link "@near-js/wallet-account".near.NearConfig | NearConfig} + * and are used by the {@link "@near-js/signers".in_memory_signer.InMemorySigner | InMemorySigner} to sign transactions. * - * @see {@link connect} */ export abstract class KeyStore { abstract setKey(networkId: string, accountId: string, keyPair: KeyPair): Promise; diff --git a/packages/keystores/src/merge_key_store.ts b/packages/keystores/src/merge_key_store.ts index ca3e5705d5..2fc6227dc6 100644 --- a/packages/keystores/src/merge_key_store.ts +++ b/packages/keystores/src/merge_key_store.ts @@ -54,7 +54,7 @@ export class MergeKeyStore extends KeyStore { } /** - * Store a {@link utils/key_pair!KeyPair} to the first index of a key store array + * Store a {@link KeyPair} to the first index of a key store array * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @param keyPair The key pair to store in local storage @@ -64,7 +64,7 @@ export class MergeKeyStore extends KeyStore { } /** - * Gets a {@link utils/key_pair!KeyPair} from the array of key stores + * Gets a {@link KeyPair} from the array of key stores * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair * @returns {Promise} @@ -80,7 +80,7 @@ export class MergeKeyStore extends KeyStore { } /** - * Removes a {@link utils/key_pair!KeyPair} from the array of key stores + * Removes a {@link KeyPair} from the array of key stores * @param networkId The targeted network. (ex. default, betanet, etc…) * @param accountId The NEAR account tied to the key pair */ diff --git a/packages/keystores/typedoc.json b/packages/keystores/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/keystores/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/near-api-js/src/browser-connect.ts b/packages/near-api-js/src/browser-connect.ts index e0e5bd7f4a..92d93283ba 100644 --- a/packages/near-api-js/src/browser-connect.ts +++ b/packages/near-api-js/src/browser-connect.ts @@ -1,9 +1,9 @@ /** * Connect to NEAR using the provided configuration. * - * {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required. + * {@link ConnectConfig#networkId} and {@link ConnectConfig#nodeUrl} are required. * - * To sign transactions you can also pass: {@link ConnectConfig.keyStore} + * To sign transactions you can also pass: {@link ConnectConfig#keyStore} * * Both are passed they are prioritize in that order. * diff --git a/packages/near-api-js/src/connect.ts b/packages/near-api-js/src/connect.ts index f46971eee1..656450bace 100644 --- a/packages/near-api-js/src/connect.ts +++ b/packages/near-api-js/src/connect.ts @@ -1,12 +1,12 @@ /** * Connect to NEAR using the provided configuration. * - * {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required. + * {@link ConnectConfig#networkId} and {@link ConnectConfig#nodeUrl} are required. * * To sign transactions you can also pass: - * 1. {@link ConnectConfig.keyStore} - * 2. {@link ConnectConfig.keyPath} - * 3. {@link ConnectConfig.deps.keyStore} (deprecated, only for use in legacy applications) + * 1. {@link ConnectConfig#keyStore} + * 2. {@link ConnectConfig#keyPath} + * 3. {@link ConnectConfig#deps.keyStore} (deprecated, only for use in legacy applications) * * If all three are passed they are prioritize in that order. * @@ -29,7 +29,7 @@ import { logWarning } from './utils'; export interface ConnectConfig extends NearConfig { /** - * Initialize an {@link key_stores/in_memory_key_store!InMemoryKeyStore} by reading the file at keyPath. + * Initialize an {@link InMemoryKeyStore} by reading the file at keyPath. */ keyPath?: string; } diff --git a/packages/near-api-js/typedoc.json b/packages/near-api-js/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/near-api-js/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/providers/README.md b/packages/providers/README.md index 9373b95c2b..05882aa421 100644 --- a/packages/providers/README.md +++ b/packages/providers/README.md @@ -4,10 +4,10 @@ A collection of classes, functions, and types for communicating with the NEAR bl ## Modules -- [Provider](src/provider.ts) abstract class for interacting with NEAR RPC -- [JsonRpcProvider](src/json-rpc-provider.ts) implementation of `Provider` for [JSON-RPC](https://www.jsonrpc.org/) -- [fetch](src/fetch.ts) NodeJS `fetch` implementation -- [fetchJson](src/fetch_json.ts) low-level function for fetching and parsing RPC data +- [Provider](https://github.com/near/near-api-js/blob/master/packages/providers/src/provider.ts) abstract class for interacting with NEAR RPC +- [JsonRpcProvider](https://github.com/near/near-api-js/blob/master/packages/providers/src/json-rpc-provider.ts) implementation of `Provider` for [JSON-RPC](https://www.jsonrpc.org/) +- [fetch](https://github.com/near/near-api-js/blob/master/packages/providers/src/fetch.ts) NodeJS `fetch` implementation +- [fetchJson](https://github.com/near/near-api-js/blob/master/packages/providers/src/fetch_json.ts) low-level function for fetching and parsing RPC data # License diff --git a/packages/providers/src/json-rpc-provider.ts b/packages/providers/src/json-rpc-provider.ts index 921c860612..0e1cfa2243 100644 --- a/packages/providers/src/json-rpc-provider.ts +++ b/packages/providers/src/json-rpc-provider.ts @@ -3,7 +3,7 @@ * @description * This module contains the {@link JsonRpcProvider} client class * which can be used to interact with the [NEAR RPC API](https://docs.near.org/api/rpc/introduction). - * @see {@link providers/provider | providers} for a list of request and response types + * @see {@link "@near-js/types".provider | provider} for a list of request and response types */ import { baseEncode, @@ -139,7 +139,7 @@ export class JsonRpcProvider extends Provider { } /** - * Query the RPC by passing an {@link providers/provider!RpcQueryRequest} + * Query the RPC by passing an {@link "@near-js/types".provider/request.RpcQueryRequest | RpcQueryRequest } * @see [https://docs.near.org/api/rpc/contracts](https://docs.near.org/api/rpc/contracts) * * @typeParam T the shape of the returned query response @@ -167,7 +167,7 @@ export class JsonRpcProvider extends Provider { * pass block_id OR finality as blockQuery, not both * @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk) * - * @param blockQuery {@link providers/provider!BlockReference} (passing a {@link providers/provider!BlockId} is deprecated) + * @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated) */ async block(blockQuery: BlockId | BlockReference): Promise { const { finality } = blockQuery as any; diff --git a/packages/providers/typedoc.json b/packages/providers/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/providers/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/signers/README.md b/packages/signers/README.md index c70a03991b..ca54f591d1 100644 --- a/packages/signers/README.md +++ b/packages/signers/README.md @@ -4,8 +4,8 @@ A collection of classes and types to facilitate cryptographic signing. ## Modules -- [Signer](src/signer.ts) abstract class for cryptographic signing -- [InMemorySigner](src/in_memory_signer.ts) implementation of `Signer` using [InMemoryKeyStore](../keystores/src/in_memory_key_store.ts) to provide keys +- [Signer](https://github.com/near/near-api-js/blob/master/packages/signer/src/ssigner.ts) abstract class for cryptographic signing +- [InMemorySigner](https://github.com/near/near-api-js/blob/master/packages/signer/src/in_memory_signer.ts) implementation of `Signer` using [InMemoryKeyStore](https://github.com/near/near-api-js/blob/master/packages/keystores/src/in_memory_key_store.ts) to provide keys # License diff --git a/packages/signers/typedoc.json b/packages/signers/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/signers/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/transactions/README.md b/packages/transactions/README.md index ba88ef08f8..7c75db549b 100644 --- a/packages/transactions/README.md +++ b/packages/transactions/README.md @@ -4,11 +4,11 @@ A collection of classes, functions, and types for composing, serializing, and si ## Modules -- [actionCreators](src/action_creators.ts) functions for composing actions -- [Actions](src/actions.ts) classes for actions -- [Schema](src/schema.ts) classes and types concerned with (de-)serialization of transactions -- [createTransaction](src/create_transaction.ts) function for composing a transaction -- [signTransaction](src/sign.ts) function for signing a transaction +- [actionCreators](https://github.com/near/near-api-js/blob/master/packages/transactions/src/action_creators.ts) functions for composing actions +- [Actions](https://github.com/near/near-api-js/blob/master/packages/transactions/src/actions.ts) classes for actions +- [Schema](https://github.com/near/near-api-js/blob/master/packages/transactions/src/schema.ts) classes and types concerned with (de-)serialization of transactions +- [createTransaction](https://github.com/near/near-api-js/blob/master/packages/transactions/src/create_transaction.ts) function for composing a transaction +- [signTransaction](https://github.com/near/near-api-js/blob/master/packages/transactions/src/sign.ts) function for signing a transaction # License diff --git a/packages/transactions/typedoc.json b/packages/transactions/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/transactions/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/types/typedoc.json b/packages/types/typedoc.json new file mode 100644 index 0000000000..43ffb21143 --- /dev/null +++ b/packages/types/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src", "src/provider" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/utils/README.md b/packages/utils/README.md index 6da1b4d45c..79edc0fad1 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -4,10 +4,10 @@ A collection of commonly-used functions and constants. ## Modules -- [Format](src/format.ts) NEAR denomination formatting functions -- [Logging](src/logging.ts) functions for printing formatted RPC output -- [Provider](src/provider.ts) functions for parsing RPC output -- [Validators](src/validators.ts) functions for querying blockchain validators +- [Format](https://github.com/near/near-api-js/blob/master/packages/utils/src/format.ts) NEAR denomination formatting functions +- [Logging](https://github.com/near/near-api-js/blob/master/packages/utils/src/logging.ts) functions for printing formatted RPC output +- [Provider](https://github.com/near/near-api-js/blob/master/packages/utils/src/provider.ts) functions for parsing RPC output +- [Validators](https://github.com/near/near-api-js/blob/master/packages/utils/src/validators.ts) functions for querying blockchain validators # License diff --git a/packages/utils/typedoc.json b/packages/utils/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/utils/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/packages/wallet-account/README.md b/packages/wallet-account/README.md index 6650243423..ad4a9f6635 100644 --- a/packages/wallet-account/README.md +++ b/packages/wallet-account/README.md @@ -4,8 +4,8 @@ A collection of classes and types for working with accounts within browser-based ## Modules -- [Near](src/near.ts) a general purpose class for configuring and working with the NEAR blockchain -- [WalletAccount](src/wallet_account.ts) an [Account](../accounts/src/account.ts) implementation for use in a browser-based wallet +- [Near](https://github.com/near/near-api-js/blob/master/packages/wallet-account/src/near.ts) a general purpose class for configuring and working with the NEAR blockchain +- [WalletAccount](https://github.com/near/near-api-js/blob/master/packages/wallet-account/src/wallet_account.ts) an [Account](https://github.com/near/near-api-js/blob/master/packages/accounts/src/account.ts) implementation for use in a browser-based wallet # License diff --git a/packages/wallet-account/src/near.ts b/packages/wallet-account/src/near.ts index 171da805dc..a67c621af0 100644 --- a/packages/wallet-account/src/near.ts +++ b/packages/wallet-account/src/near.ts @@ -1,6 +1,6 @@ /** * This module contains the main class developers will use to interact with NEAR. - * The {@link Near} class is used to interact with {@link account!Account | Accounts} through the {@link providers/json-rpc-provider!JsonRpcProvider}. + * The {@link Near} class is used to interact with {@link "@near-js/accounts".account.Account | Account} through the {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider | JsonRpcProvider}. * It is configured via the {@link NearConfig}. * * @see [https://docs.near.org/tools/near-api-js/quick-reference#account](https://docs.near.org/tools/near-api-js/quick-reference#account) @@ -20,7 +20,7 @@ import { Signer } from '@near-js/signers'; import BN from 'bn.js'; export interface NearConfig { - /** Holds {@link utils/key_pair!KeyPair | KeyPairs} for signing transactions */ + /** Holds {@link "@near-js/crypto".key_pair.KeyPair | KeyPair} for signing transactions */ keyStore?: KeyStore; /** @hidden */ @@ -28,36 +28,36 @@ export interface NearConfig { /** * [NEAR Contract Helper](https://github.com/near/near-contract-helper) url used to create accounts if no master account is provided - * @see {@link account_creator!UrlAccountCreator} + * @see {@link UrlAccountCreator} */ helperUrl?: string; /** - * The balance transferred from the {@link masterAccount} to a created account - * @see {@link account_creator!LocalAccountCreator} + * The balance transferred from the {@link NearConfig#masterAccount} to a created account + * @see {@link LocalAccountCreator} */ initialBalance?: string; /** * The account to use when creating new accounts - * @see {@link account_creator!LocalAccountCreator} + * @see {@link LocalAccountCreator} */ masterAccount?: string; /** - * {@link utils/key_pair!KeyPair | KeyPairs} are stored in a {@link key_stores/keystore!KeyStore} under the `networkId` namespace. + * {@link "@near-js/crypto".key_pair.KeyPair | KeyPair} are stored in a {@link KeyStore} under the `networkId` namespace. */ networkId: string; /** * NEAR RPC API url. used to make JSON RPC calls to interact with NEAR. - * @see {@link providers/json-rpc-provider!JsonRpcProvider} + * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider | JsonRpcProvider} */ nodeUrl: string; /** * NEAR RPC API headers. Can be used to pass API KEY and other parameters. - * @see {@link providers/json-rpc-provider!JsonRpcProvider} + * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider | JsonRpcProvider} */ headers?: { [key: string]: string | number }; @@ -120,10 +120,10 @@ export class Near { } /** - * Create an account using the {@link account_creator!AccountCreator}. Either: - * * using a masterAccount with {@link account_creator!LocalAccountCreator} - * * using the helperUrl with {@link account_creator!UrlAccountCreator} - * @see {@link NearConfig.masterAccount} and {@link NearConfig.helperUrl} + * Create an account using the {@link AccountCreator}. Either: + * * using a masterAccount with {@link LocalAccountCreator} + * * using the helperUrl with {@link UrlAccountCreator} + * @see {@link NearConfig#masterAccount} and {@link NearConfig#helperUrl} * * @param accountId * @param publicKey diff --git a/packages/wallet-account/src/wallet_account.ts b/packages/wallet-account/src/wallet_account.ts index 9d27e9bd25..dfd7126dd9 100644 --- a/packages/wallet-account/src/wallet_account.ts +++ b/packages/wallet-account/src/wallet_account.ts @@ -1,8 +1,7 @@ /** - * The classes in this module are used in conjunction with the {@link key_stores/browser_local_storage_key_store!BrowserLocalStorageKeyStore}. * This module exposes two classes: * * {@link WalletConnection} which redirects users to [NEAR Wallet](https://wallet.near.org/) for key management. - * * {@link ConnectedWalletAccount} is an {@link account!Account} implementation that uses {@link WalletConnection} to get keys + * * {@link ConnectedWalletAccount} is an {@link "@near-js/accounts".account.Account | Account} implementation that uses {@link WalletConnection} to get keys * * @module walletAccount */ @@ -48,8 +47,6 @@ interface RequestSignTransactionsOptions { } /** - * This class is used in conjunction with the {@link key_stores/browser_local_storage_key_store!BrowserLocalStorageKeyStore}. - * It redirects users to [NEAR Wallet](https://wallet.near.org) for key management. * This class is not intended for use outside the browser. Without `window` (i.e. in server contexts), it will instantiate but will throw a clear error when used. * * @see [https://docs.near.org/tools/near-api-js/quick-reference#wallet](https://docs.near.org/tools/near-api-js/quick-reference#wallet) @@ -288,7 +285,7 @@ export class WalletConnection { } /** - * {@link account!Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available. + * {@link Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available. */ export class ConnectedWalletAccount extends Account { walletConnection: WalletConnection; @@ -302,7 +299,7 @@ export class ConnectedWalletAccount extends Account { /** * Sign a transaction by redirecting to the NEAR Wallet - * @see {@link WalletConnection.requestSignTransactions} + * @see {@link WalletConnection#requestSignTransactions} */ async signAndSendTransaction({ receiverId, actions, walletMeta, walletCallbackUrl = window.location.href }: SignAndSendTransactionOptions): Promise { const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId); @@ -343,7 +340,7 @@ export class ConnectedWalletAccount extends Account { }); // TODO: Aggregate multiple transaction request with "debounce". - // TODO: Introduce TrasactionQueue which also can be used to watch for status? + // TODO: Introduce TransactionQueue which also can be used to watch for status? } /** diff --git a/packages/wallet-account/typedoc.json b/packages/wallet-account/typedoc.json new file mode 100644 index 0000000000..61b70ef7b6 --- /dev/null +++ b/packages/wallet-account/typedoc.json @@ -0,0 +1,9 @@ +{ + "extends": [ + "../../typedoc.json" + ], + "entryPoints": [ + "src" + ], + "entryPointStrategy": "expand", +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9f0204836b..eb8cbae4b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,5 +1,9 @@ lockfileVersion: '6.0' +settings: + autoInstallPeers: false + excludeLinksFromLockfile: false + importers: .: @@ -37,6 +41,9 @@ importers: turbo: specifier: ^1.4.5 version: 1.4.5 + typedoc: + specifier: ^0.25.3 + version: 0.25.3(typescript@4.9.4) typescript: specifier: ^4.9.4 version: 4.9.4 @@ -94,7 +101,7 @@ importers: version: 4.0.0 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 near-hello: specifier: ^0.5.1 version: 0.5.1 @@ -198,7 +205,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -230,7 +237,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -249,7 +256,7 @@ importers: devDependencies: jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -271,7 +278,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -377,7 +384,7 @@ importers: version: 2.0.0 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 localstorage-memory: specifier: ^1.0.3 version: 1.0.3 @@ -427,7 +434,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -452,7 +459,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -492,7 +499,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -511,7 +518,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -542,7 +549,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 ts-jest: specifier: ^26.5.6 version: 26.5.6(jest@26.0.1)(typescript@4.9.4) @@ -585,7 +592,7 @@ importers: version: 18.16.1 jest: specifier: ^26.0.1 - version: 26.0.1(ts-node@10.9.1) + version: 26.0.1 localstorage-memory: specifier: ^1.0.3 version: 1.0.3 @@ -1467,7 +1474,7 @@ packages: slash: 3.0.0 dev: true - /@jest/core@26.6.3(ts-node@10.9.1): + /@jest/core@26.6.3: resolution: {integrity: sha512-xvV1kKbhfUqFVuZ8Cyo+JPpipAHHAV3kcDBftiduK8EICXmTFddryy3P7NfZt8Pv37rA9nEJBKCCkglCPt/Xjw==} engines: {node: '>= 10.14.2'} dependencies: @@ -1482,14 +1489,14 @@ packages: exit: 0.1.2 graceful-fs: 4.2.11 jest-changed-files: 26.6.2 - jest-config: 26.6.3(ts-node@10.9.1) + jest-config: 26.6.3 jest-haste-map: 26.6.2 jest-message-util: 26.6.2 jest-regex-util: 26.0.0 jest-resolve: 26.6.2 jest-resolve-dependencies: 26.6.3 - jest-runner: 26.6.3(ts-node@10.9.1) - jest-runtime: 26.6.3(ts-node@10.9.1) + jest-runner: 26.6.3 + jest-runtime: 26.6.3 jest-snapshot: 26.6.2 jest-util: 26.6.2 jest-validate: 26.6.2 @@ -1591,15 +1598,15 @@ packages: collect-v8-coverage: 1.0.2 dev: true - /@jest/test-sequencer@26.6.3(ts-node@10.9.1): + /@jest/test-sequencer@26.6.3: resolution: {integrity: sha512-YHlVIjP5nfEyjlrSr8t/YdNfU/1XEt7c5b4OxcXCjyRhjzLYu/rO69/WHPuYcbCWkz8kAeZVZp2N2+IOLLEPGw==} engines: {node: '>= 10.14.2'} dependencies: '@jest/test-result': 26.6.2 graceful-fs: 4.2.11 jest-haste-map: 26.6.2 - jest-runner: 26.6.3(ts-node@10.9.1) - jest-runtime: 26.6.3(ts-node@10.9.1) + jest-runner: 26.6.3 + jest-runtime: 26.6.3 transitivePeerDependencies: - bufferutil - canvas @@ -2268,6 +2275,10 @@ packages: engines: {node: '>=8'} dev: true + /ansi-sequence-parser@1.1.1: + resolution: {integrity: sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg==} + dev: true + /ansi-styles@3.2.1: resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} engines: {node: '>=4'} @@ -2567,6 +2578,12 @@ packages: concat-map: 0.0.1 dev: true + /brace-expansion@2.0.1: + resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==} + dependencies: + balanced-match: 1.0.2 + dev: true + /braces@2.3.2: resolution: {integrity: sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==} engines: {node: '>=0.10.0'} @@ -4433,6 +4450,8 @@ packages: li: 1.3.0 query-string: 6.14.1 universal-url: 2.0.0 + transitivePeerDependencies: + - encoding dev: true /glob-parent@5.1.2: @@ -5237,12 +5256,12 @@ packages: throat: 5.0.0 dev: true - /jest-cli@26.6.3(ts-node@10.9.1): + /jest-cli@26.6.3: resolution: {integrity: sha512-GF9noBSa9t08pSyl3CY4frMrqp+aQXFGFkf5hEPbh/pIUFYWMK6ZLTfbmadxJVcJrdRoChlWQsA2VkJcDFK8hg==} engines: {node: '>= 10.14.2'} hasBin: true dependencies: - '@jest/core': 26.6.3(ts-node@10.9.1) + '@jest/core': 26.6.3 '@jest/test-result': 26.6.2 '@jest/types': 26.6.2 chalk: 4.1.2 @@ -5250,7 +5269,7 @@ packages: graceful-fs: 4.2.11 import-local: 3.1.0 is-ci: 2.0.0 - jest-config: 26.6.3(ts-node@10.9.1) + jest-config: 26.6.3 jest-util: 26.6.2 jest-validate: 26.6.2 prompts: 2.4.2 @@ -5263,7 +5282,7 @@ packages: - utf-8-validate dev: true - /jest-config@26.6.3(ts-node@10.9.1): + /jest-config@26.6.3: resolution: {integrity: sha512-t5qdIj/bCj2j7NFVHb2nFB4aUdfucDn3JRKgrZnplb8nieAirAzRSHP8uDEd+qV6ygzg9Pz4YG7UTJf94LPSyg==} engines: {node: '>= 10.14.2'} peerDependencies: @@ -5273,7 +5292,7 @@ packages: optional: true dependencies: '@babel/core': 7.22.9 - '@jest/test-sequencer': 26.6.3(ts-node@10.9.1) + '@jest/test-sequencer': 26.6.3 '@jest/types': 26.6.2 babel-jest: 26.6.3(@babel/core@7.22.9) chalk: 4.1.2 @@ -5283,14 +5302,13 @@ packages: jest-environment-jsdom: 26.6.2 jest-environment-node: 26.6.2 jest-get-type: 26.3.0 - jest-jasmine2: 26.6.3(ts-node@10.9.1) + jest-jasmine2: 26.6.3 jest-regex-util: 26.0.0 jest-resolve: 26.6.2 jest-util: 26.6.2 jest-validate: 26.6.2 micromatch: 4.0.5 pretty-format: 26.6.2 - ts-node: 10.9.1(@types/node@18.17.2)(typescript@4.9.4) transitivePeerDependencies: - bufferutil - canvas @@ -5384,7 +5402,7 @@ packages: - supports-color dev: true - /jest-jasmine2@26.6.3(ts-node@10.9.1): + /jest-jasmine2@26.6.3: resolution: {integrity: sha512-kPKUrQtc8aYwBV7CqBg5pu+tmYXlvFlSFYn18ev4gPFtrRzB15N2gW/Roew3187q2w2eHuu0MU9TJz6w0/nPEg==} engines: {node: '>= 10.14.2'} dependencies: @@ -5401,7 +5419,7 @@ packages: jest-each: 26.6.2 jest-matcher-utils: 26.6.2 jest-message-util: 26.6.2 - jest-runtime: 26.6.3(ts-node@10.9.1) + jest-runtime: 26.6.3 jest-snapshot: 26.6.2 jest-util: 26.6.2 pretty-format: 26.6.2 @@ -5497,7 +5515,7 @@ packages: slash: 3.0.0 dev: true - /jest-runner@26.6.3(ts-node@10.9.1): + /jest-runner@26.6.3: resolution: {integrity: sha512-atgKpRHnaA2OvByG/HpGA4g6CSPS/1LK0jK3gATJAoptC1ojltpmVlYC3TYgdmGp+GLuhzpH30Gvs36szSL2JQ==} engines: {node: '>= 10.14.2'} dependencies: @@ -5510,13 +5528,13 @@ packages: emittery: 0.7.2 exit: 0.1.2 graceful-fs: 4.2.11 - jest-config: 26.6.3(ts-node@10.9.1) + jest-config: 26.6.3 jest-docblock: 26.0.0 jest-haste-map: 26.6.2 jest-leak-detector: 26.6.2 jest-message-util: 26.6.2 jest-resolve: 26.6.2 - jest-runtime: 26.6.3(ts-node@10.9.1) + jest-runtime: 26.6.3 jest-util: 26.6.2 jest-worker: 26.6.2 source-map-support: 0.5.21 @@ -5529,7 +5547,7 @@ packages: - utf-8-validate dev: true - /jest-runtime@26.6.3(ts-node@10.9.1): + /jest-runtime@26.6.3: resolution: {integrity: sha512-lrzyR3N8sacTAMeonbqpnSka1dHNux2uk0qqDXVkMv2c/A3wYnvQ4EXuI013Y6+gSKSCxdaczvf4HF0mVXHRdw==} engines: {node: '>= 10.14.2'} hasBin: true @@ -5549,7 +5567,7 @@ packages: exit: 0.1.2 glob: 7.2.3 graceful-fs: 4.2.11 - jest-config: 26.6.3(ts-node@10.9.1) + jest-config: 26.6.3 jest-haste-map: 26.6.2 jest-message-util: 26.6.2 jest-mock: 26.6.2 @@ -5647,14 +5665,14 @@ packages: supports-color: 7.2.0 dev: true - /jest@26.0.1(ts-node@10.9.1): + /jest@26.0.1: resolution: {integrity: sha512-29Q54kn5Bm7ZGKIuH2JRmnKl85YRigp0o0asTc6Sb6l2ch1DCXIeZTLLFy9ultJvhkTqbswF5DEx4+RlkmCxWg==} engines: {node: '>= 10.14.2'} hasBin: true dependencies: - '@jest/core': 26.6.3(ts-node@10.9.1) + '@jest/core': 26.6.3 import-local: 3.1.0 - jest-cli: 26.6.3(ts-node@10.9.1) + jest-cli: 26.6.3 transitivePeerDependencies: - bufferutil - canvas @@ -5765,6 +5783,10 @@ packages: hasBin: true dev: true + /jsonc-parser@3.2.0: + resolution: {integrity: sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==} + dev: true + /jsonfile@4.0.0: resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} optionalDependencies: @@ -5870,7 +5892,9 @@ packages: dependencies: abort-controller: 3.0.0 ky: 0.12.0 - node-fetch: 2.6.1 + node-fetch: 2.6.12 + transitivePeerDependencies: + - encoding dev: true /ky@0.12.0: @@ -6054,6 +6078,10 @@ packages: resolution: {integrity: sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg==} dev: false + /lunr@2.3.9: + resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + dev: true + /make-dir@4.0.0: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} @@ -6093,6 +6121,12 @@ packages: object-visit: 1.0.1 dev: true + /marked@4.3.0: + resolution: {integrity: sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==} + engines: {node: '>= 12'} + hasBin: true + dev: true + /md5.js@1.3.5: resolution: {integrity: sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==} dependencies: @@ -6223,6 +6257,13 @@ packages: brace-expansion: 1.1.11 dev: true + /minimatch@9.0.3: + resolution: {integrity: sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==} + engines: {node: '>=16 || 14 >=14.17'} + dependencies: + brace-expansion: 2.0.1 + dev: true + /minimist-options@4.1.0: resolution: {integrity: sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==} engines: {node: '>= 6'} @@ -6353,6 +6394,7 @@ packages: /node-fetch@2.6.1: resolution: {integrity: sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==} engines: {node: 4.x || >=6.0.0} + dev: false /node-fetch@2.6.12: resolution: {integrity: sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==} @@ -7300,6 +7342,15 @@ packages: dev: true optional: true + /shiki@0.14.5: + resolution: {integrity: sha512-1gCAYOcmCFONmErGTrS1fjzJLA7MGZmKzrBNX7apqSwhyITJg2O102uFzXUeBxNnEkDA9vHIKLyeKq0V083vIw==} + dependencies: + ansi-sequence-parser: 1.1.1 + jsonc-parser: 3.2.0 + vscode-oniguruma: 1.7.0 + vscode-textmate: 8.0.0 + dev: true + /side-channel@1.0.4: resolution: {integrity: sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==} dependencies: @@ -7861,7 +7912,7 @@ packages: bs-logger: 0.2.6 buffer-from: 1.1.2 fast-json-stable-stringify: 2.1.0 - jest: 26.0.1(ts-node@10.9.1) + jest: 26.0.1 jest-util: 26.6.2 json5: 2.2.3 lodash: 4.17.21 @@ -8164,6 +8215,20 @@ packages: resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} dev: true + /typedoc@0.25.3(typescript@4.9.4): + resolution: {integrity: sha512-Ow8Bo7uY1Lwy7GTmphRIMEo6IOZ+yYUyrc8n5KXIZg1svpqhZSWgni2ZrDhe+wLosFS8yswowUzljTAV/3jmWw==} + engines: {node: '>= 16'} + hasBin: true + peerDependencies: + typescript: 4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x + dependencies: + lunr: 2.3.9 + marked: 4.3.0 + minimatch: 9.0.3 + shiki: 0.14.5 + typescript: 4.9.4 + dev: true + /typescript@4.9.4: resolution: {integrity: sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==} engines: {node: '>=4.2.0'} @@ -8344,6 +8409,14 @@ packages: resolution: {integrity: sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==} dev: true + /vscode-oniguruma@1.7.0: + resolution: {integrity: sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==} + dev: true + + /vscode-textmate@8.0.0: + resolution: {integrity: sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==} + dev: true + /w3c-hr-time@1.0.2: resolution: {integrity: sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==} deprecated: Use your platform's native performance.now() and performance.timeOrigin. @@ -8615,7 +8688,3 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} dev: true - -settings: - autoInstallPeers: false - excludeLinksFromLockfile: false diff --git a/tsconfig.base.json b/tsconfig.base.json index 3ae27a0e33..8194814911 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -6,6 +6,7 @@ "moduleResolution": "node", "alwaysStrict": true, "declaration": true, + "declarationMap": true, "preserveSymlinks": true, "preserveWatchOutput": true, "pretty": false, diff --git a/tsconfig.node.json b/tsconfig.node.json index b4f7644289..976778f200 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -5,5 +5,5 @@ "es2015", "esnext" ], - } + }, } diff --git a/typedoc.json b/typedoc.json new file mode 100644 index 0000000000..47bca6adcf --- /dev/null +++ b/typedoc.json @@ -0,0 +1,26 @@ +{ + "includeVersion": true, + "entryPoints": [ + "packages/near-api-js", + "packages/accounts", + "packages/biometric-ed25519", + "packages/crypto", + "packages/iframe-rpc", + "packages/keystores", + "packages/keystores-browser", + "packages/keystores-node", + "packages/providers", + "packages/signers", + "packages/transactions", + "packages/types", + "packages/utils", + "packages/wallet-account" + ], + "entryPointStrategy": "packages", + "githubPages": true, + "validation": { + "notExported": false + }, + "out": "docs", + "readme": "./docs/README_TYPEDOC.md" +} \ No newline at end of file From 44c6b9d47f9d64a4f12fa16fe5de98535b924ab0 Mon Sep 17 00:00:00 2001 From: gagdiez Date: Thu, 30 Nov 2023 20:02:50 +0100 Subject: [PATCH 3/4] fix: allow workflow to write content --- .github/workflows/typedoc-generator.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/typedoc-generator.yml b/.github/workflows/typedoc-generator.yml index a3d7b03d62..8b6f63970f 100644 --- a/.github/workflows/typedoc-generator.yml +++ b/.github/workflows/typedoc-generator.yml @@ -16,6 +16,8 @@ jobs: deploy: concurrency: ci-${{ github.ref }} runs-on: ubuntu-latest + permissions: + contents: write steps: - uses: actions/checkout@v4 From ecf29e2d56611a7773c79d5bb5bd20c8b7e738ea Mon Sep 17 00:00:00 2001 From: Den <41162202+denbite@users.noreply.github.com> Date: Wed, 6 Dec 2023 20:42:10 +0200 Subject: [PATCH 4/4] feat: Make users capable of integrating modern logging library (#1215) --- .changeset/nervous-bugs-doubt.md | 9 +++ MIGRATION.md | 2 + packages/accounts/src/account.ts | 10 ++- packages/accounts/src/account_2fa.ts | 7 +- packages/accounts/src/account_multisig.ts | 3 +- packages/accounts/src/contract.ts | 6 +- packages/accounts/test/account.test.js | 41 +++++++----- packages/near-api-js/src/connect.ts | 24 +++++-- packages/near-api-js/src/utils/index.ts | 2 + packages/near-api-js/src/utils/logger.ts | 1 + packages/providers/src/fetch_json.ts | 9 ++- packages/providers/src/json-rpc-provider.ts | 5 +- packages/utils/src/errors/errors.ts | 8 ++- packages/utils/src/index.ts | 1 + packages/utils/src/logger/console.logger.ts | 64 ++++++++++++++++++ packages/utils/src/logger/index.ts | 2 + packages/utils/src/logger/interface.ts | 33 ++++++++++ packages/utils/src/logger/logger.ts | 73 +++++++++++++++++++++ packages/utils/src/logging.ts | 17 ++--- packages/utils/test/logger.test.js | 59 +++++++++++++++++ packages/wallet-account/src/near.ts | 5 ++ 21 files changed, 321 insertions(+), 60 deletions(-) create mode 100644 .changeset/nervous-bugs-doubt.md create mode 100644 packages/near-api-js/src/utils/logger.ts create mode 100644 packages/utils/src/logger/console.logger.ts create mode 100644 packages/utils/src/logger/index.ts create mode 100644 packages/utils/src/logger/interface.ts create mode 100644 packages/utils/src/logger/logger.ts create mode 100644 packages/utils/test/logger.test.js diff --git a/.changeset/nervous-bugs-doubt.md b/.changeset/nervous-bugs-doubt.md new file mode 100644 index 0000000000..dd3c6ce557 --- /dev/null +++ b/.changeset/nervous-bugs-doubt.md @@ -0,0 +1,9 @@ +--- +"near-api-js": minor +"@near-js/accounts": patch +"@near-js/providers": patch +"@near-js/utils": patch +"@near-js/wallet-account": patch +--- + +Internal logging library with capabilities for integration with modern logging libraries like Pino, Winston, etc diff --git a/MIGRATION.md b/MIGRATION.md index 5ab6f9e1b0..db45c788c9 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -276,6 +276,7 @@ const { format, logWarning, rpc_errors, + Logger } = utils; const { formatNearAmount, @@ -316,5 +317,6 @@ import { parseNearAmount, parseResultError, parseRpcError, + Logger } from '@near-js/utils'; ``` diff --git a/packages/accounts/src/account.ts b/packages/accounts/src/account.ts index 1c462d4202..0ce11cbeda 100644 --- a/packages/accounts/src/account.ts +++ b/packages/accounts/src/account.ts @@ -28,7 +28,7 @@ import { import { baseDecode, baseEncode, - logWarning, + Logger, parseResultError, DEFAULT_FUNCTION_CALL_GAS, printTxOutcomeLogs, @@ -223,12 +223,12 @@ export class Account { return await this.connection.provider.sendTransaction(signedTx); } catch (error) { if (error.type === 'InvalidNonce') { - logWarning(`Retrying transaction ${receiverId}:${baseEncode(txHash)} with new nonce.`); + Logger.warn(`Retrying transaction ${receiverId}:${baseEncode(txHash)} with new nonce.`); delete this.accessKeyByPublicKeyCache[publicKey.toString()]; return null; } if (error.type === 'Expired') { - logWarning(`Retrying transaction ${receiverId}:${baseEncode(txHash)} due to expired block hash`); + Logger.warn(`Retrying transaction ${receiverId}:${baseEncode(txHash)} due to expired block hash`); return null; } @@ -360,9 +360,7 @@ export class Account { * @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted */ async deleteAccount(beneficiaryId: string) { - if (!(typeof process === 'object' && process.env['NEAR_NO_LOGS'])) { - console.log('Deleting an account does not automatically transfer NFTs and FTs to the beneficiary address. Ensure to transfer assets before deleting.'); - } + Logger.log('Deleting an account does not automatically transfer NFTs and FTs to the beneficiary address. Ensure to transfer assets before deleting.'); return this.signAndSendTransaction({ receiverId: this.accountId, actions: [deleteAccount(beneficiaryId)] diff --git a/packages/accounts/src/account_2fa.ts b/packages/accounts/src/account_2fa.ts index a45d3ac0a9..6bfec76ef8 100644 --- a/packages/accounts/src/account_2fa.ts +++ b/packages/accounts/src/account_2fa.ts @@ -2,6 +2,7 @@ import { PublicKey } from '@near-js/crypto'; import { FinalExecutionOutcome, TypedError, FunctionCallPermissionView } from '@near-js/types'; import { fetchJson } from '@near-js/providers'; import { actionCreators } from '@near-js/transactions'; +import { Logger } from '@near-js/utils' import BN from 'bn.js'; import { SignAndSendTransactionOptions } from './account'; @@ -84,7 +85,7 @@ export class Account2FA extends AccountMultisig { deployContract(contractBytes), ]; const newFunctionCallActionBatch = actions.concat(functionCall('new', newArgs, MULTISIG_GAS, MULTISIG_DEPOSIT)); - console.log('deploying multisig contract for', accountId); + Logger.log('deploying multisig contract for', accountId); const { stateStatus: multisigStateStatus } = await this.checkMultisigCodeAndStateStatus(contractBytes); switch (multisigStateStatus) { @@ -185,7 +186,7 @@ export class Account2FA extends AccountMultisig { ...(await this.get2faDisableKeyConversionActions()), deployContract(contractBytes), ]; - console.log('disabling 2fa for', this.accountId); + Logger.log('disabling 2fa for', this.accountId); return await this.signAndSendTransaction({ receiverId: this.accountId, actions @@ -217,7 +218,7 @@ export class Account2FA extends AccountMultisig { // TODO: Parse error from result for real (like in normal account.signAndSendTransaction) return result; } catch (e) { - console.warn('Error validating security code:', e); + Logger.warn('Error validating security code:', e); if (e.toString().includes('invalid 2fa code provided') || e.toString().includes('2fa code not valid')) { return await this.promptAndVerify(); } diff --git a/packages/accounts/src/account_multisig.ts b/packages/accounts/src/account_multisig.ts index cfca45354c..c159b4b70c 100644 --- a/packages/accounts/src/account_multisig.ts +++ b/packages/accounts/src/account_multisig.ts @@ -1,5 +1,6 @@ import { Action, actionCreators } from '@near-js/transactions'; import { FinalExecutionOutcome } from '@near-js/types'; +import { Logger } from '@near-js/utils'; import { Account, SignAndSendTransactionOptions } from './account'; import { Connection } from './connection'; @@ -156,7 +157,7 @@ export class AccountMultisig extends Account { actions: [functionCall('delete_request', { request_id: requestIdToDelete }, MULTISIG_GAS, MULTISIG_DEPOSIT)] }); } catch (e) { - console.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.'); + Logger.warn('Attempt to delete an earlier request before 15 minutes failed. Will try again.'); } } } diff --git a/packages/accounts/src/contract.ts b/packages/accounts/src/contract.ts index 77e7982aaf..1acfb0f2b6 100644 --- a/packages/accounts/src/contract.ts +++ b/packages/accounts/src/contract.ts @@ -1,4 +1,4 @@ -import { getTransactionLastResult } from '@near-js/utils'; +import { getTransactionLastResult, Logger } from '@near-js/utils'; import { ArgumentTypeError, PositionalArgsError } from '@near-js/types'; import { LocalViewExecution } from './local-view-execution'; import Ajv from 'ajv'; @@ -194,8 +194,8 @@ export class Contract { ...options, }); } catch (error) { - console.warn(`Local view execution failed with: "${error.message}"`); - console.warn(`Fallback to normal RPC call`); + Logger.warn(`Local view execution failed with: "${error.message}"`); + Logger.warn(`Fallback to normal RPC call`); } } diff --git a/packages/accounts/test/account.test.js b/packages/accounts/test/account.test.js index 5a6220c079..9b32d4b4d3 100644 --- a/packages/accounts/test/account.test.js +++ b/packages/accounts/test/account.test.js @@ -1,4 +1,4 @@ -const { getTransactionLastResult } = require('@near-js/utils'); +const { getTransactionLastResult, Logger } = require('@near-js/utils'); const { actionCreators } = require('@near-js/transactions'); const { TypedError } = require('@near-js/types'); const BN = require('bn.js'); @@ -90,19 +90,23 @@ test('findAccessKey returns the same access key when fetched simultaneously', as }); describe('errors', () => { - let oldLog; let logs; - beforeEach(async () => { - oldLog = console.log; - logs = []; - console.log = function () { - logs.push(Array.from(arguments).join(' ')); + beforeAll(async () => { + const custom = { + log: (...args) => { + logs.push(args.join(' ')); + }, + warn: () => {}, + error: () => {}, }; + + Logger.overrideLogger(custom); }); - afterEach(async () => { - console.log = oldLog; + beforeEach(async () => { + logs = []; + }); test('create existing account', async() => { @@ -112,7 +116,6 @@ describe('errors', () => { }); describe('with deploy contract', () => { - let oldLog; let logs; let contractId = testUtils.generateUniqueString('test_contract'); let contract; @@ -125,18 +128,20 @@ describe('with deploy contract', () => { viewMethods: ['hello', 'getValue', 'returnHiWithLogs'], changeMethods: ['setValue', 'generateLogs', 'triggerAssert', 'testSetRemove', 'crossContract'] }); - }); - beforeEach(async () => { - oldLog = console.log; - logs = []; - console.log = function () { - logs.push(Array.from(arguments).join(' ')); + const custom = { + log: (...args) => { + logs.push(args.join(' ')); + }, + warn: () => {}, + error: () => {}, }; + + Logger.overrideLogger(custom); }); - afterEach(async () => { - console.log = oldLog; + beforeEach(async () => { + logs = []; }); test('cross-contact assertion and panic', async () => { diff --git a/packages/near-api-js/src/connect.ts b/packages/near-api-js/src/connect.ts index 656450bace..64777da84e 100644 --- a/packages/near-api-js/src/connect.ts +++ b/packages/near-api-js/src/connect.ts @@ -20,12 +20,21 @@ * }) * } * ``` + * @example disable library logs + * ```js + * async function initNear() { + * const near = await connect({ + * networkId: 'testnet', + * nodeUrl: 'https://rpc.testnet.near.org', + * logger: false + * }) + * } * @module connect */ import { readKeyFile } from './key_stores/unencrypted_file_system_keystore'; import { InMemoryKeyStore, MergeKeyStore } from './key_stores'; import { Near, NearConfig } from './near'; -import { logWarning } from './utils'; +import { Logger } from '@near-js/utils'; export interface ConnectConfig extends NearConfig { /** @@ -38,6 +47,13 @@ export interface ConnectConfig extends NearConfig { * Initialize connection to Near network. */ export async function connect(config: ConnectConfig): Promise { + if (config.logger === false) { + // disables logging + Logger.overrideLogger(undefined); + } else if (config.logger !== undefined && config.logger !== null) { + Logger.overrideLogger(config.logger); + } + // Try to find extra key in `KeyPath` if provided. if (config.keyPath && (config.keyStore || config.deps?.keyStore)) { try { @@ -54,12 +70,10 @@ export async function connect(config: ConnectConfig): Promise { keyPathStore, config.keyStore || config.deps?.keyStore ], { writeKeyStoreIndex: 1 }); - if (!(typeof process === 'object' && process.env['NEAR_NO_LOGS'])) { - console.log(`Loaded master account ${accountKeyFile[0]} key from ${config.keyPath} with public key = ${keyPair.getPublicKey()}`); - } + Logger.log(`Loaded master account ${accountKeyFile[0]} key from ${config.keyPath} with public key = ${keyPair.getPublicKey()}`); } } catch (error) { - logWarning(`Failed to load master account key from ${config.keyPath}: ${error}`); + Logger.warn(`Failed to load master account key from ${config.keyPath}: ${error}`); } } return new Near(config); diff --git a/packages/near-api-js/src/utils/index.ts b/packages/near-api-js/src/utils/index.ts index 69b355258f..43f784c3da 100644 --- a/packages/near-api-js/src/utils/index.ts +++ b/packages/near-api-js/src/utils/index.ts @@ -8,6 +8,7 @@ import * as rpc_errors from './rpc_errors'; import { PublicKey, KeyPair, KeyPairEd25519 } from './key_pair'; import { logWarning } from './errors'; +import { Logger } from './logger'; export { key_pair, @@ -20,4 +21,5 @@ export { KeyPairEd25519, rpc_errors, logWarning, + Logger }; diff --git a/packages/near-api-js/src/utils/logger.ts b/packages/near-api-js/src/utils/logger.ts new file mode 100644 index 0000000000..92523889fd --- /dev/null +++ b/packages/near-api-js/src/utils/logger.ts @@ -0,0 +1 @@ +export { Logger } from '@near-js/utils'; diff --git a/packages/providers/src/fetch_json.ts b/packages/providers/src/fetch_json.ts index 57ee7a9766..1e8836f1eb 100644 --- a/packages/providers/src/fetch_json.ts +++ b/packages/providers/src/fetch_json.ts @@ -1,4 +1,5 @@ import { TypedError } from '@near-js/types'; +import { Logger } from '@near-js/utils'; import createError from 'http-errors'; import { exponentialBackoff } from './exponential-backoff'; @@ -16,8 +17,6 @@ export interface ConnectionInfo { headers?: { [key: string]: string | number }; } -const logWarning = (...args) => !(typeof process === 'object' && process.env['NEAR_NO_LOGS']) && console.warn(...args); - export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, json?: string): Promise { let connectionInfo: ConnectionInfo = { url: null }; if (typeof (connectionInfoOrUrl) === 'string') { @@ -36,10 +35,10 @@ export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, js }); if (!response.ok) { if (response.status === 503) { - logWarning(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`); + Logger.warn(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`); return null; } else if (response.status === 408) { - logWarning(`Retrying HTTP request for ${connectionInfo.url} as the previous connection was unused for some time`); + Logger.warn(`Retrying HTTP request for ${connectionInfo.url} as the previous connection was unused for some time`); return null; } throw createError(response.status, await response.text()); @@ -47,7 +46,7 @@ export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, js return response; } catch (error) { if (error.toString().includes('FetchError') || error.toString().includes('Failed to fetch')) { - logWarning(`Retrying HTTP request for ${connectionInfo.url} because of error: ${error}`); + Logger.warn(`Retrying HTTP request for ${connectionInfo.url} because of error: ${error}`); return null; } throw error; diff --git a/packages/providers/src/json-rpc-provider.ts b/packages/providers/src/json-rpc-provider.ts index 0e1cfa2243..22ccd07281 100644 --- a/packages/providers/src/json-rpc-provider.ts +++ b/packages/providers/src/json-rpc-provider.ts @@ -8,6 +8,7 @@ import { baseEncode, getErrorTypeFromErrorMessage, + Logger, parseRpcError, } from '@near-js/utils'; import { @@ -372,9 +373,7 @@ export class JsonRpcProvider extends Provider { return response; } catch (error) { if (error.type === 'TimeoutError') { - if (!(typeof process === 'object' && process.env['NEAR_NO_LOGS'])) { - console.warn(`Retrying request to ${method} as it has timed out`, params); - } + Logger.warn(`Retrying request to ${method} as it has timed out`, params); return null; } diff --git a/packages/utils/src/errors/errors.ts b/packages/utils/src/errors/errors.ts index 8173ea2e65..c13d04657b 100644 --- a/packages/utils/src/errors/errors.ts +++ b/packages/utils/src/errors/errors.ts @@ -1,5 +1,7 @@ +import { Logger } from '../logger'; + +/** @deprecated */ export function logWarning(...args: any[]): void { - if (!(typeof process === 'object' && process.env['NEAR_NO_LOGS'])){ - console.warn(...args); - } + const [message, ...optinalParams] = args; + Logger.warn(message, ...optinalParams); } diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index acf0293d22..6fb6401bf4 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -4,3 +4,4 @@ export * from './format'; export * from './logging'; export * from './provider'; export * from './validators'; +export * from './logger'; diff --git a/packages/utils/src/logger/console.logger.ts b/packages/utils/src/logger/console.logger.ts new file mode 100644 index 0000000000..efc826493b --- /dev/null +++ b/packages/utils/src/logger/console.logger.ts @@ -0,0 +1,64 @@ +import type { LoggerService, LogLevel } from './interface'; + +export class ConsoleLogger implements LoggerService { + public constructor(protected readonly logLevels: LogLevel[]) {} + + public isLevelEnabled = (level: LogLevel): boolean => { + return this.logLevels.includes(level); + }; + + private print( + level: LogLevel, + message: any, + ...optionalParams: any[] + ): void { + switch (level) { + case 'error': + case 'fatal': + return console.error(message, ...optionalParams); + case 'warn': + return console.warn(message, ...optionalParams); + case 'log': + return console.log(message, ...optionalParams); + case 'debug': + case 'verbose': + return console.debug(message, ...optionalParams); + } + } + + verbose(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('verbose')) return; + + this.print('verbose', message, ...optionalParams); + } + + debug(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('debug')) return; + + this.print('debug', message, ...optionalParams); + } + + log(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('log')) return; + + this.print('log', message, ...optionalParams); + } + + warn(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('warn')) return; + + this.print('warn', message, ...optionalParams); + } + + error(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('error')) return; + + this.print('error', message, ...optionalParams); + } + + fatal(message: any, ...optionalParams: any[]) { + if (!this.isLevelEnabled('fatal')) return; + + this.print('fatal', message, ...optionalParams); + } +} diff --git a/packages/utils/src/logger/index.ts b/packages/utils/src/logger/index.ts new file mode 100644 index 0000000000..70a0a1249d --- /dev/null +++ b/packages/utils/src/logger/index.ts @@ -0,0 +1,2 @@ +export { Logger } from './logger'; +export type { LoggerService } from './interface'; diff --git a/packages/utils/src/logger/interface.ts b/packages/utils/src/logger/interface.ts new file mode 100644 index 0000000000..8c1b15429e --- /dev/null +++ b/packages/utils/src/logger/interface.ts @@ -0,0 +1,33 @@ +export type LogLevel = 'log' | 'error' | 'warn' | 'debug' | 'verbose' | 'fatal'; + +export interface LoggerService { + /** + * Write a 'log' level log. + */ + log(message: any, ...optionalParams: any[]): any; + + /** + * Write an 'error' level log. + */ + error(message: any, ...optionalParams: any[]): any; + + /** + * Write a 'warn' level log. + */ + warn(message: any, ...optionalParams: any[]): any; + + /** + * Write a 'debug' level log. + */ + debug?(message: any, ...optionalParams: any[]): any; + + /** + * Write a 'verbose' level log. + */ + verbose?(message: any, ...optionalParams: any[]): any; + + /** + * Write a 'fatal' level log. + */ + fatal?(message: any, ...optionalParams: any[]): any; +} diff --git a/packages/utils/src/logger/logger.ts b/packages/utils/src/logger/logger.ts new file mode 100644 index 0000000000..d528a6792d --- /dev/null +++ b/packages/utils/src/logger/logger.ts @@ -0,0 +1,73 @@ +import { ConsoleLogger } from './console.logger'; +import type { LogLevel, LoggerService } from './interface'; + +const DEFAULT_LOG_LEVELS: LogLevel[] = [ + 'verbose', + 'debug', + 'log', + 'warn', + 'error', + 'fatal', +]; + +const DEFAULT_LOGGER = + typeof process === 'object' && process.env.NEAR_NO_LOGS + ? undefined + : new ConsoleLogger(DEFAULT_LOG_LEVELS); + +/** + * Used to log the library messages + */ +export class Logger { + protected static instanceRef?: LoggerService = DEFAULT_LOGGER; + + public static overrideLogger = (logger?: LoggerService): void => { + this.instanceRef = logger; + }; + + /** + * Write an 'error' level log. + */ + public static error(message: any, stack?: string): void; + public static error(message: any, ...optionalParams: [string, ...any[]]): void; + public static error(message: any, ...optionalParams: any[]) { + this.instanceRef?.error(message, ...optionalParams); + } + + /** + * Write a 'log' level log. + */ + public static log(message: any, ...optionalParams: any[]) { + this.instanceRef?.log(message, ...optionalParams); + } + + /** + * Write a 'warn' level log. + */ + public static warn(message: any, ...optionalParams: any[]) { + this.instanceRef?.warn(message, ...optionalParams); + } + + /** + * Write a 'debug' level log. + */ + public static debug(message: any, ...optionalParams: any[]) { + this.instanceRef?.debug?.(message, ...optionalParams); + } + + /** + * Write a 'verbose' level log. + */ + public static verbose(message: any, ...optionalParams: any[]) { + this.instanceRef?.verbose?.(message, ...optionalParams); + } + + /** + * Write a 'fatal' level log. + */ + public static fatal(message: any, stack?: string): void; + public static fatal(message: any, ...optionalParams: [string, ...any[]]): void; + public static fatal(message: any, ...optionalParams: any[]) { + this.instanceRef?.fatal?.(message, ...optionalParams); + } +} diff --git a/packages/utils/src/logging.ts b/packages/utils/src/logging.ts index 4b134562b7..f80d15096d 100644 --- a/packages/utils/src/logging.ts +++ b/packages/utils/src/logging.ts @@ -1,8 +1,7 @@ import { FinalExecutionOutcome } from '@near-js/types'; import { parseRpcError } from './errors'; - -const SUPPRESS_LOGGING = !!(typeof process === 'object' && process.env.NEAR_NO_LOGS); +import { Logger } from './logger'; /** * Parse and print details from a query execution response @@ -14,10 +13,6 @@ export function printTxOutcomeLogsAndFailures({ contractId, outcome, }: { contractId: string, outcome: FinalExecutionOutcome }) { - if (SUPPRESS_LOGGING) { - return; - } - const flatLogs = [outcome.transaction_outcome, ...outcome.receipts_outcome] .reduce((acc, it) => { const isFailure = typeof it.outcome.status === 'object' && typeof it.outcome.status.Failure === 'object'; @@ -35,7 +30,7 @@ export function printTxOutcomeLogsAndFailures({ }, []); for (const result of flatLogs) { - console.log(`Receipt${result.receiptIds.length > 1 ? 's' : ''}: ${result.receiptIds.join(', ')}`); + Logger.log(`Receipt${result.receiptIds.length > 1 ? 's' : ''}: ${result.receiptIds.join(', ')}`); printTxOutcomeLogs({ contractId, logs: result.logs, @@ -43,7 +38,7 @@ export function printTxOutcomeLogsAndFailures({ }); if (result.failure) { - console.warn(`\tFailure [${contractId}]: ${result.failure}`); + Logger.warn(`\tFailure [${contractId}]: ${result.failure}`); } } } @@ -60,11 +55,7 @@ export function printTxOutcomeLogs({ logs, prefix = '', }: { contractId: string, logs: string[], prefix?: string }) { - if (SUPPRESS_LOGGING) { - return; - } - for (const log of logs) { - console.log(`${prefix}Log [${contractId}]: ${log}`); + Logger.log(`${prefix}Log [${contractId}]: ${log}`); } } diff --git a/packages/utils/test/logger.test.js b/packages/utils/test/logger.test.js new file mode 100644 index 0000000000..d9fbeea0ce --- /dev/null +++ b/packages/utils/test/logger.test.js @@ -0,0 +1,59 @@ +const { Logger } = require('../lib'); + +describe('logger', () => { + let logs; + + beforeEach(async () => { + logs = []; + + const custom = { + verbose: (...args) => { + logs.push(args.join('')); + }, + debug: (...args) => { + logs.push(args.join('')); + }, + log: (...args) => { + logs.push(args.join('')); + }, + warn: (...args) => { + logs.push(args.join('')); + }, + error: (...args) => { + logs.push(args.join('')); + }, + fatal: (...args) => { + logs.push(args.join('')); + }, + }; + + Logger.overrideLogger(custom); + }); + + test('test logger can be overrided', async () => { + Logger.log('111'); + Logger.debug('11s1'); + Logger.warn('1111'); + Logger.error('1131'); + Logger.log('112'); + + expect(logs.length).toBe(5); + }); + + test('test logger can be disabled', async () => { + Logger.overrideLogger(undefined); + + Logger.log('111'); + Logger.log('222'); + + expect(logs.length).toBe(0); + }); + + test('test logged data is accurate', async () => { + Logger.log('lol'); + expect(logs[0]).toEqual('lol'); + + Logger.log('his name is ', 'test'); + expect(logs[1]).toEqual('his name is test'); + }); +}); diff --git a/packages/wallet-account/src/near.ts b/packages/wallet-account/src/near.ts index a67c621af0..9762fa9be1 100644 --- a/packages/wallet-account/src/near.ts +++ b/packages/wallet-account/src/near.ts @@ -17,6 +17,7 @@ import { import { PublicKey } from '@near-js/crypto'; import { KeyStore } from '@near-js/keystores'; import { Signer } from '@near-js/signers'; +import { LoggerService } from '@near-js/utils'; import BN from 'bn.js'; export interface NearConfig { @@ -76,6 +77,10 @@ export interface NearConfig { * Backward-compatibility for older versions */ deps?: { keyStore: KeyStore }; + /** + * Specifies the logger to use. Pass `false` to turn off logging. + */ + logger?: LoggerService | false; } /**