Skip to content

About

A collection of classes to organize Verus related data in JS/TS

Resources

Stars

1 star

Watchers

3 watching

Forks

Latest commit

 

History

640 Commits

Folders and files

Repository files navigation

verus-typescript-primitives

verus-typescript-primitives is a comprehensive TypeScript library designed for interacting with the Verus blockchain. It provides a robust set of tools for serialization and deserialization of Verus's core data structures, enabling developers to build applications that can construct, parse, and manage Verus identities, currencies, transactions, and more.

This library is essential for any JavaScript or TypeScript project that needs to interface with the Verus network at a low level, offering typed classes for Verus RPC API requests and responses, and handling the complexities of Verus's unique data formats like VDXF (Verus Data Exchange Format).

Core Features

  • PBaaS Primitives: Strong-typed classes for core Verus data structures like Identity, CurrencyDefinition, ReserveTransfer, and TokenOutput.
  • VDXF Support: Full implementation for creating, parsing, and verifying VDXF objects, including VerusPayInvoice, LoginConsentRequest, and SignedSessionObject.
  • RPC API Wrappers: Typed classes for Verus daemon RPC API calls (e.g., getidentity, sendcurrency, getblock), simplifying communication with a Verus node.
  • Serialization & Deserialization: Robust methods (toBuffer, fromBuffer) to convert complex objects into byte-level representations for network transport or storage.
  • Utility Functions: A suite of helper functions for address conversion (toIAddress), hashing, and Verus script compilation/decompilation.

⚠️ Features in Progress ⚠️

Certain features in this library are not yet implemented on the wallet side and may be subject to breaking changes. These include the following and all related subclasses to the following (e.g. the details classes for IdentityUpdateRequest and IdentityUpdateResponse):

  • IdentityUpdateRequest
  • IdentityUpdateResponse
  • IdentityUpdateEnvelope
  • IDENTITY_UPDATE_REQUEST_VDXF_KEY
  • IDENTITY_UPDATE_RESPONSE_VDXF_KEY
  • DATA_TYPE_DEFINEDKEY
  • DefinedKey

Installation

Install the package using npm:

npm install verus-typescript-primitives

Usage

Below are some examples of how to use the library.

Buffer parsing is single-use per instance: fromBuffer, fromDataBuffer, and fromBufferOptionalType share one attempt, including failed attempts. Create a fresh parser for each buffer. Superclass calls and internal payload parsing belong to the same attempt. The guard does not reset existing object state.

Subclasses inherit SerializableEntityBase and may set this.allowRepeatedFromBuffer = true in their constructor if they handle repeated parsing safely. Implement parser overrides as prototype methods; assigning a replacement parser function on an instance replaces its guard.

App encryption requests

AppEncryptionRequestDetails requests a Sapling address and keys for an encrypted channel between a user and an app. The channel can be used for identity uploads or other communication and data sharing. This experimental request has one API: appOrDelegatorID on the enclosing GenericRequest, with hasAppOrDelegatorID(), setHasAppOrDelegatorID(), and FLAG_HAS_APP_OR_DELEGATOR_ID. The JSON field is also appOrDelegatorID. There are no legacy aliases.

Clients must verify the request signature before resolving the app scope:

Envelope scope Required authorization First derivation toId
appOrDelegatorID absent Valid request signature Request signer ID
appOrDelegatorID present Signer is the user's own ID or another ID whose signing authority the wallet fully controls appOrDelegatorID
appOrDelegatorID present, signer not fully controlled Unsupported until the delegate approval handshake is implemented; reject None

Signer equality with appOrDelegatorID alone does not satisfy the second row. An app signing its own request can omit that field. Full signing control means the wallet can satisfy the identity's signing threshold; a linked identity or one key in a higher-threshold identity is insufficient. Serialization and isValid() do not perform signature or authorization checks.

The first zGetEncryptionAddress call uses the wallet user's ID as fromId, the authorized scope as toId, and the wallet's existing key material. Without derivationID, that result is the response. With derivationID, make a second call with the first result's extended spending key as key material, the same user's ID as fromId, and derivationID as toId. Return only this second address and its keys. The optional derivationID can be any ID; it never replaces the app scope in the first call.

