eosjs

repository·master·Indexed 23 days ago

https://github.com/eosio/eosjs

A JavaScript API for integrating with EOSIO-based blockchains via the EOSIO RPC API. It enables developers to interact with the blockchain, sign transactions, and manage account actions in both browser and Node.js environments. The library provides the JsonRpc object for read-only queries and the Api object for submitting state-changing transactions.

Tokens
30.2K
Snippets
70
Records
142
Agent score
79%

What's inside eosjs

  1. What is a SignatureProvider and how does it work?

    master

    A SignatureProvider is an interface used by eosjs to handle the signing of transactions. It is responsible for taking a transaction and its associated chainId and returning the necessary cryptographic signatures.

    When the sign method of a SignatureProvider is called, it typically:

    1. Creates a buffer containing the chainId and the serializedTransaction.
    2. Uses an elliptic curve cryptography library (like eosjs-ecc) to sign that buffer using the private key that corresponds to the required public key(s) in the transaction.

    eosjs includes an example implementation called JsSignatureProvider. This implementation is intended for demonstration purposes only; it accepts a list of private keys as strings in its constructor. Warning: JsSignatureProvider is insecure and must not be used in production environments.

  2. What is a Signature Provider?

    master

    A Signature Provider is responsible for holding private keys and signing transactions.

    Security Warning: JsSignatureProvider is intended for development only and is not secure for browser use. In production, use a secure vault outside the webpage context to sign transactions.

    const defaultPrivateKey = "5JtUScZK2XEp3g9gh7F8bwtPTRAkASmNrrftmx4AxDKD5K4zDnr"; // bob
    const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);
  3. Implement a SignatureProvider for the Api constructor

    master

    The Api constructor requires a SignatureProvider which must implement the dist/eosjs-api-interfaces.SignatureProvider interface. This provider must contain the private keys corresponding to the actors and permission requirements of the actions being executed.

    Security Warning: In production, do not keep private keys in the webpage context. Use a secure vault outside of the webpage that implements the SignatureProvider interface to ensure security.

  4. Use the JsonRpc object for read-only blockchain queries

    master

    The JsonRpc object is used for interacting with the EOSIO Nodeos RPC API when signing is not required. It is the primary tool for retrieving information from the blockchain without performing state-changing transactions.

    Common use cases include:

    • Getting block information
    • Getting transaction information
    • Getting table information
    • Retrieving account details via get_account or ABIs via get_abi.

    JsonRpc uses a fetch library to issue requests to the endpoint specified during instantiation. You can provide your own fetch implementation if needed.

  5. Retrieve return values from smart contracts

    master

    When a smart contract returns values, they are available in the transaction object returned by api.transact().

    • The values are located in the transaction.processed.action_traces array.
    • The order of action_traces matches the order of actions in your transaction.
    • Within each action_trace, the deserialized return value is found in the return_value field.
  6. Use the Api object for submitting transactions

    master

    The Api object is used when you need to perform state-changing operations on an EOSIO-based blockchain, such as staking, creating accounts, or proposing multi-sig transactions.

    The core method for this object is transact. When you call transact, the Api object orchestrates several steps:

    1. Chain ID Verification: Checks if a chainId was provided in the constructor; if not, it fetches it using JsonRpc.get_info.
    2. TAPOS Configuration: Determines the reference block using expireSeconds and either blocksBehind or useLastIrreversible.
    3. ABI Retrieval: Fetches necessary ABIs if the transaction requires signing.
    4. Serialization: Serializes actions and the full transaction using eosjs-serialize.
    5. Signing: Optionally signs the transaction using a signatureProvider and the chainId.
    6. Compression: Optionally compresses the transaction using zlib.
    7. Broadcasting: Broadcasts the final transaction via JsonRpc.push_transaction.
  7. Perform read-only transactions

    master

    To perform queries that do not change state, use the readOnlyTrx configuration option in api.transact(). This sends the transaction through the push_ro_transaction endpoint in the chain_api.

    Note: Even if the transaction contains actions that would normally change data, the push_ro_transaction endpoint will roll back any changes.

    Configuration Options

    • readOnlyTrx: true: Enables read-only mode.
    • returnFailureTraces: true: Enables returning a trace message if the transaction fails (only available for read-only transactions).
  8. Construct the proposeInput object for multi-sig

    master

    The proposeInput object is the data payload for the propose action on the eosio.msig account. It requires a proposer, a proposal_name, a list of requested signers, and a trx object. The trx object must contain the actions field, which is populated with the output from api.serializeActions().

    const proposeInput = {
        proposer: 'useraaaaaaaa',
        proposal_name: 'changeowner',
        requested: [
          {
            actor: 'useraaaaaaaa',
            permission: 'active'
          },
          {
            actor: 'userbbbbbbbb',
            permission: 'active'
          }
        ],
        trx: {
          expiration: '2019-09-14T16:39:15',
          ref_block_num: 0,
          ref_block_prefix: 0,
          max_net_usage_words: 0,
          max_cpu_usage_ms: 0,
          delay_sec: 0,
          context_free_actions: [],
          actions: serialized_actions,
          transaction_extensions: []
        }
      };
  9. Get block information using get_block

    master

    To retrieve information about a specific block, call the get_block method on your RPC object. You must provide the block number as a required argument. The method returns the block data as a JSON object containing details such as the timestamp, producer, block ID, and transactions.

    (async () => { 
      await rpc.get_block(1) //get the first block
    })();
  10. Set a resource payer for a transaction

    master

    To sponsor resources for a transaction (allowing a service or application to pay for a user's transaction resources), add a resource_payer object to your transaction object. This feature requires the RESOURCE_PAYER protocol feature to be enabled on the chain (available since nodeos v2.2).

    The resource_payer object must include the following fields:

    • payer: The account name of the entity paying for the resources.
    • max_net_bytes: The maximum network bandwidth to be used.
    • max_cpu_us: The maximum CPU time (in microseconds) to be used.
    • max_memory_bytes: The maximum memory to be used.

    Note on Authorization: Because both the transaction user and the payer are involved, the transaction must be signed by both the user's account and the payer's account. A common workflow is to have the user's wallet sign the transaction first, followed by the service/application signing it before sending it to the node.

    {
        resource_payer: {
            payer: 'alice',
            max_net_bytes: 4096,
            max_cpu_us: 400,
            max_memory_bytes: 0
        },
        actions: [{
            account: 'eosio.token',
            name: 'transfer',
            authorization: [{
                actor: 'bob',
                permission: 'active',
            }, {
                actor: 'alice',
                permission: 'active',
            }],
            data: {
                from: 'bob',
                to: 'alice',
                quantity: '0.0001 SYS',
                memo: 'resource payer',
            },
        }]
    }
  11. Initialize JsonRpc and Api

    master

    To interact with the blockchain, first initialize a JsonRpc instance with the endpoint URL. If running in Node.js, you must provide a fetch implementation.

    Then, initialize the Api class. In Node.js, you must explicitly provide textDecoder and textEncoder. In modern browsers, these are typically available natively and can be omitted.