Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

chia-agent

Chia-Mine8.7kMIT14.5.0TypeScript support: included

chia rpc/websocket client library

chia, xch, crypto, rpc, websocket, pool, typescript

readme

chia-agent

npm version License: MIT

chia rpc/websocket client library for NodeJS.
Supports all RPC/Websocket API available at 2.5.1/2.5.2 of chia-blockchain.
(If you need previous version, search for the corresponding release here)

you can develop your own nodejs script with chia-agent to:

  • retrieve latest data from RPC servers like farmer, harvester, full_node, wallet, pool, data_layer, crawler.
  • send email when proof is found.
  • trigger scripts when target event is observed.
  • start/stop services.
  • write program to schedule plotting with javascript.
  • etc, etc, etc

Install

npm install chia-agent
# or
yarn add chia-agent

Compatibility

This code is compatible with:

API

There are 2 kinds of APIs in chia.
RPC API and Websocket API.

RPC API

RPC API is used to send message directly to chia services like farmer, harvester, full_node, wallet, data_layer, crawler.

RPC API is just an async function in a traditional request/response style.

const {RPCAgent, setLogLevel} = require("chia-agent");
const {get_plots} = require("chia-agent/api/rpc");
setLogLevel("debug");

const agent = new RPCAgent({
  service: "harvester",
});

const res = await get_plots(agent);
console.log(res.plots[0]);

/*
// sample output
{
  file_size: 108875876912,
  filename: 'M:\\plot-k32-yyyy-mm-dd-xx-xx-xxxxxxxxxxxxxxxxxxxxxxxxx.plot',
  plot_id: '...',
  plot_public_key: '0x934a93489...',
  pool_contract_puzzle_hash: null,
  pool_public_key: '0xb0aa9485c0d...',
  size: 32,
  time_modified: 1619540745
}
*/

// Or you can request RPC API via daemon websocket like this
const {getDaemon, setLogLevel} = require("chia-agent");
const {get_plots} = require("chia-agent/api/rpc");
const daemon = getDaemon();
await daemon.connect(); // connect to local daemon using config file.
const res = await get_plots(daemon);

Websocket API

Websocket API is used to connect to chia daemon.

With websocket API, you can request chia daemon to start/stop plotting or other services,
or capture various broadcast messages like:

  • Plotting progress
  • Farming info such as passed filter, proofs found, etc.
const {getDaemon, setLogLevel} = require("chia-agent");
const {on_new_farming_info} = require("chia-agent/api/ws");

setLogLevel("debug");

const daemon = getDaemon();
await daemon.connect(); // connect to local daemon using config file.
const unsubscribe = await on_new_farming_info(daemon, (e) => {
  console.log(e.data);
})

setTimeout(async () => {
  unsubscribe(); // Stop capturing message
  daemon.close();
}, 30*1000); // Disconnect after 30s passed.

/*
// sample output
{
  farming_info: {
    challenge_hash: '0x07228cf04e8877797adc1e0605018007def282548f009564b00286886e23e88b',
    passed_filter: 0,
    proofs: 0,
    signage_point: '0xfe1272a8e6659c0a3875cac37f8b170f1f85d47fecfee36d825dfae0b2a73a31',
    timestamp: 1621255822,
    total_plots: 299
  },
  success: true
}
 */

API Reference

See Documentation here

Examples

See documentation here

Here are some of those examples

Build from source

Once source files is build by npm run build:prod, files will be output to /dist directory.
Then the files/directories are published to npm registry.
Please note it does not upload files in project root to npm registry, but files inside '/dist'.

Read details here

Donation

For continuous development, please support me with donation xch1wr8g2k7cn55xvepmg480dsu2xhf4rz5ezghwwapulj7jxqcz9ztqqclwdj

changelog

Changelog

[14.5.0]

Changed

14.4.0

Changed

14.3.3

Changed

  • The default service name which Daemon client tries to register is now wallet_ui.
    Previously chia_agent service and optionally wallet_ui service were registered to chia-blockchain's Daemon.

14.3.2

Changed

  • Error logs are generated when
    • an error occurs during sending a message.
    • it receives a websocket message with unexpected format.
  • Debug logs are generated when ping/pong events are triggered.