For the Mobile integration, use derivationNumber as the first call's encryptionIndex, and secondaryDerivationNumber as the second call's encryptionIndex. The optional secondary number defaults to zero, including when secondaryderivationnumber is omitted from JSON. It is used only when derivationID is present. Keep hdIndex at its current default. The first call must set returnSecret: true when a second call is needed. Decode its Bech32 spending key to raw hex for the second call's extsk; the native API has no parameter for the intermediate z-address. The final call's returnSecret follows FLAG_RETURN_ESK. Intermediate scope keys must never appear in the response. encryptResponseToAddress protects the response and is separate from the derived channel address; Mobile requires it when returning a spending key.

Wallet authorization, native derivation, response encryption, and approval UI are client responsibilities. These primitives serialize the scope and details into the signed request and represent the final address and keys in AppEncryptionResponseDetails.

On the wire, the FLAG_HAS_DERIVATION_ID payload contains the compact derivationID immediately followed by a VarInt secondaryDerivationNumber, including an explicit zero for the default. The optional requestID follows both fields. This is the sole format; there is no legacy decoding path.

Creating a VerusPay Invoice

You can easily create a VerusPay invoice, which can then be converted into a QR code string or a wallet deeplink.

import { VerusPayInvoice, VerusPayInvoiceDetails } from 'verus-typescript-primitives';
import { TransferDestination, DEST_PKH } from 'verus-typescript-primitives';
import { fromBase58Check } from 'verus-typescript-primitives';
import { BN } from 'bn.js';

// Define the invoice details
const details = new VerusPayInvoiceDetails({
  amount: new BN('10000000000'), // 100 VRSC in satoshis
  destination: new TransferDestination({
    type: DEST_PKH,
    destination_bytes: fromBase58Check("R9J8E2no2HVjQmzX6Ntes2ShSGcn7WiRcx").hash
  }),
  requestedcurrencyid: "iJhCezBExJHvtyH3fGhNnt2NhU4Ztkf2yq", // VRSCTEST i-address
});

// Create the invoice object
const invoice = new VerusPayInvoice({ details });

// Generate a string for a QR code
const qrString = invoice.toQrString();
console.log("QR String:", qrString);

// Generate a deeplink URI for wallets
const deeplink = invoice.toWalletDeeplinkUri();
console.log("Deeplink:", deeplink);

Parsing a VerusPay Invoice from a Deeplink

You can parse an existing invoice URI to extract its details.

import { VerusPayInvoice } from 'verus-typescript-primitives';

const deeplinkUri = "i5jtwbp6zymeay9llnraglgjqgdrffsau4://x-callback-url/iEETy7La3FTN2Sd2hNRgepek5S8x8eeUeQ/hv7-_wPSGvW4AVxk05q0TGDq2DF_n1qbbExTYMDNOUi9NaTOjY-LamaVjDHK0QFIAYG2IQABQSAN1fp6A9NIVbxvKuOVLLU-0I-G3oQGbRtS6u4Eampfb217Cdf5FCMScQhV9kMxtjI9GWzpchmjuiTB2tctk6qTD6SfrscAAhQALTMRw4v9IZCS0q70SYBL6LO-_qbvnqI1Y14ygST_NCnbn56Rtk4t-YgAkoizAALNUVCdtT6CLffu0RysEee3KeIkAFT1qksXEsEIZuULP1txVIMuOHY-";

const invoice = VerusPayInvoice.fromWalletDeeplinkUri(deeplinkUri);

console.log('Parsed Invoice Details:', invoice.details.toJson());
console.log('Amount:', invoice.details.amount.toString());
console.log('Destination:', invoice.details.destination.getAddressString());

Local upload primitives

