{"id":16017,"library":"eosjs","title":"EOSJS Library","description":"EOSJS is the official JavaScript library for interacting with EOSIO blockchain APIs. It provides a comprehensive set of tools for sending transactions, querying blockchain state, managing accounts, and performing cryptographic operations like signing and verifying. The current stable version is 22.1.0, which introduces support for read-only transactions within smart contracts via HTTP-RPC and action return values. Historically, the library has undergone significant internal changes, such as the switch from `eosjs-ecc` to the `elliptic` cryptography library in v21.0.2, while striving to maintain a stable public API. Releases often include security, stability, and miscellaneous fixes, with release candidates preceding major version bumps. It is a critical component for building applications that interact with EOSIO-based blockchains, offering robust TypeScript support and keeping pace with new blockchain features.","status":"active","version":"22.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/EOSIO/eosjs","tags":["javascript"],"install":[{"cmd":"npm install eosjs","lang":"bash","label":"npm"},{"cmd":"yarn add eosjs","lang":"bash","label":"yarn"},{"cmd":"pnpm add eosjs","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"HTTP client used internally for making RPC calls to EOSIO nodes in Node.js environments. Was explicitly mentioned in v21.0.4 for security fixes, implying its role as a key dependency.","package":"node-fetch","optional":false}],"imports":[{"note":"The primary class for making RPC calls to an EOSIO node. Recommended for ESM environments, use dynamic import or ensure proper CommonJS interoperability for CJS.","wrong":"const JsonRpc = require('eosjs').JsonRpc;","symbol":"JsonRpc","correct":"import { JsonRpc } from 'eosjs';"},{"note":"Main API class for building and pushing transactions. Requires a `SignatureProvider` and `JsonRpc` instance. Named import is standard. Accompanying types like `RpcInterfaces` are also commonly imported.","wrong":"import Api from 'eosjs';","symbol":"Api","correct":"import { Api, RpcInterfaces, SignatureProvider, TransactConfig } from 'eosjs';"},{"note":"Cryptographic utilities like `PrivateKey`, `PublicKey`, and `Signature` are typically exported from internal 'dist' paths (e.g., `eosjs/dist/eosjs-key-conversions`) in newer versions, or from `eosjs-ecc` in older versions. Always verify the exact path for your specific `eosjs` version.","wrong":"import { PrivateKey } from 'eosjs';","symbol":"PrivateKey","correct":"import { PrivateKey } from 'eosjs/dist/eosjs-key-conversions';"},{"note":"A common in-memory signature provider for development and testing. Like key conversion utilities, it resides in a specific `dist` submodule.","wrong":"import { JsSignatureProvider } from 'eosjs';","symbol":"JsSignatureProvider","correct":"import { JsSignatureProvider } from 'eosjs/dist/eosjs-jssig';"}],"quickstart":{"code":"import { JsonRpc } from 'eosjs';\nimport { Api, RpcInterfaces } from 'eosjs';\nimport { JsSignatureProvider } from 'eosjs/dist/eosjs-jssig'; // Example signature provider\nimport { TextEncoder, TextDecoder } from 'util'; // For Node.js environments\n\n// Configuration\nconst defaultPrivateKey = process.env.EOS_PRIVATE_KEY ?? ''; // Replace with an actual private key for signing, DO NOT expose in client-side code.\nconst rpcEndpoint = 'https://eos.greymass.com'; // Example public EOS mainnet endpoint\n\n// 1. Setup RPC client\nconst rpc = new JsonRpc(rpcEndpoint, { fetch }); // Using global fetch or node-fetch in Node.js\n\n// 2. Setup SignatureProvider (required even for read-only if you intend to send transactions later)\n// For demonstration, using a JS-based signature provider. In production, consider more secure options.\nconst signatureProvider = new JsSignatureProvider([defaultPrivateKey]);\n\n// 3. Setup API client\nconst api = new Api({\n    rpc,\n    signatureProvider,\n    textDecoder: new TextDecoder(), // Required for Node.js\n    textEncoder: new TextEncoder(), // Required for Node.js\n});\n\nasync function runExample() {\n    try {\n        console.log(`Querying a public contract table on ${rpcEndpoint}...`);\n\n        // Example: Get 'stat' table from 'eosio.token' contract for 'EOS' symbol\n        const tableRows = await rpc.get_table_rows({\n            json: true,\n            code: 'eosio.token',\n            scope: 'EOS',\n            table: 'stat',\n            lower_bound: null,\n            upper_bound: null,\n            limit: 1,\n        });\n\n        console.log('Table Rows (eosio.token, EOS, stat):', JSON.stringify(tableRows, null, 2));\n\n        // Example of pushing a transaction (requires a valid private key and account for 'youraccount')\n        // This part is commented out as it requires a real key and funded account to execute.\n        /*\n        if (defaultPrivateKey && defaultPrivateKey !== '') {\n            console.log('Attempting to push a dummy transaction...');\n            const transactionResult = await api.transact({\n                actions: [{\n                    account: 'eosio.token',\n                    name: 'transfer',\n                    authorization: [{\n                        actor: 'youraccount', // Replace with your EOS account name\n                        permission: 'active',\n                    }],\n                    data: {\n                        from: 'youraccount',\n                        to: 'teamgreymass', // Example recipient\n                        quantity: '0.0001 EOS', // Use a small test amount\n                        memo: 'Test transfer from eosjs quickstart',\n                    },\n                }]\n            }, {\n                blocksBehind: 3,\n                expireSeconds: 30,\n            });\n            console.log('Transaction Result:', JSON.stringify(transactionResult, null, 2));\n        }\n        */\n\n    } catch (error) {\n        console.error('Error:', error);\n        if (error instanceof RpcInterfaces.RpcError) {\n            console.error('RPC Error details:', JSON.stringify(error.json, null, 2));\n        }\n    }\n}\n\nrunExample();","lang":"typescript","description":"Demonstrates how to initialize `eosjs` with `JsonRpc` and `Api`, perform a read-only query using `get_table_rows`, and provides a commented-out example of pushing a transaction."},"warnings":[{"fix":"Review the official EOSIO API plugin documentation and update your application's code to align with the new endpoints and TypeScript definitions introduced in EOSJS v22.0.0. Pay close attention to any custom API calls.","message":"EOSJS v22.0.0-rc2 (which became v22.0.0 stable) introduced new endpoints and TypeScript types for Nodeos API plugins. This can lead to type errors in existing TypeScript projects or incorrect endpoint usage if not updated carefully.","severity":"breaking","affected_versions":">=22.0.0"},{"fix":"Ensure your application does not rely on internal details of the previous `eosjs-ecc` library. If you have custom cryptographic handling or key format expectations, thoroughly test for compatibility with the new `elliptic` library. Most users should be unaffected if using only the public API.","message":"In EOSJS v21.0.2, the internal cryptographic library was switched from `eosjs-ecc` to `elliptic`. While the public API was largely maintained, projects that relied on internal specifics of `eosjs-ecc` or expected certain key/signature formats might experience breaking changes.","severity":"breaking","affected_versions":">=21.0.2"},{"fix":"For versions 21.0.x, ensure that if you set `shouldHash` to `false`, you are providing data that has already been correctly hashed externally. It is strongly recommended to upgrade to the latest stable version (22.x) to ensure all signing and recovery methods function as expected.","message":"Versions 21.0.3 and earlier had an issue with `sign`/`recover`/`verify` methods when the `shouldHash` argument was set to `false` while sending *unhashed* data, leading to incorrect cryptographic operations.","severity":"gotcha","affected_versions":"21.0.0 - 21.0.3"},{"fix":"Immediately upgrade to EOSJS v21.0.4 or higher to patch critical security vulnerabilities in the underlying dependencies. This is crucial for application security and supply chain integrity.","message":"EOSJS v21.0.4 addressed several identified security vulnerabilities in underlying dependencies, including `y18n`, `elliptic`, `node-notifier`, `ini`, and `node-fetch`. Older versions are susceptible to these vulnerabilities.","severity":"security","affected_versions":"<21.0.4"},{"fix":"Prefer `import` statements and configure your project for ESM usage (e.g., by setting `\"type\": \"module\"` in `package.json`). If you must use CommonJS, explore dynamic `import()` or specific transpilation configurations, or consider sticking to older `eosjs` versions that offered better CJS compatibility if full CJS support is critical.","message":"Newer versions of `eosjs` are often developed with ECMAScript Modules (ESM) in mind, which can lead to import/export issues when used in CommonJS (CJS) environments with `require()`. This can manifest as `TypeError: (0, _eosjs.Api) is not a constructor` or similar.","severity":"gotcha","affected_versions":">=21.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"In Node.js, install `node-fetch` (e.g., `npm install node-fetch`) and pass it explicitly: `new JsonRpc(rpcEndpoint, { fetch: require('node-fetch') })` or `new JsonRpc(rpcEndpoint, { fetch })` after `import fetch from 'node-fetch'`.","cause":"The `JsonRpc` constructor expects a global `fetch` API, which is available in browsers but not natively in Node.js environments prior to Node 18 without a polyfill or explicit import.","error":"TypeError: fetch is not a function"},{"fix":"Ensure your `SignatureProvider` (e.g., `JsSignatureProvider`) is correctly initialized with the private key corresponding to the `actor` and `permission` specified in your transaction's `authorization` array. Double-check the private key and account name for accuracy and that the private key corresponds to the network you're connected to.","cause":"This error commonly occurs when attempting to push a transaction without a properly configured or working `SignatureProvider`, or if the provided private key is invalid or mismatched for the account's permissions defined in the transaction's `authorization` array.","error":"RpcError: unknown key: signature"},{"fix":"In Node.js, import `TextEncoder` and `TextDecoder` from the built-in `util` module: `import { TextEncoder, TextDecoder } from 'util';` and pass them to the `Api` constructor: `{ textDecoder: new TextDecoder(), textEncoder: new TextEncoder() }`.","cause":"The `Api` constructor requires `textDecoder` and `textEncoder` instances, which are global in modern browser environments but need to be explicitly imported or polyfilled in some Node.js environments.","error":"TypeError: Cannot read properties of undefined (reading 'textDecoder')"},{"fix":"Provide an instance of a `SignatureProvider` (e.g., `JsSignatureProvider` for testing purposes, or a more secure provider for production) to the `Api` constructor. If you only need to query blockchain state and do not intend to send transactions, you can use `JsonRpc` directly without `Api`.","cause":"The `Api` class constructor strictly requires an instance of a `SignatureProvider` to be passed, even if you only intend to perform read-only operations with the `Api` instance later. This ensures a consistent API interface.","error":"Error: Missing RpcInterfaces.SignatureProvider"}],"ecosystem":"npm"}