### Install BitsharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/README.md Install the library via npm. ```bash npm install bitsharesjs ``` -------------------------------- ### Generate ESDoc Documentation Source: https://github.com/bitshares/bitsharesjs/blob/develop/README.md Commands to install and run ESDoc for the project. ```bash npm i -g esdoc esdoc-es7-plugin esdoc -c ./esdoc.json open out/esdoc/index.html ``` -------------------------------- ### Publish Price Feed in BitSharesJS Source: https://context7.com/bitshares/bitsharesjs/llms.txt This example demonstrates how to publish a price feed for a BitAsset. Ensure the publisher account ID and asset ID are correct. ```javascript import { Apis } from "bitsharesjs-ws"; import { TransactionBuilder, PrivateKey } from "bitsharesjs"; let privateKey = PrivateKey.fromWif("5KBuq5WmHvgePmB7w3onYsqLM8ESomM2Ae7SigYuuwg8MDHW7NN"); Apis.instance("wss://node.testnet.bitshares.eu", true).init_promise.then(res => { let tr = new TransactionBuilder(); tr.add_type_operation("asset_publish_feed", { publisher: "1.2.680", // Publisher account ID asset_id: "1.3.1003", // BitAsset ID feed: { settlement_price: { quote: { amount: 10, asset_id: "1.3.0" }, // BTS base: { amount: 5, asset_id: "1.3.1003" } // BitAsset }, maintenance_collateral_ratio: 1750, // 175% maximum_short_squeeze_ratio: 1200, // 120% core_exchange_rate: { quote: { amount: 10, asset_id: "1.3.0" }, base: { amount: 5, asset_id: "1.3.1003" } } } }); tr.set_required_fees().then(() => { tr.add_signer(privateKey, privateKey.toPublicKey().toPublicKeyString()); tr.broadcast().then(() => { console.log("Feed published successfully!"); }).catch(err => { console.error("Error:", err); }); }); }); ``` -------------------------------- ### Example Auths Object Source: https://github.com/bitshares/bitsharesjs/blob/develop/README.md Structure for the auths object containing account authority arrays. ```json { active: [ ["GPH5Abm5dCdy3hJ1C5ckXkqUH2Me7dXqi9Y7yjn9ACaiSJ9h8r8mL", 1] ] } ``` -------------------------------- ### Define Linear Vesting Policy Initializer Serializer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/temp.js.html Defines the structure for a linear vesting policy, specifying the start time, cliff duration, and total vesting duration in seconds. ```javascript linear_vesting_policy_initializer = new Serializer( "linear_vesting_policy_initializer", { begin_timestamp: time_point_sec, vesting_cliff_seconds: uint32, vesting_duration_seconds: uint32 } ); ``` -------------------------------- ### Integrate in Browser Environment Source: https://context7.com/bitshares/bitsharesjs/llms.txt Demonstrates loading the library via script tag and accessing the bitshares_js namespace. Ensure the library is bundled and available in the project build directory. ```html ``` -------------------------------- ### Get Address Buffer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/ecc/src/address.js.html Returns the raw buffer representation of the address. ```javascript toBuffer() { return this.addy; } ``` -------------------------------- ### Initialize ChainStore Source: https://github.com/bitshares/bitsharesjs/blob/develop/README.md Connect to the blockchain and initialize the ChainStore to subscribe to state updates. ```javascript import {Apis} from "bitsharesjs-ws"; var {ChainStore} = require("bitsharesjs"); Apis.instance("wss://eu.nodes.bitshares.ws", true).init_promise.then((res) => { console.log("connected to:", res[0].network); ChainStore.init().then(() => { ChainStore.subscribe(updateState); }); }); let dynamicGlobal = null; function updateState(object) { dynamicGlobal = ChainStore.getObject("2.1.0"); console.log("ChainStore object update\n", dynamicGlobal ? dynamicGlobal.toJS() : dynamicGlobal); } ``` -------------------------------- ### Initialize ChainStore and Dependencies Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Imports necessary modules and initializes constants for object type identification and debugging. ```javascript import Immutable from "immutable"; import {Apis} from "bitsharesjs-ws"; import ChainTypes from "./ChainTypes"; import ChainValidation from "./ChainValidation"; import BigInteger from "bigi"; import ee from "./EmitterInstance"; const {object_type, impl_object_type} = ChainTypes; let emitter = ee(); let op_history = parseInt(object_type.operation_history, 10); let witness_object_type = parseInt(object_type.witness, 10); let committee_member_object_type = parseInt(object_type.committee_member, 10); let account_object_type = parseInt(object_type.account, 10); let witness_prefix = "1." + witness_object_type + "."; let committee_prefix = "1." + committee_member_object_type + "."; let account_prefix = "1." + account_object_type + "."; const DEBUG = JSON.parse( process.env.npm_config__graphene_chain_chain_debug || false ); const objectTypesArray = Object.keys(object_type); const implObjectTypesArray = Object.keys(impl_object_type); ``` -------------------------------- ### GET /state/get Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/state.js.html Retrieves a value from the state object based on the provided key. ```APIDOC ## GET /state/get ### Description Retrieves a value from the state object. If the key does not exist, it returns an empty string. ### Method GET ### Parameters #### Path Parameters - **key** (string) - Required - The key to look up in the state object. ### Response #### Success Response (200) - **value** (any) - The value associated with the key or an empty string. ``` -------------------------------- ### Export State Functions Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/state.js.html Exports the get and set functions for use in other modules. ```javascript export {get, set}; ``` -------------------------------- ### ChainStore - init Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/chain/src/ChainStore.js~ChainStore.html Initializes the ChainStore. Optionally subscribes to new objects. ```APIDOC ## POST /api/chain/init ### Description Initializes the ChainStore. This method can optionally subscribe to new objects being added to the chain. ### Method POST ### Endpoint /api/chain/init ### Parameters #### Request Body - **subscribe_to_new** (boolean): Optional. Defaults to true. If true, the store will subscribe to new objects. ### Response #### Success Response (200) - **status** (*): Indicates the initialization status. ``` -------------------------------- ### Initialize ChainStore and Subscription Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Initializes the ChainStore instance, verifies API availability, and sets up subscription callbacks after ensuring the node is synced. ```javascript return this.init(subscribe_to_new).catch(err => { console.log("resetCache init error:", err()); }); } setDispatchFrequency(freq) { this.dispatchFrequency = freq; } init(subscribe_to_new = true) { let reconnectCounter = 0; var _init = (resolve, reject) => { if (this.subscribed) return resolve(); let db_api = Apis.instance().db_api(); if (!db_api) { return reject( new Error( "Api not found, please initialize the api instance before calling the ChainStore" ) ); } return db_api .exec("get_objects", [["2.1.0"]]) .then(optional_objects => { //if(DEBUG) console.log("... optional_objects",optional_objects ? optional_objects[0].id : null) for (let i = 0; i < optional_objects.length; i++) { let optional_object = optional_objects[i]; if (optional_object) { /* ** Because 2.1.0 gets fetched here before the set_subscribe_callback, ** the new witness_node subscription model makes it so we ** never get subscribed to that object, therefore ** this._updateObject is commented out here */ // this._updateObject( optional_object, true ); let head_time = new Date( optional_object.time + "+00:00" ).getTime(); this.head_block_time_string = optional_object.time; this.chain_time_offset.push( new Date().getTime() - timeStringToDate( optional_object.time ).getTime() ); let now = new Date().getTime(); let delta = (now - head_time) / 1000; // let start = Date.parse("Sep 1, 2015"); // let progress_delta = head_time - start; // this.progress = progress_delta / (now-start); if (delta < 60) { Apis.instance() .db_api() .exec("set_subscribe_callback", [ this.onUpdate.bind(this), subscribe_to_new ]) .then(() => { console.log( "synced and subscribed, chainstore ready" ); this.subscribed = true; this.subError = null; this.notifySubscribers(); resolve(); }) .catch(error => { this.subscribed = false; this.subError = error; this.notifySubscribers(); reject(error); console.log("Error: ", error); }); } else { console.log("not yet synced, retrying in 1s"); this.subscribed = false; reconnectCounter++; this.notifySubscribers(); if (reconnectCounter > 5) { this.subError = new Error( "ChainStore sync error, please check your system clock" ); return reject(this.subError); } setTimeout( _init.bind(this, resolve, reject), 1000 ); } ``` -------------------------------- ### Get First Element Utility Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/src/types.js.html Retrieves the first element of an array or returns the element itself if it's not an array. ```javascript firstEl = el => (Array.isArray(el) ? el[0] : el); ``` -------------------------------- ### PrivateKey Static Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Methods for initializing a PrivateKey instance from different data formats. ```APIDOC ## Static Methods for PrivateKey ### fromBuffer - **Description**: Creates a PrivateKey from a buffer. - **Parameters**: buf (*) - **Returns**: * ### fromHex - **Description**: Creates a PrivateKey from a hex string. - **Parameters**: hex (*) - **Returns**: * ### fromSeed - **Description**: Creates a PrivateKey from a seed. - **Parameters**: seed (*) - **Returns**: * ### fromWif - **Description**: Creates a PrivateKey from a Wallet Import Format (WIF) string. - **Parameters**: _private_wif (*) - **Returns**: string ``` -------------------------------- ### Get Transaction as Object Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Returns the transaction object in its object representation. This is often used for inspection or before serialization. ```javascript toObject() { return ops.signed_transaction.toObject(this); } ``` -------------------------------- ### Get Type Operation Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Retrieves and prepares an operation by name. Sets default fee structures if not provided. ```javascript get_type_operation(name, operation) { if (this.tr_buffer) { throw new Error("already finalized"); } assert(name, "name"); assert(operation, "operation"); var _type = ops[name]; assert(_type, `Unknown operation ${name}`); var operation_id = ChainTypes.operations[_type.operation_name]; if (operation_id === undefined) { throw new Error(`unknown operation: ${_type.operation_name}`); } if (!operation.fee) { operation.fee = {amount: 0, asset_id: 0}; } if (name === "proposal_create") { /* * Proposals involving the committee account require a review * period to be set, look for them here */ ``` -------------------------------- ### PublicKey Class Documentation Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PublicKey.js~PublicKey.html This section provides a comprehensive overview of the PublicKey class, including its static methods for creating PublicKey objects from different formats, its constructor, and its instance methods for retrieving key information. ```APIDOC ## PublicKey Class This class represents a public key in the BitShares ecosystem. ### Static Methods #### `fromBinary(bin)` Creates a PublicKey object from its binary representation. * **Parameters:** * `bin` (*): The binary data of the public key. * **Returns:** * (*): A new PublicKey object. #### `fromBuffer(buffer)` Creates a PublicKey object from a buffer. * **Parameters:** * `buffer` (*): The buffer containing the public key data. * **Returns:** * (*): A new PublicKey object. #### `fromHex(hex)` Creates a PublicKey object from its hexadecimal representation. * **Parameters:** * `hex` (*): The hexadecimal string of the public key. * **Returns:** * (*): A new PublicKey object. #### `fromPoint(point)` Creates a PublicKey object from a point on the elliptic curve. * **Parameters:** * `point` (*): The point object representing the public key. * **Returns:** * (*): A new PublicKey object. #### `fromPublicKeyString(public_key, address_prefix)` Creates a PublicKey object from a public key string. * **Parameters:** * `public_key` (*): The public key string. * `address_prefix` (*): Optional. The address prefix to use for validation. * **Returns:** * (*): A new PublicKey object or `null` if the string is invalid. #### `fromPublicKeyStringHex(hex)` Creates a PublicKey object from a public key string in hexadecimal format. * **Parameters:** * `hex` (*): The hexadecimal public key string. * **Returns:** * (*): A new PublicKey object. #### `fromStringOrThrow(public_key, address_prefix)` Creates a PublicKey object from a public key string, throwing an error if invalid. * **Parameters:** * `public_key` (*): The public key string. * `address_prefix` (*): Optional. The address prefix to use for validation. * **Returns:** * (*): A new PublicKey object. ### Constructor #### `constructor(public)` Initializes a new PublicKey object. * **Parameters:** * `public` (Point): The public point of the key. ### Instance Methods #### `child(offset)` Derives a child public key. * **Parameters:** * `offset` (*): The offset for derivation. * **Returns:** * (*): The derived child PublicKey object. #### `toAddressString(address_prefix)` Converts the public key to its corresponding address string. * **Parameters:** * `address_prefix` (*): The address prefix to use. * **Returns:** * (*): The address string. #### `toBlockchainAddress()` Converts the public key to its blockchain address format. * **Returns:** * (bts::blockchain::address): The blockchain address. #### `toBuffer(compressed)` Converts the public key to its buffer representation. * **Parameters:** * `compressed` (*): Whether to use compressed format. * **Returns:** * (*): The buffer representation of the public key. #### `toByteBuffer()` Converts the public key to its byte buffer representation. * **Returns:** * (*): The byte buffer representation. #### `toHex()` Converts the public key to its hexadecimal representation. * **Returns:** * (*): The hexadecimal string of the public key. #### `toPtsAddy()` Converts the public key to the PTS Addy format. * **Returns:** * (*): The PTS Addy string. #### `toPublicKeyString(address_prefix)` Converts the public key to its string representation. * **Parameters:** * `address_prefix` (*): The address prefix to use. * **Returns:** * (*): The public key string. #### `toString(address_prefix)` Alias for `toPublicKeyString`. * **Parameters:** * `address_prefix` (*): The address prefix to use. * **Returns:** * (*): The public key string. #### `toUncompressed()` Converts the public key to its uncompressed format. * **Returns:** * (*): The uncompressed PublicKey object. ``` -------------------------------- ### toWif Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Converts the private key to the Wallet Import Format (WIF). ```APIDOC ## GET /api/toWif ### Description Converts the private key to the Wallet Import Format (WIF). ### Method GET ### Endpoint /api/toWif ### Response #### Success Response (200) - **wif** (*) ### Response Example { "wif": "example_wif_string" } ``` -------------------------------- ### Get State Property Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/state.js.html Retrieves a property from the state object. Returns an empty string if the property is not found. ```javascript function get(state) { return function(key) { return state[key] || ""; }; } ``` -------------------------------- ### Get Head Block Date in BitSharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Returns the date of the head block. Assumes `timeStringToDate` is defined elsewhere. ```javascript getHeadBlockDate() { return timeStringToDate(this.head_block_time_string); } ``` -------------------------------- ### Get Corresponding PublicKey Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Derive the public key associated with this private key. This is a fundamental operation in asymmetric cryptography. ```javascript import PrivateKey from 'bitsharesjs/lib/ecc/src/PrivateKey.js' // Assuming 'privateKey' is an instance of PrivateKey // const publicKey = privateKey.toPublicKey(); ``` -------------------------------- ### Import Hash Functions Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/function/index.html Utilities for RIPEMD160, SHA256, and SHA512 hashing. ```javascript import {ripemd160} from 'bitsharesjs/lib/ecc/src/hash.js' ``` ```javascript import {sha256} from 'bitsharesjs/lib/ecc/src/hash.js' ``` ```javascript import {sha512} from 'bitsharesjs/lib/ecc/src/hash.js' ``` -------------------------------- ### PublicKey Static Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PublicKey.js~PublicKey.html Static methods for creating PublicKey instances. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. ### Request Example ```json { "username": "john_doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user123", "username": "john_doe", "email": "john.doe@example.com" } ``` #### Error Response (400) - **error** (string) - A message describing the error. #### Error Example ```json { "error": "Username already exists." } ``` ``` ```APIDOC ## GET /api/users/{id} ### Description Retrieves details for a specific user. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": "user123", "username": "john_doe", "email": "john.doe@example.com" } ``` #### Error Response (404) - **error** (string) - A message describing the error. #### Error Example ```json { "error": "User not found." } ``` ``` -------------------------------- ### Get Head Block Date Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Retrieves the date of the head block by calling the timeStringToDate utility function with the global head_block_time_string. ```javascript function getHeadBlockDate() { return timeStringToDate(head_block_time_string); } ``` -------------------------------- ### Get Transaction ID Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Calculates the SHA256 hash of the transaction buffer to return a hex transaction ID. Requires the transaction to be finalized. ```javascript id() { if (!this.tr_buffer) { throw new Error("not finalized"); } return hash .sha256(this.tr_buffer) .toString("hex") .substring(0, 40); } ``` -------------------------------- ### Initialize ChainStore Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Initializes the ChainStore by connecting to the BitShares network and fetching initial data. It uses a Promise to handle asynchronous operations and includes error handling for API issues. ```javascript init() { return new Promise((resolve, reject) => { let _init = (resolve, reject) => { // ... initialization logic ... if (this.initPromise) { // If already initializing, return the existing promise return this.initPromise; } this.initPromise = new Promise((resolve, reject) => { // ... actual initialization steps ... // Example: Fetching core assets let coreAssetPromise = this.fetch(ChainConfig.core_asset); // Example: Fetching genesis object let genesisObjectPromise = this.fetch("2.1.0"); Promise.all([coreAssetPromise, genesisObjectPromise]) .then(result => { // ... process results ... resolve(); }) .catch(error => { console.error("ChainStore initialization failed:", error); reject(error); }); }); return this.initPromise; }; if (this.initialized) { resolve(); } else { setTimeout(_init.bind(this, resolve, reject), 1000); } }) .catch(error => { // in the event of an error clear the pending state for id console.log("!!! Chain API error", error); this.objects_by_id.delete("2.1.0"); reject(error); }); } ``` -------------------------------- ### Get PublicKey Point Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Retrieve the public key as a Point object, which represents the point on the elliptic curve corresponding to the public key. ```javascript import PrivateKey from 'bitsharesjs/lib/ecc/src/PrivateKey.js' // Assuming 'privateKey' is an instance of PrivateKey // const publicKeyPoint = privateKey.toPublicKeyPoint(); ``` -------------------------------- ### Login Class Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/README.md Available methods for the login class. ```text generateKeys(account, password, [roles]) checkKeys(account, password, auths) signTransaction(tr) ``` -------------------------------- ### Get Object by Single Vote ID in BitSharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Retrieves a single object using its vote ID. Returns undefined if the object is not found. ```javascript getObjectByVoteID(vote_id) { let obj_id = this.objects_by_vote_id.get(vote_id); if (obj_id) return this.getObject(obj_id); return undefined; } ``` -------------------------------- ### Initialize Singleton Emitter Instance Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/EmitterInstance.js.html Returns a shared event-emitter instance, creating it if it does not already exist. Requires the event-emitter package. ```javascript import ee from "event-emitter"; var _emitter; export default function emitter() { if (!_emitter) { _emitter = ee({}); } return _emitter; } ``` -------------------------------- ### Convert PrivateKey to Hex String Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Get the hexadecimal string representation of the private key. This is a common format for displaying or logging private keys. ```javascript import PrivateKey from 'bitsharesjs/lib/ecc/src/PrivateKey.js' // Assuming 'privateKey' is an instance of PrivateKey // const hexString = privateKey.toHex(); ``` -------------------------------- ### Import TransactionBuilder Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/chain/src/TransactionBuilder.js~TransactionBuilder.html Import the TransactionBuilder class from the library to begin constructing transactions. ```javascript import TransactionBuilder from 'bitsharesjs/lib/chain/src/TransactionBuilder.js' ``` -------------------------------- ### Define Account Create Serializer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/temp.js.html Defines the structure for creating a new account, including registrar, referrer, name, and authorities. ```javascript account_create = new Serializer("account_create", { fee: asset, registrar: protocol_id_type("account"), referrer: protocol_id_type("account"), referrer_percent: uint16, name: string, owner: authority, active: authority, options: account_options, extensions: set(future_extensions) }); ``` -------------------------------- ### Import Transaction Template Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/function/index.html Print transaction objects with zero default values. ```javascript import template from 'bitsharesjs/lib/serializer/src/template.js' ``` -------------------------------- ### Get Required Signatures for a Transaction Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Fetches the public keys required to sign a transaction, given a set of available keys. Ensure that `Apis.instance().db_api()` is accessible. ```javascript get_required_signatures(available_keys) { if (!available_keys.length) { return Promise.resolve([]); } var tr_object = ops.signed_transaction.toObject(this); //DEBUG console.log('... tr_object',tr_object) return Apis.instance() .db_api() .exec("get_required_signatures", [tr_object, available_keys]) .then(function(required_public_keys) { //DEBUG console.log('... get_required_signatures',required_public_keys) return required_public_keys; }); } ``` -------------------------------- ### Import Emitter Instance Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/function/index.html Access the emitter instance for event handling. ```javascript import emitter from 'bitsharesjs/lib/chain/src/EmitterInstance.js' ``` -------------------------------- ### Get Potential Signatures for a Transaction Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/TransactionBuilder.js.html Retrieves potential public keys and addresses that can sign a given transaction object. This is useful for determining signing requirements before a transaction is finalized. ```javascript get_potential_signatures(ops) { var tr_object = ops.signed_transaction.toObject(this); return Promise.all([ Apis.instance() .db_api() .exec("get_potential_signatures", [tr_object]), Apis.instance() .db_api() .exec("get_potential_address_signatures", [tr_object]) ]).then(function(results) { return {pubkeys: results[0], addys: results[1]}; }); } ``` -------------------------------- ### Handle Protocol and Implementation Object Types Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/src/SerializerValidation.js.html Utilities for verifying and extracting instances from specific protocol, relative, and implementation object types. ```javascript require_object_type: function( reserved_spaces = 1, type, value, field_name = "" ) { if (this.is_empty(value)) { return value; } var object_type = ChainTypes.object_type[type]; if (!object_type) { throw new Error( `Unknown object type ${type} ${field_name} ${value}` ); } var re = new RegExp(`${reserved_spaces}\.${object_type}\.[0-9]+$`); if (!re.test(value)) { throw new Error( `Expecting ${type} in format ` + `${reserved_spaces}.${object_type}.[0-9]+ ` + `instead of ${value} ${field_name} ${value}` ); } return value; }, ``` ```javascript get_instance: function(reserve_spaces, type, value, field_name) { if (this.is_empty(value)) { return value; } this.require_object_type(reserve_spaces, type, value, field_name); return this.to_number(value.split(".")[2]); }, ``` ```javascript require_relative_type: function(type, value, field_name) { this.require_object_type(0, type, value, field_name); return value; }, ``` ```javascript get_relative_instance: function(type, value, field_name) { if (this.is_empty(value)) { return value; } this.require_object_type(0, type, value, field_name); return this.to_number(value.split(".")[2]); }, ``` ```javascript require_protocol_type: function(type, value, field_name) { this.require_object_type(1, type, value, field_name); return value; }, ``` ```javascript get_protocol_instance: function(type, value, field_name) { if (this.is_empty(value)) { return value; } this.require_object_type(1, type, value, field_name); return this.to_number(value.split(".")[2]); }, ``` ```javascript get_protocol_type: function(value, field_name) { if (this.is_empty(value)) { return value; } this.require_object_id(value, field_name); var values = value.split("."); return this.to_number(values[1]); }, ``` ```javascript get_protocol_type_name(value, field_name) { if (this.is_empty(value)) { return value; } var type_id = this.get_protocol_type(value, field_name); return Object.keys(ChainTypes.object_type)[type_id]; }, ``` ```javascript require_implementation_type: function(type, value, field_name) { this.require_object_type(2, type, value, field_name); return value; }, ``` ```javascript get_implementation_instance: function(type, value, field_name) { if (this.is_empty(value)) { return value; } this.require_object_type(2, type, value, field_name); return this.to_number(value.split(".")[2]); }, ``` -------------------------------- ### Create PrivateKey from Buffer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Use this static method to create a PrivateKey instance from a buffer. Ensure the buffer contains valid private key data. ```javascript import PrivateKey from 'bitsharesjs/lib/ecc/src/PrivateKey.js' // Assuming 'buf' is a Buffer containing private key data // const privateKey = PrivateKey.fromBuffer(buf); ``` -------------------------------- ### Get Shared Secret for ECIES Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Calculate the shared secret for Elliptic Curve Integrated Encryption Scheme (ECIES) using a public key. The 'legacy' parameter may affect the calculation. ```javascript import PrivateKey from 'bitsharesjs/lib/ecc/src/PrivateKey.js' // Assuming 'privateKey' is an instance of PrivateKey, 'public_key' is a PublicKey object, and 'legacy' is a boolean // const sharedSecret = privateKey.get_shared_secret(public_key, legacy); ``` -------------------------------- ### Emitter Instance Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/function/index.html Provides access to the emitter instance for event handling. ```APIDOC ## GET /api/emitter ### Description Returns the emitter instance for event handling. ### Method GET ### Endpoint /api/emitter ### Response #### Success Response (200) - **emitter** (*) ### Response Example { "emitter": "*" } ``` -------------------------------- ### Define CDD Vesting Policy Initializer Serializer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/temp.js.html Defines the structure for a cumulative defined distribution (CDD) vesting policy, specifying the start claim time and vesting duration in seconds. ```javascript cdd_vesting_policy_initializer = new Serializer( "cdd_vesting_policy_initializer", { start_claim: time_point_sec, vesting_seconds: uint32 } ); ``` -------------------------------- ### Get Object from Cache Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Retrieves an object by its ID. Supports forcing a re-fetch, subscribing to changes, and optionally omitting full account details. Returns undefined if pending, null if not found, or the object itself. ```javascript getObject( id, force = false, autosubscribe = true, no_full_account = false ) { if (!ChainValidation.is_object_id(id)) throw Error("argument is not an object id: " + JSON.stringify(id)); let result = this.objects_by_id.get(id); let subChange = id.substring(0, account_prefix.length) == account_prefix && !this.get_full_accounts_subscriptions.get(id, false) && autosubscribe; if (result === null && !force) return result; if (result === undefined || force || subChange) return this.fetchObject(id, force, autosubscribe, no_full_account); if (result === true) return undefined; return result; } ``` -------------------------------- ### PrivateKey Instance Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Methods available on a PrivateKey instance for key derivation and transformation. ```APIDOC ## Instance Methods for PrivateKey ### child - **Description**: Derives a child key from the current key using an offset. - **Parameters**: offset (*) - **Returns**: * - **Throws**: Error (overflow of the key could not be derived) ### get_shared_secret - **Description**: Generates a shared secret with a public key. - **Parameters**: public_key (*), legacy (boolean) - **Returns**: * ``` -------------------------------- ### Hex and Buffer Conversion Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/ecc/src/signature.js.html Utility methods for converting signatures to and from hex strings and ByteBuffers. ```javascript toByteBuffer() { var b; b = new ByteBuffer( ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN ); this.appendByteBuffer(b); return b.copy(0, b.offset); } static fromHex(hex) { return Signature.fromBuffer(Buffer.from(hex, "hex")); } toHex() { return this.toBuffer().toString("hex"); } static signHex(hex, private_key) { var buf; buf = Buffer.from(hex, "hex"); return Signature.signBuffer(buf, private_key); } verifyHex(hex, public_key) { var buf; buf = Buffer.from(hex, "hex"); return this.verifyBuffer(buf, public_key); } } export default Signature; ``` -------------------------------- ### Get Account Member Status Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Determines the membership status of an account ('lifetime', 'annual', 'basic', or 'unknown') based on its 'lifetime_referrer', 'membership_expiration_date', and current time. Handles undefined or null account inputs gracefully. ```javascript getAccountMemberStatus(account) { if (account === undefined) return undefined; if (account === null) return "unknown"; if (account.get("lifetime_referrer") == account.get("id")) return "lifetime"; let exp = new Date(account.get("membership_expiration_date")).getTime(); let now = new Date().getTime(); if (exp < now) return "basic"; return "annual"; } ``` -------------------------------- ### Fetch Witness by Account - BitSharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Fetches a witness object associated with a given account ID. It subscribes to witness updates and stores the witness information. Use this to get specific witness details for an account. ```javascript Apis.instance() .db_api() .exec("get_witness_by_account", [account_id]) .then(optional_witness_object => { if (optional_witness_object) { this._subTo("witnesses", optional_witness_object.id); this.witness_by_account_id = this.witness_by_account_id.set( optional_witness_object.witness_account, optional_witness_object.id ); let witness_object = this._updateObject( optional_witness_object, true ); resolve(witness_object); } else { this.witness_by_account_id = this.witness_by_account_id.set( account_id, null ); this.notifySubscribers(); resolve(null); } }, reject); ``` -------------------------------- ### Manage Private Keys with PrivateKey Source: https://context7.com/bitshares/bitsharesjs/llms.txt Handles generation, import, and export of private keys. Requires importing PrivateKey and key utilities from bitsharesjs. ```javascript import { PrivateKey, key } from "bitsharesjs"; // Generate private key from a brainkey seed let seed = "THIS IS A TERRIBLE BRAINKEY SEED WORD SEQUENCE"; let normalizedSeed = key.normalize_brainKey(seed); let privateKey = PrivateKey.fromSeed(normalizedSeed); console.log("Private key (WIF):", privateKey.toWif()); // Output: 5JBuq5WmHvgePmB7w3onYsqLM8ESomM2Ae7SigYuuwg8MDHW7NN console.log("Public key:", privateKey.toPublicKey().toString()); // Output: BTS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV // Import from WIF format let importedKey = PrivateKey.fromWif("5KBuq5WmHvgePmB7w3onYsqLM8ESomM2Ae7SigYuuwg8MDHW7NN"); // Generate from hex let hexKey = PrivateKey.fromHex("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); console.log("Hex key WIF:", hexKey.toWif()); // Get shared secret for encrypted communication (ECIES) let sharedSecret = privateKey.get_shared_secret(recipientPublicKey); ``` -------------------------------- ### Fetch Committee Member by Account - BitSharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Retrieves committee member details for a specific account ID. It handles subscription and updates internal state. Use this to check if an account is a committee member and get its details. ```javascript Apis.instance() .db_api() .exec("get_committee_member_by_account", [account_id]) .then(optional_committee_object => { if (optional_committee_object) { this._subTo("committee", optional_committee_object.id); this.committee_by_account_id = this.committee_by_account_id.set( optional_committee_object.committee_member_account, optional_committee_object.id ); let committee_object = this._updateObject( optional_committee_object, true ); resolve(committee_object); } else { this.committee_by_account_id = this.committee_by_account_id.set( account_id, null ); this.notifySubscribers(); resolve(null); } }, reject); ``` -------------------------------- ### ChainStore Initialization in BitSharesJS Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Initializes a new ChainStore instance. This is a global instance used for managing blockchain data. ```javascript let chain_store = new ChainStore(); ``` -------------------------------- ### Signature Instance Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/signature.js~Signature.html Instance methods for working with a Signature object, including verification and serialization. ```APIDOC ## Signature Instance Methods ### Description Provides instance methods for verifying signatures and serializing them into different formats. ### Public Methods #### public recoverPublicKey(sha256_buffer: *): PublicKey Recovers the public key associated with the signature from a SHA256 buffer. - **sha256_buffer** (*): The SHA256 hash buffer. #### public recoverPublicKeyFromBuffer(buffer: *): * Recovers the public key from a buffer. - **buffer** (*): The buffer containing signature data. #### public toBuffer(): * Serializes the signature into a buffer. #### public toByteBuffer(): * Serializes the signature into a byte buffer. #### public toHex(): * Serializes the signature into a hexadecimal string. #### public verifyBuffer(un-hashed: Buffer): boolean Verifies a signature against an un-hashed buffer. - **un-hashed** (Buffer): The original buffer that was signed. #### public verifyHash(hash: *, public_key: *): * Verifies a signature against a hash using a public key. - **hash** (*): The hash to verify. - **public_key** (*): The public key to use for verification. #### public verifyHex(hex: *, public_key: *): * Verifies a signature against a hexadecimal string using a public key. - **hex** (*): The hexadecimal string to verify. - **public_key** (*): The public key to use for verification. ### Request Example ```json { "example": "request body for verification" } ``` ### Response Example ```json { "example": "boolean indicating verification success" } ``` ``` -------------------------------- ### Get Asset by ID or Symbol Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Retrieves an asset using either its object ID or symbol. Returns null if the input is invalid or the asset does not exist. Handles cases where the asset might be a bitasset without a current feed. ```javascript getAsset(id_or_symbol) { if (!id_or_symbol) return null; if (ChainValidation.is_object_id(id_or_symbol)) { let asset = this.getObject(id_or_symbol); if ( asset && (asset.get("bitasset") && !asset.getIn(["bitasset", "current_feed"])) ``` -------------------------------- ### Helper Function to Get Constructor Name Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/ecc/src/enforce_types.js.html This utility function retrieves the name of a constructor function. It is used internally by the `enforce` function to compare constructor names reliably, avoiding issues with the `name` property in some JavaScript environments. ```javascript function getName(fn) { // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property var match = fn.toString().match(/function (.*?)\(/); return match ? match[1] : null; } ``` -------------------------------- ### Define Worker Initializers and Create Operation Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/src/operations.js.html Serializers for different worker types and the worker creation operation. ```javascript export const refund_worker_initializer = new Serializer( "refund_worker_initializer" ); export const vesting_balance_worker_initializer = new Serializer( "vesting_balance_worker_initializer", {pay_vesting_period_days: uint16} ); export const burn_worker_initializer = new Serializer( "burn_worker_initializer" ); var worker_initializer = static_variant([ refund_worker_initializer, vesting_balance_worker_initializer, burn_worker_initializer ]); export const worker_create = new Serializer("worker_create", { fee: asset, owner: protocol_id_type("account"), work_begin_date: time_point_sec, work_end_date: time_point_sec, daily_pay: int64, name: string, url: string, initializer: worker_initializer }); ``` -------------------------------- ### ChainStore Class Constructor Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Initializes the ChainStore instance with default subscriber sets and cache state. ```javascript class ChainStore { constructor() { /** tracks everyone who wants to receive updates when the cache changes */ this.subscribers = new Set(); this.subscribed = false; this.clearCache(); // this.progress = 0; // this.chain_time_offset is used to estimate the blockchain time this.chain_time_offset = []; this.dispatchFrequency = 40; } ``` -------------------------------- ### Get Account Balance Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/chain/src/ChainStore.js.html Retrieves the balance for a specific asset type within an account. It looks up the balance object ID from the account's balances and then fetches the actual balance amount from the object. Returns 0 if the asset or balance object is not found. ```javascript getAccountBalance(account, asset_type) { let balances = account.get("balances"); if (!balances) return 0; let balance_obj_id = balances.get(asset_type); if (balance_obj_id) { let bal_obj = this.objects_by_id.get(balance_obj_id); if (bal_obj) return bal_obj.get("balance"); } return 0; } ``` -------------------------------- ### Initialize Serializer Module Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/src/operations.js.html Imports necessary types and initializes the base operation structure for the BitShares serializer. ```javascript import types from "./types"; import SerializerImpl from "./serializer"; var { //id_type, //varint32, uint8, uint16, uint32, int64, uint64, string, bytes, bool, array, protocol_id_type, object_id_type, vote_id, future_extensions, static_variant, map, set, public_key, address, time_point_sec, optional } = types; future_extensions = types.void; var operation = static_variant(); export {operation}; var Serializer = function(operation_name, serilization_types_object) { return new SerializerImpl(operation_name, serilization_types_object); }; ``` -------------------------------- ### toBuffer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/PrivateKey.js~PrivateKey.html Converts the private key to a buffer format. ```APIDOC ## GET /api/toBuffer ### Description Converts the private key to a buffer format. ### Method GET ### Endpoint /api/toBuffer ### Response #### Success Response (200) - **buffer** (*) ### Response Example { "buffer": "example_buffer" } ``` -------------------------------- ### Witness Create Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/variable/index.html Serializer for creating a witness. ```APIDOC ## Serializer: witness_create ### Description Serializer for creating a witness. ### Method N/A (Serializer definition) ### Endpoint N/A ### Request Body N/A ### Response N/A ``` -------------------------------- ### Import State Accessors Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/function/index.html Manage state retrieval and updates. ```javascript import {get} from 'bitsharesjs/lib/chain/src/state.js' ``` ```javascript import {set} from 'bitsharesjs/lib/chain/src/state.js' ``` -------------------------------- ### Define Vesting Balance Create Serializer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/serializer/temp.js.html Defines the structure for creating a vesting balance. Requires fee, creator, owner, amount, and the vesting policy. ```javascript vesting_balance_create = new Serializer("vesting_balance_create", { fee: asset, creator: protocol_id_type("account"), owner: protocol_id_type("account"), amount: asset, policy: vesting_policy_initializer }); ``` -------------------------------- ### Address.fromBuffer Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/class/lib/ecc/src/address.js~Address.html Creates an Address instance from a buffer. ```APIDOC ## static fromBuffer ### Description Creates an Address instance from a buffer. ### Parameters - **buffer** (*) - Required - The input buffer. ### Response - **Returns** (*) - An Address instance. ``` -------------------------------- ### Address Generation Methods Source: https://github.com/bitshares/bitsharesjs/blob/develop/docs/file/lib/ecc/src/address.js.html Details on how to generate Address objects using static methods. ```APIDOC ## Static Methods for Address Creation ### `Address.fromBuffer(buffer)` Creates an `Address` object from a raw buffer. - **Parameters**: - `buffer` (Buffer): The buffer containing the address hash. ### `Address.fromString(string, address_prefix = ChainConfig.address_prefix)` Creates an `Address` object from a string, validating the prefix and checksum. - **Parameters**: - `string` (string): The address string (e.g., "BTS..."). - `address_prefix` (string, optional): The expected prefix for the address. Defaults to the global `ChainConfig.address_prefix`. - **Throws**: - `Error`: If the address prefix does not match or the checksum is invalid. ### `Address.fromPublic(public_key, compressed = true, version = 56)` Generates an `Address` from a public key. - **Parameters**: - `public_key` (PublicKey): The public key object. - `compressed` (boolean, optional): Whether to use the compressed form of the public key. Defaults to `true`. - `version` (number, optional): The address version byte. Defaults to `56`. - **Returns**: - `Address`: The generated address object. ```