hashData(bytes, hashType?) returns the daemon's serialized 32-byte digest. It supports EHashTypes.HASH_SHA256 (default), HASH_SHA256D, and HASH_BLAKE2BMMR (Verus-personalized Blake2b). Unsupported algorithms throw. Hash ordinary upload leaves over Buffer.concat([payload, salt]), using an exactly 32-byte salt. getMMRRoot(leafHashes, hashType?) combines ordered hashes with the daemon's MMR algorithm, defaulting to personalized Blake2b. A single leaf is its own root; set the single-item descriptor's MMR hash type to its object hash type. These helpers use wire byte order, without display reversal. Existing MMR proof classes retain their original Blake2b behavior.

Once a wallet has encrypted the tagged descriptors, package each upload group:

import {
  BigNumber, CrossChainProof, EvidenceData, ETypes, NotaryEvidence,
  createNotaryEvidenceOutputs, DataDescriptorKey
} from 'verus-typescript-primitives';

function uploadOutputs(chainId: string, taggedEncryptedDescriptor: Buffer) {
  const evidence = new NotaryEvidence({
    systemId: chainId,
    evidence: new CrossChainProof({
      chainObjects: [new EvidenceData({
        version: new BigNumber(1),
        type: new BigNumber(ETypes.TYPE_DATA),
        md: undefined,
        vdxfd: DataDescriptorKey.vdxfid,
        data_vec: taggedEncryptedDescriptor
      })]
    })
  });
  return createNotaryEvidenceOutputs(evidence);
}

The payload is a tagged encrypted DataDescriptor for one leaf, or a tagged MMRDescriptor for multiple leaves; the outer evidence key remains DataDescriptorKey in both cases. The helper returns zero-value {script, value} outputs, splitting the complete serialized evidence into 5,724-byte chunks only when its condition would reach 6,000 bytes. Preserve output order, adjacency, and absolute positions when creating references and funding. NotaryEvidence.reassemble(parts) checks one multipart group's headers, indexes, offsets, and total length. Callers must reject adjacent multipart groups because of the daemon reader limitation.

These are serialization and hashing primitives. Wallet encryption, public recipient creation, request validation, identity merging, reference construction, funding, and transaction-size limits remain responsibilities of the client. Data-signature production is not included.

Offline tests use captured VRSCTEST 1.2.18 signdata and non-broadcast updateidentity results in src/__tests__/fixtures/local-upload. Regenerate them with node scripts/generate-upload-hash-fixtures.js and node scripts/generate-upload-evidence-fixtures.js, supplying VRSCTEST_RPC_URL, VRSCTEST_RPC_USER, and VRSCTEST_RPC_PASSWORD. The fixtures check commitments and exact evidence/script bytes, including the 5,999/6,000-byte boundary. Additional MMR fixtures cover native encryption interoperability as described below; funded/broadcast acceptance is not covered.

MMR compatibility and limits

DataDescriptor, MMRDescriptor, VdxfUniValue and FqnVdxfUniValue use one JSON contract: fromJson / toJson accept and emit the supported lossless daemon representation. The explicitly named fromDaemonJson / toDaemonJson methods are aliases with identical behavior. There is no historical TypeScript JSON mode. Use native constructors and binary serialization for fields RPC JSON cannot retain. FQN JSON requires unique named entries followed by at most one raw byte suffix; sequences that would be overwritten or reordered are rejected.

A native empty descriptor has version 1, while JSON with no version has version 0. An empty native MMR has SHA-256 object hashes, Blake2b MMR hashes, two empty descriptors and an empty leaf array. JSON construction instead uses the daemon's zero defaults for absent versions and hash tags.

JSON conversion accepts only metadata that the daemon preserves. It rejects whitespace normalization, oversized metadata, unpaired surrogates, nonhex bare object data, nonempty EPK/IVK/SSK vectors other than 32 bytes, and vdxfkey fields the daemon would drop. Native descriptors retain VDXF keys and general key vectors. Binary metadata must be valid UTF-8 and fit the 64-byte label / 128-byte MIME limits; writer and isValid() checks are deliberately stricter than the daemon's native writer and validity predicate. Versions and flags are uint32; MMR algorithm tags are nonnegative int32. Unknown representable algorithm tags survive serialization but do not establish hashing support.