14.3.1

Changed

  • Added a Host header when sending https request to a remote host.

14.3.0

Changed

14.2.2

Changed

  • For the log which is output when success property in API response is false, the log level is now INFO instead of ERROR.

14.2.1

Changed

  • daemon.connect() now returns a rejected promise on failure instead of throwing an uncaught exception
  • daemon.connect() now accepts connection timeout in milliseconds.

14.2.0

Note

14.1.0

Changed

-get_network_info RPC API is now commonized and available in addition to full_node and wallet.

14.0.0

Breaking change

  • When RPC API responds with success: false, its Promise now does reject. (Previously it does resolve)
  • At chia-blockchain@2.2.1, in chia/consensus/cost_calculator.py,
    NPCResult.cost was removed.
    As a result, the RPC APIs below might be incompatible between 2.1.4 and 2.2.1.
    • get_all_mempool_items of FullNode RPC API
    • get_mempool_item_by_tx_id of FullNode RPC API

      Changed

  • Loosened a type of agent to call RPC APIs. RPC APIs can be invoked with agent which just implements sendMessage method depicted as below.
    export interface APIAgent {
    sendMessage<M extends unknown>(
            destination: string,
            command: string,
            data?: Record<string, unknown>,
    ): Promise<M>;
    }
  • sp_source_data was added to NewSignagePoint
    As a result the following API responses were affected
  • include_signature_source_data was added to DeclareProofOfSpace As a result the following API responses were affected
  • foliage_block_data, foliage_transaction_block_data and rc_block_unfinished were added to RequestSignedValues
  • eligible_for_fast_forward was added to BundleCoinSpend
  • CHIP_0002_P2_DELEGATED_CONDITIONS was added to SigningMode
    As a result the following API responses were affected
  • Wallet RPC API
    • get_notifications
      • The types of request parameters were slightly changed
        • ids are now bytes32[] (previously str[])
        • start are now uint32 (previously int[])
        • end are now uint32 (previously int[])
      • The types of response parameters were slightly changed
        • id are now bytes32 (previously str)
        • message are now bytes (previously str)
    • get_offer_summary
      • The following properties were added to the response parameters
        • additions: str[]
        • removals: str[]
    • nft_get_info
      • The following properties were removed from the response parameters
        • ignore_size_limit

          Added

  • Added connectivity options for RPCAgent.
    • keepAlive (default: true)
    • keepAliveMsecs (default: 1000)
    • maxSockets (default: Infinity)
    • timeout (default: undefined) `typescript // Usage const {RPCAgent} = require("chia-agent"); const {get_plots} = require("chia-agent/api/rpc");

const agent = new RPCAgent({ service: "harvester", keepAlive: true, keepAliveMsecs: 3000, maxSockets: 1, // Avoid to set 1 if your requests may be sent in parallel. timeout: 5000, }); const res = await get_plots(agent);

- Added `httpsAgent`, `httpAgent` option for `RPCAgent`.
  You can now configure and inject your own `require('https').Agent` into `RPCAgent`.
```typescript
// Usage
const {Agent: HttpsAgent} = require("https"); // or const {Agent: HttpAgent} = require('http');
const {RPCAgent} = require("chia-agent");
const {get_plots} = require("chia-agent/api/rpc");

const httpsAgent = new HttpsAgent({
  host: "localhost",
  port: 8560,
  ca: ...,
  cert: ...,
  key: ...,
  rejectUnauthorized: false,
});
const agent = new RPCAgent({httpsAgent: httpsAgent}); // `new RPCAgent({httpAgent: httpAgent});` is also allowed.
const res = await get_plots(agent);

13.2.0

Added

13.1.0

Added

13.0.1

Changed

13.0.0

Breaking change

  • The format of PoolState) has been changed.
    • points_found_24h and points_acknowledged_24h are now Array<[uint32, uint64]> (they were Array<[float, uint64]>)
    • pool_errors_24h is now Array<[uint32, ErrorResponse]> (it was ErrorResponse[])
  • The following request properties of send_transaction and cat_spend Wallet RPC API were renamed
    • exclude_coin_amounts -> excluded_coin_amounts
    • exclude_coins -> excluded_coins
    • The previous property names(exclude_coin_amounts, exclude_coins) are preserved for backward compatibility
  • The following request properties of create_signed_transaction Wallet RPC API were renamed
    • exclude_coin_amounts -> excluded_coin_amounts
    • exclude_coins -> excluded_coins
    • The previous property name (exclude_coins) is preserved for backward compatibility
    • Unlike send_transaction and cat_spend, exclude_coin_amounts is removed by accident and not backward compatible.

      Changed

  • Daemon WebSocket API
    • start_plotting
      • The t2 option for chiapos plotter is now optional
      • Added compress option for bladebit plotter
      • Added cudaplot plot type for bladebit plotter
    • get_plotters
      • Added cuda_support property to bladebit install info
  • DataLayer RPC API
    • Renamed the type WsTakeOfferMessageDL to WsTakeOfferMessage
    • Renamed the type WsCancelOfferMessageDL to WsCancelOfferMessage
  • Farmer RPC API
    • get_pool_state
      • Added new properties
        • valid_partials_since_start
        • valid_partials_24h
        • invalid_partials_since_start
        • invalid_partials_24h
        • stale_partials_since_start
        • stale_partials_24h
        • missing_partials_since_start
        • missing_partials_24h
    • get_harvesters
      • Added total_effective_plot_size and harvesting_mode to harvesters in response
    • get_harvesters_summary
      • Added total_effective_plot_size and harvesting_mode to harvesters in response
  • Farmer WebSocket API
  • Harvester RPC API
    • get_plots
      • Added compression_level to response
  • FullNode RPC API
  • Wallet RPC API
    • get_farmed_amount
      • Added last_time_farmed to response
      • Added blocks_won to response

        Added

  • Daemon WebSocket API
  • Farmer WebSocket API
  • DataLayer RPC API
  • Harvester RPC API
    • get_harvester_config
    • update_harvester_config

      Fixed

    • Fixed documentation for plotter params.
      • bladebit_params => bladebit_ramplot_params
      • bladebit2_params => bladebit_diskplot_params
    • Fixed an issue where ts files related to the data layer RPC API had a circular dependency.
    • Fixed an issue where the following request parameters for the did_find_lost_did Wallet RPC API were missing.
      • recovery_list_hash
      • num_verification
      • metadata

12.1.0

Changed

12.0.1

Changed

  • Replace the npm module json-bigint to @chiamine/json-bigint.

    Fixed

  • Fixed the type of int64, uint64, uint128, uint512 to number | bigint.

12.0.0

Breaking change

Now the types of int64, uint64, uint128, uint512 are number | BigInt (Originally it was number).
When the numeric value is larger than Number.MAX_SAFE_INTEGER, the value is parsed as a BigInt.
You need to check a numeric member of API responses whether it is a number or BigInt if the type of it is either int64, uint64, uint128 or uint512.
You may also use BigInt for API request inputs wherever the type is one of the above.

11.1.1

Just updated documents. You don't need to update chia-agent from 11.1.0 for `chia-blockchain@1.8.1` because there are no API changes.

11.1.0

Changed

  • Wallet RPC API
    • get_wallet_balance
      • Part of response properties are replaced by Balance type.
        (* No new properties were added and no properties were removed to the response. Just part of props were managed separately)
    • cat_spend
      • Added extra_delta, tail_reveal and tail_solution to request parameter.
    • In chia/wallet/nft_wallet/nft_info.py, nft_coin_confirmation_height was added to NFTInfo.
      As a result of this change, the responses from following RPC API is affected.
  • Updated yaml to 2.2.2

    Added

  • New DataLayer RPC API
  • Added missing get_sync_status to README.md for RPC APIs
  • Added missing property launcher_id to dl_history in DataLayer RPC API

11.0.0

Breaking change

JSONified MempoolItem replaced original MempoolItem in chia/types/mempool_items.py for 2 RPC API responses listed below.
As a result of this change, removals was added and height_added_to_mempool/assert_height were removed from those RPC API responses.

In chia/wallet/nft_wallet/nft_info.py, nft_id was added to NftInfo.
As a result of this change, the responses from following RPC APIs are affected.

10.1.0