Tagged byte-vector output is rejected because the daemon emits only its inner payload, losing the committed wrapper; retain those values as binary. Tagged byte JSON uses numbers from 0 through 255. Raw text must use { message: text }. URL reference JSON is limited to version 1 because the daemon's version-2 output rewrites flags. Native version-2 URL references remain available through binary serialization. Reference presence flags and JSON omit zero optional system IDs and identity-reference hashes, matching the daemon.

PartialMMRData is a library request envelope, not a daemon wire format. Its CLI conversion requires one supported data key per item and rejects bare strings, unknown tags, malformed encodings, unrepresented metadata and priormmr. Supplied salts and hashes must contain exactly 32 bytes. Typed RAWSTRING and prior-MMR fields can still be stored internally; that does not make them executable RPC requests. Valid base64 currently encounters a daemon parsing defect, so the daemon-facing methods reject it; use serializedhex. SignDataRequest itself remains a raw RPC transport and does not apply these checks to arbitrary arguments supplied directly by a caller.

Surface Supported domain / exception
Root construction SHA-256, SHA-256D and Verus-personalized Blake2b; all nine object/MMR combinations tested. Empty roots are zero, singleton roots are unchanged, and hashes use raw wire byte order.
Range ownership Nodes, appended leaves, returned roots/nodes and generated proof hashes are copied. Range layers and view caches are private. Subclasses with private slots, bound methods, non-enumerable configuration or mutable state must override clone() to preserve their behavior and ownership.
Proofs Default Blake2b node proof construction; type-2/type-3 branch verification. Custom hash-node proofs and power-node construction are unsupported.
Failure results Missing positions and equal right siblings return a fresh zero hash. Equal left siblings follow the daemon. Invalid JS types, widths or hash lengths throw.
Numeric limits In-memory ranges are capped at INT32_MAX before append. Serialized branch indices/sizes retain uint32. Proof-index utility inputs must be safe integers; extra-hash counts must fit nonnegative int32, and undefined C++ shifts/counter overflow are rejected. Full uint64 utility inputs are unsupported.
Hash vectors decodeHashVector() permits trailing bytes like daemon FromVector; decodeHashVector(true) requires a correct tag and complete consumption. Nested stream readers retain their offset contract.
Duplicate peaks The named daemon proof-generation defect is excluded; TypeScript selects peaks structurally and preserves correct proofs.
Descriptor hash tags Actual encoded tags are preserved, including when the daemon's faulty deserializer reports default tags instead.
Encryption Captured native/daemon component decryption and full-wrapper bytes agree. Whole-MMR retrieval ignoring its decrypted copy is a daemon defect; this library does not provide wallet encryption.
Not implemented Keccak hashing, power-node construction, getProofBits, range rewind/truncation and proof-chain verification dispatch. Range serialization is explicitly unsupported: the inspected daemon has no corresponding wire format.

Always compare a proof result with an independently trusted nonzero root. A zero result is failure; a nonzero result alone does not prove validity. Like daemon SafeCheck, branch verification does not enforce exact proof length.

The MMR fixture notes document reproducible RPC captures, compiled daemon-method checks, provenance and regeneration. Tests retain the previously captured type-2/type-3 header proofs and verify their trusted roots. No client dependency or resolution change is included here.

Creating an Identity Update Script

This example shows how to define a VerusID, modify it, and generate the corresponding transaction script.

import { Identity, IdentityScript, KeyID, IdentityID } from 'verus-typescript-primitives';
import { BN } from 'bn.js';

// Define a new identity from a JSON structure
const identityJson = {
  "version": 3,
  "flags": 0,
  "primaryaddresses": ["RUm77XHPni9KxsppF6B5geJ83cM4ZR1TPT"],
  "minimumsignatures": 1,
  "name": "MyNewID",
  "parent": "i5w5MuNik5NtLcYmNzcvaoixooEebB6MGV", // VRSC
  "systemid": "i5w5MuNik5NtLcYmNzcvaoixooEebB6MGV", // VRSC
  "revocationauthority": "i5w5MuNik5NtLcYmNzcvaoixooEebB6MGV",

  "recoveryauthority": "i5w5MuNik5NtLcYmNzcvaoixooEebB6MGV",
  "timelock": 0
};