Indirect Change

In chia/types/mempool_items.py, assert_height was added to MempoolItem.
As a result of this change, the responses from following RPC APIs are affected.

10.0.0

Breaking change

In chia/types/mempool_items.py, removals of MempoolItem is now flagged as @property. As a result of this, removals of MempoolItem is removed from 2 RPC API responses listed below.

  • FullNode RPC API
  • Response params ofkeyring_status daemon WebSocket API below are deprecated
    • needs_migration
    • can_remove_legacy_keys

      Removed

  • Daemon WebSocket API
    (Code will remain awhile on chia-agent for backward compatibility. Only document is removed for now.)
    • Removed migrate_keyring
    • Removed notify_keyring_migration_completed

      Added

  • New DataLayer RPC API
  • New Wallet RPC API
  • Daemon WebSocket API
    • keyring_status
      • Removed needs_migration from response
      • Removed can_remove_legacy_keys from response
  • FullNode RPC API
  • Wallet RPC API
    • send_transaction
      • Added max_coin_amount to request parameter
      • Added exclude_coin_amounts to request parameter
      • Added exclude_coin_ids to request parameter
    • send_transaction_multi
      • Added max_coin_amount to request parameter
      • Added exclude_coin_amounts to request parameter
      • Added parameters for cat spends.
    • select_coins
      • Added max_coin_amount to request parameter
      • Added exclude_coin_amounts to request parameter
    • cat_spend
      • Added additions to request parameter
      • Added max_coin_amount to request parameter
      • Added exclude_coin_amounts to request parameter
      • Added exclude_coin_ids to request parameter
    • sign_message_by_id
      • Added latest_coin_id to request parameter
    • create_offer_for_ids
      • Added max_coin_amount to request parameter
    • take_offer
      • Added max_coin_amount to request parameter
    • nft_mint_nft
      • Added nft_id to return parameter
    • nft_mint_bulk
      • Added nft_id_list to return parameter
    • create_signed_transaction
      • Added max_coin_amount to return parameter
      • Added exclude_coin_amounts to return parameter
  • Wallet WebSocket API
  • TBladeBitParams has been renamed to TBladeBitRamParams
    • plot_type: "ramplot" has been added
  • TBladeBit2Params has been renamed to TBladeBitDiskParams
    • plot_type: "diskplot" has been added
    • plotter type has been converted to "bladebit" from "bladebit2"
  • Eased type requirement of daemon.sendMessage() and agent.sendMessage()
    You can request RPC API on Daemon WebSocket channel like this:
    const {getDaemon} = require("chia-agent");
    const {get_harvesters_summary} = require("chia-agent/api/rpc/farmer");
    const daemon = getDaemon();
    await daemon.connect();
    res = await get_harvesters_summary(daemon);
    // or specify service name and API command
    res = await daemon.sendMessage("chia_farmer", "get_harvesters_summary");
    /*
    {
    ack: true,
    command: 'get_harvesters_summary',
    data: { harvesters: [ [Object] ], success: true },
    destination: 'chia_agent',
    origin: 'chia_farmer',
    request_id: '4e31c04df234538901d9270932d04301b5b3a1a895d762144400852b8167973f'
    }
    */
    Please note that when you use RPC API, you can directly request to the RPC endpoint of the service(full_node/farmer/...). However, when you request RPC API on Daemon WebSocket channel, you get a response from the service which the daemon is connecting to. In other word, you can choose the exact ip:port of a service if you use RPC API, while it is the daemon which chooses the services it connects to if you use Daemon WebSocket channel.

    Fixed

  • FullNode RPC API
    • get_blockchain_state
      • Made sync_tip_height as uint32(previously Optional<uint32>) because None value would never be set
  • Wallet RPC API

9.2.0

Minor breaking change

9.1.0

Added

9.0.1

Fixed

  • Fixed an issue where wallet state_changed events(notified via WebSocket API) below were missing.
    • did_coin_added
    • nft_coin_added
    • nft_coin_removed
    • nft_coin_updated
    • nft_coin_did_set

9.0.0

Breaking Change

series_total and series_number in NFTInfo class have been renamed to edition_total and edition_number
(defined in chia/wallet/nft_wallet/nft_info.py.)
As a result, the following Wallet RPC APIs in `chia-blockchain@1.5.1become not compatible withchia-blockchain@1.5.0`

8.0.0

Breaking Change

7.0.0

Breaking Change

6.0.0

Minor Breaking Change

5.0.0

Breaking Change

4.0.0

Breaking Change

3.0.1

Added

  • Added skip_hostname_verification option for RPCAgent

    Fixed

  • Fixed an issue where wallet WebSocket message from daemon was not captured.
    Thank you! @joshpainter

3.0.0

Minor Breaking Change

  • Service name of plotter was changed:
    chia plots create => chia_plotter.
    If you have a code which starts plotting via daemon websocket API, you might write like this:
    const {getDaemon} = require("chia-agent");
    const {start_plotting} = require("chia-agent/api/ws");
    const daemon = getDaemon(); // This is the websocket connection handler
    await daemon.connect(); // connect to local daemon using config file.
    const response = await start_plotting(daemon, {service: "chia plots create", ...});
    On and after chia-blockchain@1.2.11, you must rewrite the last line of the above code like this:
    const response = await start_plotting(daemon, {service: "chia_plotter", ...});
    Please note you need to also update other code lines which refers to old service name(chia plots create).

    Changed

  • Updated start_plotting of Daemon Websocket API
  • Updated create_new_wallet of Wallet RPC API
  • Updated get_trade of Wallet RPC API
  • Updated pw_join_pool of Wallet RPC API
  • Updated pw_self_pool of Wallet RPC API
  • Updated pw_absorb_rewards of Wallet RPC API
  • Updated pw_status of Wallet RPC API

    Added

  • New daemon api

2.0.6

Changed

2.0.5

Changed

2.0.4

This release corresponds to chia-blockchain@1.2.6, which introduced no external API changes.

2.0.3

This release corresponds to chia-blockchain@1.2.5 which only updates install script.
There are no API changes at all.

2.0.2

Changed

2.0.1

Added

2.0.0

I incremented major version. See "Changed" section for detail.

Changed

Added

1.1.0 - 2021-07-08

Changed

  • Update G1Element/G2Element type to string (Serialized hex string representation)
  • Updated get_private_key

Added

Fixed

  • Fixed RPC API document links
  • Fixed the type of SerializedProgram to str
  • Fixed an issue where submodule could not be loaded. e.g. const {...} = require("chia-agent/api/rpc");
  • Correct type name TCreate_New_RC_WalletRequest/Response to TCreate_New_RL_WalletRequest/Response
  • Fixed wrong create_new_wallet request format
  • Fixed an issue where array data in YAML file was not parsed as expected.
  • Fixed login response json of Wallet RPC API
  • Fixed get_private_key response json of Wallet RPC API
  • Fixed create_offer_for_ids response json of Wallet RPC API
  • Fixed get_discrepancies_for_offer response json of Wallet RPC API
  • Fixed did_get_pubkey response json of Wallet RPC API
  • Fixed did_recovery_spend response json of Wallet RPC API

1.0.1 - 2021-05-19

Fixed

  • Only fixed typo in README.md

1.0.0 - 2021-05-19

Added

  • Added new RPC client
  • Added new RPC API
  • Added new Websocket API
  • Added API type definitions
  • Added code samples

0.0.5 - 2021-05-13

Changed

  • Reorganized internal log level and locations.
  • daemon.connect() resolves to boolean value indicating whether connecting is success or failure.
  • Trying to re-connect to an url which is already active does not output warning anymore.

Added

  • Added types

Fixed

  • Fixed an issue where it could fail to catch response from chia daemon.

0.0.4 - 2021-05-13

Fixed

  • Fixed an issue where some requests were not responded by chia daemon.

0.0.3 - 2021-05-13

Changed

  • Changed argument order for daemon.sendMessage for previous one was not intuitive.
// Old
daemon.sendMessage(get_block_record_by_height_command, destination, data);
// Now
daemon.sendMessage(destination, get_block_record_by_height_command, data);

0.0.2 - 2021-05-13

Fixed

  • Fixed an issue where it cannot be executed via npx command.

0.0.1 - 2021-05-13

Initial release.