const identity = Identity.fromJson(identityJson);

// Update primary addresses
identity.setPrimaryAddresses(["RKjVHqM4VF2pCfVcwGzKH7CxvfMUE4H6o8"]);

// Lock the identity for 10000 blocks
identity.lock(new BN(10000));

// Generate the output script for an identity update transaction
const idScript = IdentityScript.fromIdentity(identity);
const scriptBuffer = idScript.toBuffer();

console.log('Identity Script Hex:', scriptBuffer.toString('hex'));

Preparing Identity Registration Outputs

NameReservation (legacy) and AdvancedNameReservation (version 1) encode the commit/reveal payloads. getCommitment() hashes their exact serialized bytes with SHA256d. IdentityCommitmentScript and IdentityReservationScript build and parse the corresponding smart transaction outputs, including two-party commitments for permissioned namespaces.

import {
  AdvancedNameReservation, IdentityID, KeyID, TxDestination, IdentityScript,
  IdentityCommitmentScript, IdentityReservationScript,
  resolveIdentityRegistrationName, identityFromJSONForRegistration,
  decodeDestination, R_ADDR_VERSION
} from 'verus-typescript-primitives';

// The wallet supplies and persists a cryptographically random, nonzero 32-byte
// salt before broadcasting the commitment. Do not generate a new salt on retry.
function prepareIdentityRegistration(salt: Buffer, controllerAddress: string) {
  const resolved = resolveIdentityRegistrationName({
    name: 'alice.VRSCTEST@',
    rootSystemName: 'VRSCTEST',
    systemID: 'iJhCezBExJHvtyH3fGhNnt2NhU4Ztkf2yq'
  });
  const reservation = new AdvancedNameReservation({
    name: resolved.name,
    parent: IdentityID.fromAddress(resolved.parent),
    salt
  });
  reservation.validateForCreation();
  const controller = new TxDestination(
    new KeyID(decodeDestination(controllerAddress, R_ADDR_VERSION))
  );
  const identity = identityFromJSONForRegistration({
    version: 3, flags: 0, minimumsignatures: 1, timelock: 0,
    name: resolved.name, parent: resolved.parent, systemid: resolved.systemID,
    primaryaddresses: [controllerAddress],
    revocationauthority: resolved.identityID,
    recoveryauthority: resolved.identityID
  }, resolved);
  return {
    reservation,
    commitmentScript: IdentityCommitmentScript.fromCommitment(reservation.getCommitment(), controller),
    identityScript: IdentityScript.fromIdentity(identity),
    reservationScript: IdentityReservationScript.fromReservation(reservation)
  };
}

For sub-identities, resolve a qualified name such as alice.namespace.VRSCTEST@, or supply a leaf with both parent and parentName. Resolution derives IDs; the client must verify that the parent is an eligible registered currency and issues identities on the selected system. It must also resolve referral/issuer policy. For a required issuer or referral signature, pass its identity TxDestination as the third argument to IdentityCommitmentScript.fromCommitment. The script keeps the controller index separate from its two-of-two spend condition.

Salt and commitment buffers use raw serialized uint256 byte order; JSON uses reversed display hex. Names retain their original case and UTF-8 bytes. Creation validation rejects ambiguous names and requires explicit network context. Legacy reservation address derivation and script construction require an explicit parent i-address, or null for a historical root. Legacy RPC parent metadata is not part of the commitment; fromJSON(json, parent) verifies nameid against the caller's context. Use toJSONWithParent(parent) to include that metadata in legacy reservation JSON; toJSON() emits only its payload fields. Advanced reservation payloads use ordinary commitment hashes; the separately supported tagged CommitmentHash token format is not a name registration commitment.

Historical advanced reservations with a null parent require explicit chain context: use getIdentityAddress(rootSystemName), toJSONWithRootSystem(rootSystemName), and fromJSON(json, rootSystemName). Their wire payload alone cannot identify the root namespace. Identity.fromBuffer(bytes, offset, parseVdxfObjects, rootSystemName) can also reconstruct the omitted system ID of a version 1 identity; Identity.toJson(rootSystemName) supplies the same context for JSON projection.

Use validateIdentityForRegistration(identity, resolved) for an already constructed full Identity, or the stricter JSON entry point above to validate original address versions before parsing. These creation helpers currently support version 3, zero flags/timelock, and R-address primary authorities; compressed public-key principals are unsupported by the existing Principal serializer. They reject PartialIdentity. Historical reservation parsing is separate from creation checks; unknown reservation versions are rejected rather than reinterpreted.

CurrencyIdentityRegistration exposes currency-option predicates and integer registration/referral prices. Its constructor takes atomic amounts; fromJSON() takes RPC coin amounts. currencyAmountToAtomic() accepts exact decimal strings and rejects numbers that cannot preserve atomic precision. GetIdentityHistoryRequest, GetCurrencyStateRequest, and GetTxOutRequest provide the corresponding typed reads. Fees depending on currency state, fractional conversion, funding, transaction assembly/signing, commitment confirmation, and broadcasting remain responsibilities of the client.

These requests emit parameters compatible with the Rust RPC proxy once the methods are whitelisted. Currency-state numeric heights are sent as strings; omitted or nonpositive numeric heights use the current tip, while the explicit string "0" selects genesis. A missing height before a conversion currency is encoded as "", the daemon's string selector for the tip. Numeric heights must be safe integers. Identity-history requests fill skipped intermediate arguments with the daemon defaults (0, 0, false) and omit unused trailing arguments. Request JSON retains the caller's original values.

Offline daemon parity fixtures cover mined registrations, name derivation, independently encoded scripts and identities, historical proofs, currency policy and state, and UTXO reads. Coverage and regeneration instructions are in src/__tests__/fixtures/identity-registration.

Making an RPC API Request

The library provides typed classes for RPC requests. You need to provide your own transport layer (e.g., using axios or node-fetch) to send the formatted request to the Verus daemon.

import { GetIdentityRequest } from 'verus-typescript-primitives';

// Create a request object
const getIdentityRequest = new GetIdentityRequest(
  "VRSCTEST", // Chain ticker
  "VerusID@",  // Name or i-address of the identity
);

// Prepare the request parameters for your transport layer
const [chain, cmd, params] = getIdentityRequest.prepare();

console.log(`Chain: ${chain}`);
console.log(`Command: ${cmd}`);
console.log(`Params: ${JSON.stringify(params, null, 2)}`);

// Example of how you would send this with a hypothetical `sendRpcRequest` function
// async function sendRpcRequest(chain, cmd, params) {
//   const response = await myFetchFunction(`http://127.0.0.1:27486`, {
//     method: 'POST',
//     body: JSON.stringify({
//       jsonrpc: '2.0',
//       id: '1',
//       method: cmd,
//       params: params,
//     }),
//   });
//   return response.json();
// }
//
// sendRpcRequest(chain, cmd, params).then(response => {
//   console.log("RPC Response:", response.result);
// });

Modules

The library is organized into several key modules:

  • pbaas: Contains primitives for Verus Public-Blockchains-as-a-Service (PaaS), including Identity, CurrencyDefinition, ReserveTransfer, and transaction script classes like IdentityScript.
  • vdxf: Manages Verus Data Exchange Format (VDXF) objects. This is crucial for application-level data exchange, such as login confirmations (LoginConsentRequest) and payments (VerusPayInvoice).
  • api: Provides classes that map to the Verus RPC API, offering a structured and type-safe way to construct requests and handle responses.
  • utils: Includes a variety of helper functions for common tasks like address and i-address conversions, cryptographic hashing (hash, hash160), and script manipulation.

Development

To contribute to the development, clone the repository and install the dependencies.

git clone https://github.com/VerusCoin/verus-typescript-primitives.git
cd verus-typescript-primitives
yarn install

Build

Compile the TypeScript source code:

yarn build

Testing

Run the test suite using Jest:

yarn test

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

A collection of classes to organize Verus related data in JS/TS

Resources

Stars

1 star

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages