Options
All
  • Public
  • Public/Protected
  • All
Menu

Package transactions

@stacks/transactions npm

Construct, decode transactions and work with Clarity smart contracts on the Stacks blockchain.

Installation

npm install @stacks/transactions

Overview

This library supports the creation of the following Stacks transaction types:

  1. STX token transfer
  2. Smart contract deploy
  3. Smart contract function call

Key Generation

import { createStacksPrivateKey, makeRandomPrivKey, getPublicKey } from '@stacks/transactions';

// Random key
const privateKey = makeRandomPrivKey();
// Get public key from private
const publicKey = getPublicKey(privateKey);

// Private key from hex string
const key = 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01';
const privateKey = createStacksPrivateKey(key);

STX Token Transfer Transaction

import { makeSTXTokenTransfer, broadcastTransaction, AnchorMode } from '@stacks/transactions';

const txOptions = {
recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
amount: 12345n,
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
network: 'testnet', // for mainnet, use 'mainnet'
memo: 'test memo',
nonce: 0n, // set a nonce manually if you don't want builder to fetch from a Stacks node
fee: 200n, // set a tx fee if you don't want the builder to estimate
anchorMode: AnchorMode.Any,
};

const transaction = await makeSTXTokenTransfer(txOptions);

// to see the raw serialized tx
const serializedTx = transaction.serialize().toString('hex');

// broadcasting transaction to the specified network
const broadcastResponse = await broadcastTransaction(transaction);
const txId = broadcastResponse.txid;

Smart Contract Deploy Transaction

import { makeContractDeploy, broadcastTransaction, AnchorMode } from '@stacks/transactions';
import { StacksTestnet, StacksMainnet } from '@stacks/network';
import { readFileSync } from 'fs';

// for mainnet, use `StacksMainnet()`
const network = new StacksTestnet();

const txOptions = {
contractName: 'contract_name',
codeBody: readFileSync('/path/to/contract.clar').toString(),
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
network,
anchorMode: AnchorMode.Any,
};

const transaction = await makeContractDeploy(txOptions);

const broadcastResponse = await broadcastTransaction(transaction, network);
const txId = broadcastResponse.txid;

Smart Contract Function Call

import {
makeContractCall,
broadcastTransaction,
AnchorMode,
FungibleConditionCode,
makeStandardSTXPostCondition,
bufferCVFromString,
} from '@stacks/transactions';
import { StacksTestnet, StacksMainnet } from '@stacks/network';

// for mainnet, use `StacksMainnet()`
const network = new StacksTestnet();

// Add an optional post condition
// See below for details on constructing post conditions
const postConditionAddress = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE';
const postConditionCode = FungibleConditionCode.GreaterEqual;
const postConditionAmount = 1000000n;
const postConditions = [
makeStandardSTXPostCondition(postConditionAddress, postConditionCode, postConditionAmount),
];

const txOptions = {
contractAddress: 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X',
contractName: 'contract_name',
functionName: 'contract_function',
functionArgs: [bufferCVFromString('foo')],
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
validateWithAbi: true,
network,
postConditions,
anchorMode: AnchorMode.Any,
};

const transaction = await makeContractCall(txOptions);

const broadcastResponse = await broadcastTransaction(transaction, network);
const txId = broadcastResponse.txid;

In this example we construct a contract-call transaction with a post condition. We have set the validateWithAbi option to true, so the makeContractCall builder will attempt to fetch this contracts ABI from the specified Stacks network, and validate that the provided functionArgs match what is described in the ABI. This should help you avoid constructing invalid contract-call transactions. If you would prefer to provide your own ABI instead of fetching it from the network, the validateWithABI option also accepts ClarityABI objects, which can be constructed from ABI files like so:

import { ClarityAbi } from '@stacks/transactions';
import { readFileSync } from 'fs';

const abi: ClarityAbi = JSON.parse(readFileSync('abi.json').toString());
// For sample abi json see: stacks.js/packages/transactions/tests/abi/test-abi.json

Sponsoring Transactions

To generate a sponsored transaction, first create and sign the transaction as the origin. The sponsored property in the options object must be set to true.

import { makeContractCall, BufferCV, AnchorMode, bufferCVFromString } from '@stacks/transactions';

const txOptions = {
contractAddress: 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X',
contractName: 'contract_name',
functionName: 'contract_function',
functionArgs: [bufferCVFromString('foo')],
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
validateWithAbi: true,
sponsored: true,
anchorMode: AnchorMode.Any,
};

const transaction = await makeContractCall(txOptions);
const serializedTx = transaction.serialize().toString('hex');

The serialized transaction can now be passed to the sponsoring party which will sign the sponsor portion of the transaction and set the fee.

import {
sponsorTransaction,
BufferReader,
deserializeTransaction,
broadcastTransaction,
} from '@stacks/transactions';
import { StacksTestnet, StacksMainnet } from '@stacks/network';

const bufferReader = new BufferReader(Buffer.from(serializedTx, 'hex'));
const deserializedTx = deserializeTransaction(bufferReader);
const sponsorKey = '770287b9471081c8acd37d57190c7a70f0da2633311cc120853537362d32e67c01';
const fee = 1000n;

const sponsorOptions = {
transaction: deserializedTx,
sponsorPrivateKey: sponsorKey,
fee,
};

const sponsoredTx = await sponsorTransaction(sponsorOptions);

// for mainnet, use `StacksMainnet()`
const network = new StacksTestnet();

const broadcastResponse = await broadcastTransaction(sponsoredTx, network);
const txId = broadcastResponse.txid;

Supporting multi-signature transactions

To generate a multi-sig transaction, first create an unsigned transaction. The numSignatures and publicKeys properties in the options object must be set:

import {
makeUnsignedSTXTokenTransfer,
createStacksPrivateKey,
deserializeTransaction,
pubKeyfromPrivKey,
publicKeyToString,
TransactionSigner,
standardPrincipalCV,
BufferReader,
AnchorMode,
} from '@stacks/transactions';

const recipient = standardPrincipalCV('SP3FGQ8...');
const amount = 2500000n;
const fee = 0n;
const memo = 'test memo';

// private keys of the participants in the transaction
const privKeyStrings = ['6d430bb9...', '2a584d89...', 'd5200dee...'];

// create private key objects from string array
const privKeys = privKeyStrings.map(createStacksPrivateKey);

// corresponding public keys
const pubKeys = privKeyStrings.map(pubKeyfromPrivKey);

// create public key string array from objects
const pubKeyStrings = pubKeys.map(publicKeyToString);

const transaction = await makeUnsignedSTXTokenTransfer({
recipient,
amount,
fee,
memo,
numSignatures: 2, // number of signature required
publicKeys: pubKeyStrings, // public key string array with >= numSignatures elements
anchorMode: AnchorMode.Any,
});

const serializedTx = transaction.serialize();

This transaction payload can be passed along to other participants to sign. In addition to meeting the numSignatures requirement, the public keys of the parties who did not sign the transaction must be appended to the signature.

// deserialize and sign transaction
const bufferReader = new BufferReader(serializedTx);
// Partially signed or unsigned multi-sig tx can be deserialized to add the required signatures
const deserializedTx = deserializeTransaction(bufferReader);

const signer = new TransactionSigner(deserializedTx);

// first signature
signer.signOrigin(privKeys[0]);

// second signature
signer.signOrigin(privKeys[1]);

// after meeting the numSignatures requirement, the public
// keys of the participants who did not sign must be appended
signer.appendOrigin(pubKeys[2]);

// the serialized multi-sig tx
const serializedSignedTx = deserializedTx.serialize();

Calling Read-only Contract Functions

Read-only contract functions can be called without generating or broadcasting a transaction. Instead it works via a direct API call to a Stacks node.

import { bufferCVFromString, callReadOnlyFunction } from '@stacks/transactions';
import { StacksTestnet } from '@stacks/network';

const contractAddress = 'ST3KC0MTNW34S1ZXD36JYKFD3JJMWA01M55DSJ4JE';
const contractName = 'kv-store';
const functionName = 'get-value';
const buffer = bufferCVFromString('foo');
const network = new StacksTestnet();
const senderAddress = 'ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ';

const options = {
contractAddress,
contractName,
functionName,
functionArgs: [buffer],
network,
senderAddress,
};

const result = await callReadOnlyFunction(options);

Constructing Clarity Values

Building transactions that call functions in deployed clarity contracts requires you to construct valid Clarity Values to pass to the function as arguments. The Clarity type system contains the following types:

  • (tuple (key-name-0 key-type-0) (key-name-1 key-type-1) ...)
    • a typed tuple with named fields.
  • (list max-len entry-type)
    • a list of maximum length max-len, with entries of type entry-type
  • (response ok-type err-type)
    • object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior.
  • (optional some-type)
    • an option type for objects that can either be (some value) or none
  • (buff max-len)
    • byte buffer or maximum length max-len.
  • principal
    • object representing a principal (whether a contract principal or standard principal).
  • bool
    • boolean value ('true or 'false)
  • int
    • signed 128-bit integer
  • uint
    • unsigned 128-bit integer

This library contains Typescript types and classes that map to the Clarity types, in order to make it easy to construct well-typed Clarity values in Javascript. These types all extend the abstract class ClarityValue.

import {
trueCV,
falseCV,
noneCV,
someCV,
intCV,
uintCV,
standardPrincipalCV,
contractPrincipalCV,
responseErrorCV,
responseOkCV,
listCV,
tupleCV,
bufferCV,
} from '@stacks/transactions';
import { Buffer } from '@stacks/common';

// construct boolean clarity values
const t = trueCV();
const f = falseCV();

// construct optional clarity values
const nothing = noneCV();
const something = someCV(t);

// construct a buffer clarity value from an existing Buffer
const buffer = Buffer.from('foo');
const bufCV = bufferCV(buffer);

// construct signed and unsigned integer clarity values
const i = intCV(-10);
const u = uintCV(10);

// construct principal clarity values
const address = 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B';
const contractName = 'contract-name';
const spCV = standardPrincipalCV(address);
const cpCV = contractPrincipalCV(address, contractName);

// construct response clarity values
const errCV = responseErrorCV(trueCV());
const okCV = responseOkCV(falseCV());

// construct tuple clarity values
const tupCV = tupleCV({
a: intCV(1),
b: trueCV(),
c: falseCV(),
});

// construct list clarity values
const l = listCV([trueCV(), falseCV()]);

If you develop in Typescript, the type checker can help prevent you from creating wrongly-typed Clarity values. For example, the following code won't compile since in Clarity lists are homogeneous, meaning they can only contain values of a single type. It is important to include the type variable BooleanCV in this example, otherwise the typescript type checker won't know which type the list is of and won't enforce homogeneity.

const l = listCV<BooleanCV>([trueCV(), intCV(1)]);

Post Conditions

Three types of post conditions can be added to transactions:

  1. STX post condition
  2. Fungible token post condition
  3. Non-Fungible token post condition

For details see: https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#transaction-post-conditions

STX post condition

import {
FungibleConditionCode,
makeStandardSTXPostCondition,
makeContractSTXPostCondition,
} from '@stacks/transactions';

// With a standard principal
const postConditionAddress = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE';
const postConditionCode = FungibleConditionCode.GreaterEqual;
const postConditionAmount = 12345n;

const standardSTXPostCondition = makeStandardSTXPostCondition(
postConditionAddress,
postConditionCode,
postConditionAmount
);

// With a contract principal
const contractAddress = 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X';
const contractName = 'test-contract';

const contractSTXPostCondition = makeContractSTXPostCondition(
contractAddress,
contractName,
postConditionCode,
postConditionAmount
);

Fungible token post condition

import {
FungibleConditionCode,
createAssetInfo,
makeStandardFungiblePostCondition,
} from '@stacks/transactions';

// With a standard principal
const postConditionAddress = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE';
const postConditionCode = FungibleConditionCode.GreaterEqual;
const postConditionAmount = 12345n;
const assetAddress = 'SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ';
const assetContractName = 'test-asset-contract';
const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName);

const standardFungiblePostCondition = makeStandardFungiblePostCondition(
postConditionAddress,
postConditionCode,
postConditionAmount,
fungibleAssetInfo
);

// With a contract principal
const contractAddress = 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X';
const contractName = 'test-contract';
const assetAddress = 'SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ';
const assetContractName = 'test-asset-contract';
const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName);

const contractFungiblePostCondition = makeContractFungiblePostCondition(
contractAddress,
contractName,
postConditionCode,
postConditionAmount,
fungibleAssetInfo
);

Non-fungible token post condition

import {
NonFungibleConditionCode,
createAssetInfo,
makeStandardNonFungiblePostCondition,
makeContractNonFungiblePostCondition,
bufferCVFromString,
} from '@stacks/transactions';

// With a standard principal
const postConditionAddress = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE';
const postConditionCode = NonFungibleConditionCode.Owns;
const assetAddress = 'SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ';
const assetContractName = 'test-asset-contract';
const assetName = 'test-asset';
const tokenAssetName = bufferCVFromString('test-token-asset');
const nonFungibleAssetInfo = createAssetInfo(assetAddress, assetContractName, assetName);

const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition(
postConditionAddress,
postConditionCode,
nonFungibleAssetInfo,
tokenAssetName
);

// With a contract principal
const contractAddress = 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X';
const contractName = 'test-contract';

const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition(
contractAddress,
contractName,
postConditionCode,
nonFungibleAssetInfo,
tokenAssetName
);

Helper functions

Conversion of Clarity Values to JSON

Clarity Values represent values of Clarity contracts. If a JSON format is required the helper function cvToJSON can be used.

import { cvToJSON, hexToCV } from '@stacks/transactions';

cvToJSON(hexToCV(tx.tx_result.hex));

Index

Enumerations

Classes

Interfaces

Type Aliases

Variables

Functions

Type Aliases

BadAddressVersionByteRejection: { error: string; reason: BadAddressVersionByte; reason_data?: undefined; txid: string }

Type declaration

BadFunctionArgumentRejection: { error: string; reason: BadFunctionArgument; reason_data: { message: string }; txid: string }

Type declaration

  • error: string
  • reason: BadFunctionArgument
  • reason_data: { message: string }
    • message: string
  • txid: string
BadNonceRejection: { error: string; reason: BadNonce; reason_data: { actual: number; expected: number; is_origin: boolean; principal: boolean }; txid: string }

Type declaration

  • error: string
  • reason: BadNonce
  • reason_data: { actual: number; expected: number; is_origin: boolean; principal: boolean }
    • actual: number
    • expected: number
    • is_origin: boolean
    • principal: boolean
  • txid: string
BooleanCV: TrueCV | FalseCV
ClarityAbiTypeBool: "bool"
ClarityAbiTypeBuffer: { buffer: { length: number } }

Type declaration

  • buffer: { length: number }
    • length: number
ClarityAbiTypeInt128: "int128"
ClarityAbiTypeList: { list: { length: number; type: ClarityAbiType } }

Type declaration

ClarityAbiTypeNone: "none"
ClarityAbiTypeOptional: { optional: ClarityAbiType }

Type declaration

ClarityAbiTypePrincipal: "principal"
ClarityAbiTypeResponse: { response: { error: ClarityAbiType; ok: ClarityAbiType } }

Type declaration

ClarityAbiTypeStringAscii: { string-ascii: { length: number } }

Type declaration

  • string-ascii: { length: number }
    • length: number
ClarityAbiTypeStringUtf8: { string-utf8: { length: number } }

Type declaration

  • string-utf8: { length: number }
    • length: number
ClarityAbiTypeTraitReference: "trait_reference"
ClarityAbiTypeTuple: { tuple: { name: string; type: ClarityAbiType }[] }

Type declaration

ClarityAbiTypeUInt128: "uint128"
ContractAlreadyExistsRejection: { error: string; reason: ContractAlreadyExists; reason_data: { contract_identifier: string }; txid: string }

Type declaration

  • error: string
  • reason: ContractAlreadyExists
  • reason_data: { contract_identifier: string }
    • contract_identifier: string
  • txid: string
DecodedStructuredData: { domainHash: Buffer; messageHash: Buffer }

Type declaration

  • domainHash: Buffer
  • messageHash: Buffer
DeserializationRejection: { error: string; reason: Deserialization; reason_data: { message: string }; txid: string }

Type declaration

  • error: string
  • reason: Deserialization
  • reason_data: { message: string }
    • message: string
  • txid: string
FeeTooLowRejection: { error: string; reason: FeeTooLow; reason_data: { actual: number; expected: number }; txid: string }

Type declaration

  • error: string
  • reason: FeeTooLow
  • reason_data: { actual: number; expected: number }
    • actual: number
    • expected: number
  • txid: string
MultiSigHashMode: SerializeP2SH | SerializeP2WSH
NoCoinbaseViaMempoolRejection: { error: string; reason: NoCoinbaseViaMempool; reason_data?: undefined; txid: string }

Type declaration

NoSuchContractRejection: { error: string; reason: NoSuchContract; reason_data?: undefined; txid: string }

Type declaration

  • error: string
  • reason: NoSuchContract
  • Optional reason_data?: undefined
  • txid: string
NoSuchPublicFunctionRejection: { error: string; reason: NoSuchPublicFunction; reason_data?: undefined; txid: string }

Type declaration

NotEnoughFundsRejection: { error: string; reason: NotEnoughFunds; reason_data: { actual: string; expected: string }; txid: string }

Type declaration

  • error: string
  • reason: NotEnoughFunds
  • reason_data: { actual: string; expected: string }
    • actual: string
    • expected: string
  • txid: string
OptionalCV<T>: NoneCV | SomeCV<T>

Type Parameters

PoisonMicroblockHasUnknownPubKeyHashRejection: { error: string; reason: PoisonMicroblockHasUnknownPubKeyHash; reason_data?: undefined; txid: string }

Type declaration

PoisonMicroblockIsInvalidRejection: { error: string; reason: PoisonMicroblockIsInvalid; reason_data?: undefined; txid: string }

Type declaration

PoisonMicroblocksDoNotConflictRejection: { error: string; reason: PoisonMicroblocksDoNotConflict; reason_data?: undefined; txid: string }

Type declaration

PostConditionPrincipal: StandardPrincipal | ContractPrincipal
SerializationRejection: { error: string; reason: Serialization; reason_data: { message: string }; txid: string }

Type declaration

  • error: string
  • reason: Serialization
  • reason_data: { message: string }
    • message: string
  • txid: string
ServerFailureDatabaseRejection: { error: string; reason: ServerFailureDatabase; reason_data: { message: string }; txid: string }

Type declaration

ServerFailureNoSuchChainTipRejection: { error: string; reason: ServerFailureNoSuchChainTip; reason_data?: undefined; txid: string }

Type declaration

ServerFailureOtherRejection: { error: string; reason: ServerFailureOther; reason_data: { message: string }; txid: string }

Type declaration

  • error: string
  • reason: ServerFailureOther
  • reason_data: { message: string }
    • message: string
  • txid: string
SignatureValidationRejection: { error: string; reason: SignatureValidation; reason_data: { message: string }; txid: string }

Type declaration

  • error: string
  • reason: SignatureValidation
  • reason_data: { message: string }
    • message: string
  • txid: string
SingleSigHashMode: SerializeP2PKH | SerializeP2WPKH
TransactionAuthFieldContents: StacksPublicKey | MessageSignature
TxBroadcastResultOk: { error?: undefined; reason?: undefined; reason_data?: undefined; txid: string }

Type declaration

  • Optional error?: undefined
  • Optional reason?: undefined
  • Optional reason_data?: undefined
  • txid: string

Variables

CLARITY_INT_BYTE_SIZE: 16 = 16
CLARITY_INT_SIZE: 128 = 128
COINBASE_BUFFER_LENGTH_BYTES: 32 = 32
COMPRESSED_PUBKEY_LENGTH_BYTES: 32 = 32
DEFAULT_CHAIN_ID: Mainnet = ChainID.Mainnet
DEFAULT_CORE_NODE_API_URL: "https://stacks-node-api.mainnet.stacks.co" = 'https://stacks-node-api.mainnet.stacks.co'
DEFAULT_TRANSACTION_VERSION: Mainnet = TransactionVersion.Mainnet
MAX_STRING_LENGTH_BYTES: 128 = 128
MEMO_MAX_LENGTH_BYTES: 34 = 34
RECOVERABLE_ECDSA_SIG_LENGTH_BYTES: 65 = 65
STRUCTURED_DATA_PREFIX: Buffer = ...
UNCOMPRESSED_PUBKEY_LENGTH_BYTES: 64 = 64

Functions

  • Parameters

    Returns string

  • Parameters

    Returns Address

  • addressToString(address: Address): string
  • Parameters

    Returns string

  • Broadcast the signed transaction to a core node

    Parameters

    • rawTx: Buffer

      the raw serialized transaction buffer to broadcast

    • url: string

      the broadcast endpoint URL

    • Optional attachment: Buffer
    • fetchFn: FetchFn = ...

    Returns Promise<TxBroadcastResult>

    that resolves to a response if the operation succeeds

  • Broadcast the signed transaction to a core node

    Parameters

    • transaction: StacksTransaction

      the token transfer transaction to broadcast

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to broadcast transaction to

    • Optional attachment: Buffer

    Returns Promise<TxBroadcastResult>

    that resolves to a response if the operation succeeds

  • Converts a buffer to BufferCV clarity type

    example
     import { bufferCV } from '@stacks/transactions';

    const buffer = Buffer.from('this is a test');
    const buf = bufferCV(buffer);
    // { type: 2, buffer: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74> }
    const value = buf.buffer.toString();
    // this is a test
    visit

    clarity test cases for more examples

    Parameters

    • buffer: Buffer

      value to be converted to clarity type

    Returns BufferCV

    returns instance of type BufferCV

  • bufferCVFromString(str: string): BufferCV
  • Converts a string to BufferCV clarity type

    example
     import { bufferCVFromString } from '@stacks/transactions';

    const str = 'this is a test';
    const buf = bufferCVFromString(str);
    // { type: 2, buffer: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74> }
    const value = buf.buffer.toString();
    // this is a test
    visit

    clarity test cases for more examples

    Parameters

    • str: string

    Returns BufferCV

    returns instance of type BufferCV

  • Calls a function as read-only from a contract interface It is not necessary that the function is defined as read-only in the contract

    Parameters

    • readOnlyFunctionOptions: ReadOnlyFunctionOptions

      the options object

      Returns an object with a status bool (okay) and a result string that is a serialized clarity value in hex format.

    Returns Promise<ClarityValue>

  • cloneDeep<T>(obj: T): T
  • Type Parameters

    • T

    Parameters

    • obj: T

    Returns T

  • Parameters

    • content: string

    Returns LengthPrefixedString

  • Parameters

    • publicKey: string | Buffer

    Returns StacksPublicKey

  • Converts stx address in to ContractPrincipalCV clarity type

    example
     import { contractPrincipalCV } from '@stacks/transactions';

    const contractAddress = contractPrincipalCV('SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', 'test');
    // { type: 6, address: { type: 0, version: 22, hash160: 'a5d9d331000f5b79578ce56bd157f29a9056f0d6' }, contractName: { type: 2, content: 'test', lengthPrefixBytes: 1, maxLengthBytes: 128 } }
    visit

    clarity test cases for more examples

    Parameters

    • addressString: string
    • contractName: string

    Returns ContractPrincipalCV

    returns instance of type ContractPrincipalCV

  • Create ContractPrincipalCV from Address type

    example
     import { contractPrincipalCVFromAddress, createLPString, createAddress } from '@stacks/transactions';

    const contractAddressCV = contractPrincipalCVFromAddress(createAddress('SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B'), createLPString('test'));

    // { type: 6, address: { type: 0, version: 22, hash160: 'a5d9d331000f5b79578ce56bd157f29a9056f0d6' }, contractName: { type: 2, content: 'test', lengthPrefixBytes: 1, maxLengthBytes: 128 } }
    visit

    clarity test cases for more examples

    Parameters

    Returns ContractPrincipalCV

    returns instance of type ContractPrincipalCV

  • createAddress(c32AddressString: string): Address
  • Parameters

    • c32AddressString: string

    Returns Address

  • createAssetInfo(addressString: string, contractName: string, assetName: string): AssetInfo
  • Parameters

    • addressString: string
    • contractName: string
    • assetName: string

    Returns AssetInfo

  • createContractPrincipal(addressString: string, contractName: string): ContractPrincipal
  • Parameters

    • addressString: string
    • contractName: string

    Returns ContractPrincipal

  • Returns Address

  • Type Parameters

    Parameters

    • values: T[]
    • Optional lengthPrefixBytes: number

    Returns LengthPrefixedList

  • Parameters

    • content: string

    Returns LengthPrefixedString

  • Parameters

    • content: string
    • lengthPrefixBytes: number

    Returns LengthPrefixedString

  • Parameters

    • content: string
    • lengthPrefixBytes: number
    • maxLengthBytes: number

    Returns LengthPrefixedString

  • Parameters

    • content: string

    Returns MemoString

  • Parameters

    • signature: string

    Returns MessageSignature

  • Parameters

    • key: string | Buffer

    Returns StacksPrivateKey

  • Parameters

    • key: string

    Returns StacksPublicKey

  • Parameters

    • addressString: string

    Returns StandardPrincipal

  • Converts a clarity value to a hex encoded string with 0x prefix

    Parameters

    Returns string

  • Parameters

    Returns any

  • cvToString(val: ClarityValue, encoding?: "hex" | "tryAscii"): string
  • Parameters

    Returns string

  • cvToValue(val: ClarityValue, strictJsonCompat?: boolean): any
  • Parameters

    • val: ClarityValue
    • strictJsonCompat: boolean = false

      If true then ints and uints are returned as JSON serializable numbers when less than or equal to 53 bit length, otherwise string wrapped integers when larger than 53 bits. If false, they are returned as js native bigints which are not JSON serializable.

    Returns any

  • Parameters

    • signature: string | Buffer

    Returns DecodedStructuredData

  • Parameters

    Returns Address

  • deserializeCV<T>(serializedClarityValue: string | Buffer | BufferReader): T
  • Deserializes clarity value to clarity type

    example
     import { intCV, serializeCV, deserializeCV } from '@stacks/transactions';

    const serialized = serializeCV(intCV(100)); // Similarly works for other clarity types as well like listCV, booleanCV ...

    // <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 64>

    const deserialized = deserializeCV(serialized);
    // { type: 0, value: 100n }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    Returns T

    returns the clarity type instance

  • Parameters

    • bufferReader: BufferReader
    • Optional prefixBytes: number
    • Optional maxLength: number

    Returns LengthPrefixedString

  • Parameters

    Returns StacksTransaction

  • Returns MessageSignature

  • deprecated

    Use the new estimateTransaction function insterad.

    Estimate the total transaction fee in microstacks for a contract deploy

    Parameters

    • transaction: StacksTransaction

      the token transfer transaction to estimate fees for

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to estimate transaction for

    Returns Promise<bigint>

    a promise that resolves to number of microstacks per byte

  • deprecated

    Use the new estimateTransaction function insterad.

    Estimate the total transaction fee in microstacks for a contract function call

    Parameters

    • transaction: StacksTransaction

      the token transfer transaction to estimate fees for

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to estimate transaction for

    Returns Promise<bigint>

    a promise that resolves to number of microstacks per byte

  • estimateTransaction(transactionPayload: Payload, estimatedLen?: number, network?: "mainnet" | "testnet" | StacksNetwork): Promise<[FeeEstimation, FeeEstimation, FeeEstimation]>
  • Estimate the total transaction fee in microstacks for a Stacks transaction

    Parameters

    • transactionPayload: Payload
    • Optional estimatedLen: number

      is an optional argument that provides the endpoint with an estimation of the final length (in bytes) of the transaction, including any post-conditions and signatures

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to estimate transaction fees for

    Returns Promise<[FeeEstimation, FeeEstimation, FeeEstimation]>

    a promise that resolves to FeeEstimate

  • Estimates transaction byte length Context:

    1. Multi-sig transaction byte length increases by adding signatures which causes the incorrect fee estimation because the fee value is set while creating unsigned transaction
    2. Single-sig transaction byte length remain same due to empty message signature which allocates the space for signature

    Parameters

    Returns number

    Estimated transaction byte length

  • deprecated

    Use the new estimateTransaction function insterad.

    Estimate the total transaction fee in microstacks for a token transfer

    Parameters

    • transaction: StacksTransaction

      the token transfer transaction to estimate fees for

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to estimate transaction for

    Returns Promise<bigint>

    a promise that resolves to number of microstacks per byte

  • exceedsMaxLengthBytes(string: string, maxLengthBytes: number): boolean
  • Parameters

    • string: string
    • maxLengthBytes: number

    Returns boolean

  • Converts false to BooleanCV clarity type

    example
     import { falseCV } from '@stacks/transactions';

    const falseCV = falseCV();
    // { type: 4 }
    visit

    clarity test cases for more examples

    Returns BooleanCV

    returns instance of type BooleanCV

  • Fetch a contract's ABI

    Parameters

    • address: string

      the contracts address

    • contractName: string

      the contracts name

    • network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to broadcast transaction to

    Returns Promise<ClarityAbi>

    that resolves to a ClarityAbi if the operation succeeds

  • getAddressFromPrivateKey(privateKey: string | Buffer, transactionVersion?: TransactionVersion): string
  • Creates a P2PKH address string from the given private key and tx version.

    Parameters

    • privateKey: string | Buffer
    • transactionVersion: TransactionVersion = TransactionVersion.Mainnet

    Returns string

  • getAddressFromPublicKey(publicKey: string | Buffer, transactionVersion?: TransactionVersion): string
  • Creates a P2PKH address string from the given public key and tx version.

    Parameters

    • publicKey: string | Buffer
    • transactionVersion: TransactionVersion = TransactionVersion.Mainnet

    Returns string

  • Parameters

    Returns string

  • Parameters

    Returns bigint

  • getNonce(address: string, network?: "mainnet" | "testnet" | StacksNetwork): Promise<bigint>
  • Lookup the nonce for an address from a core node

    Parameters

    • address: string

      the c32check address to look up

    • Optional network: "mainnet" | "testnet" | StacksNetwork

      the Stacks network to look up address on

    Returns Promise<bigint>

    a promise that resolves to an integer

  • Parameters

    Returns string

  • hash160(input: Buffer): Buffer
  • Parameters

    • input: Buffer

    Returns Buffer

  • hashP2PKH(input: Buffer): string
  • Parameters

    • input: Buffer

    Returns string

  • hashP2SH(numSigs: number, pubKeys: Buffer[]): string
  • Parameters

    • numSigs: number
    • pubKeys: Buffer[]

    Returns string

  • hashP2WPKH(input: Buffer): string
  • Parameters

    • input: Buffer

    Returns string

  • hashP2WSH(numSigs: number, pubKeys: Buffer[]): string
  • Parameters

    • numSigs: number
    • pubKeys: Buffer[]

    Returns string

  • Parameters

    Returns Buffer

  • Converts a hex encoded string to a clarity value

    Parameters

    • hex: string

      the hex encoded string with or without 0x prefix

    Returns ClarityValue

  • Converts IntegerType in to IntCV clarity type

    example
     import { intCV } from '@stacks/transactions';

    const value = intCV('100'); // parameter any of type: number | string | bigint | Uint8Array | BN
    // { type: 0, value: 100n }
    visit

    clarity test cases for more examples

    Parameters

    Returns IntCV

    returns instance of type IntCV

  • isClarityName(name: string): boolean
  • Parameters

    • name: string

    Returns boolean

  • Parameters

    Returns boolean

  • leftPadHex(hexString: string): string
  • Parameters

    • hexString: string

    Returns string

  • leftPadHexToLength(hexString: string, length: number): string
  • Parameters

    • hexString: string
    • length: number

    Returns string

  • listCV<T>(values: T[]): ListCV<T>
  • Create list of clarity types

    example
     import { listCV, intCV } from '@stacks/transactions';

    const list = listCV([intCV(1), intCV(2), intCV(3), intCV(-4)]);
    // { type: 11, list: [ { type: 0, value: 1n }, { type: 0, value: 2n }, { type: 0, value: 3n }, { type: 0, value: -4n } ] }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    • values: T[]

    Returns ListCV<T>

    returns instance of type ListCV

  • Generates a Clarity smart contract deploy transaction

    Parameters

    • txOptions: ContractDeployOptions

      an options object for the contract deploy

      Returns a signed Stacks smart contract deploy transaction.

    Returns Promise<StacksTransaction>

  • Generates a fungible token post condition with a contract principal

    Returns a fungible token post condition object

    Parameters

    • address: string

      the c32check address

    • contractName: string

      the name of the contract

    • conditionCode: FungibleConditionCode

      the condition code

    • amount: IntegerType

      the amount of fungible tokens

    • assetInfo: string | AssetInfo

      asset info describing the fungible token

    Returns FungiblePostCondition

  • Generates a non-fungible token post condition with a contract principal

    Returns a non-fungible token post condition object

    Parameters

    • address: string

      the c32check address

    • contractName: string

      the name of the contract

    • conditionCode: NonFungibleConditionCode

      the condition code

    • assetInfo: string | AssetInfo

      asset info describing the non-fungible token

    • assetName: ClarityValue

      asset name describing the non-fungible token

    Returns NonFungiblePostCondition

  • Generates a STX post condition with a contract principal

    Returns a STX post condition object

    Parameters

    • address: string

      the c32check address of the contract

    • contractName: string

      the name of the contract

    • conditionCode: FungibleConditionCode

      the condition code

    • amount: IntegerType

      the amount of STX tokens

    Returns STXPostCondition

  • Parameters

    Returns string

  • Generates a fungible token post condition with a standard principal

    Returns a fungible token post condition object

    Parameters

    • address: string

      the c32check address

    • conditionCode: FungibleConditionCode

      the condition code

    • amount: IntegerType

      the amount of fungible tokens

    • assetInfo: string | AssetInfo

      asset info describing the fungible token

    Returns FungiblePostCondition

  • Generates a non-fungible token post condition with a standard principal

    Returns a non-fungible token post condition object

    Parameters

    • address: string

      the c32check address

    • conditionCode: NonFungibleConditionCode

      the condition code

    • assetInfo: string | AssetInfo

      asset info describing the non-fungible token

    • assetName: ClarityValue

      asset name describing the non-fungible token

    Returns NonFungiblePostCondition

  • Generates a STX post condition with a standard principal

    Returns a STX post condition object

    Parameters

    Returns STXPostCondition

  • Create a null clarity type *

    example
     import { noneCV } from '@stacks/transactions';

    const value = noneCV();
    // { type: 9 }
    visit

    clarity test cases for more examples

    Returns NoneCV

    returns instance of type NoneCV

  • omit<T, K>(obj: T, prop: K): Omit<T, K>
  • Type Parameters

    • T

    • K extends string | number | symbol

    Parameters

    • obj: T
    • prop: K

    Returns Omit<T, K>

  • Parameters

    • id: string

    Returns AssetInfo

  • Parses a principal string for either a standard principal or contract principal.

    example

    "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G.example-contract"

    example

    "SP13N5TE1FBBGRZD1FCM49QDGN32WAXM2E5F8WT2G"

    Parameters

    • principalString: string

      String in the format {address}.{contractName}

    Returns StandardPrincipal | ContractPrincipal

  • Converts the response of a read-only function call into its Clarity Value

    Parameters

    Returns ClarityValue

  • parseRecoverableSignature(signature: string): { r: string; recoveryId: number; s: string }
  • deprecated

    This method is now exported from @stacks/common {@link parseRecoverableSignatureVrs}

    Parameters

    • signature: string

    Returns { r: string; recoveryId: number; s: string }

    • r: string
    • recoveryId: number
    • s: string
  • Convert string input to Clarity value based on contract ABI data. Only handles Clarity primitives and buffers. Responses, optionals, tuples and lists are not supported.

    Parameters

    • input: string

      string to be parsed into Clarity value

    • type: ClarityAbiType

      the contract function argument object

    Returns ClarityValue

    returns a Clarity value

  • Parameters

    Returns string

  • Parameters

    • privateKey: string | Buffer

    Returns StacksPublicKey

  • Parameters

    • data: Buffer

    Returns StacksPublicKey

  • Parameters

    Returns string

  • Parameters

    Returns string

  • Parameters

    Returns string

  • randomBytes(bytesLength?: number): Buffer
  • Use utils.randomBytes to replace randombytes dependency Generates a buffer with random bytes of given length

    Parameters

    • Optional bytesLength: number

    Returns Buffer

    For return type compatibility converting utils.randomBytes return value to buffer

  • Converts ClarityValue to responseErrorCV

    example
     import { responseErrorCV, intCV } from '@stacks/transactions';

    const respErrorCV = responseErrorCV(intCV(1));

    // { type: 8, value: { type: 0, value: 1n } }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    • value: T

    Returns ResponseErrorCV<T>

    returns instance of type responseErrorCV

  • Converts ClarityValue to ResponseOkCV

    example
     import { responseOkCV, intCV } from '@stacks/transactions';

    const respOKCV = responseOkCV(intCV(1));

    // { type: 7, value: { type: 0, value: 1n } }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    • value: T

    Returns ResponseOkCV<T>

    returns instance of type ResponseOkCV

  • rightPadHexToLength(hexString: string, length: number): string
  • Parameters

    • hexString: string
    • length: number

    Returns string

  • serializeAddress(address: Address): Buffer
  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Serializes clarity value to buffer

    example
     import { intCV, serializeCV } from '@stacks/transactions';

    const serialized = serializeCV(intCV(100)); // Similarly works for other clarity types as well like listCV, booleanCV ...

    // <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 64>
    visit

    clarity test cases for more examples

    Parameters

    Returns Buffer

    returns the buffer instance

  • Parameters

    Returns Buffer

  • serializeMemoString(memoString: MemoString): Buffer
  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • serializePayload(payload: PayloadInput): Buffer
  • Parameters

    • payload: PayloadInput

    Returns Buffer

  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Parameters

    Returns Buffer

  • Signs a message using a private key. The resulting signature along with the original message can be verified using verifyMessageSignature

    Parameters

    Returns MessageSignature

    A recoverable signature (in RSV order)

  • deprecated

    The Clarity compatible signMessageHashRsv is preferred, but differs in signature format

    Parameters

    Returns MessageSignature

    A recoverable signature (in VRS order)

  • Converts any ClarityValue in to OptionalCV clarity type

    example
     import { someCV, trueCV } from '@stacks/transactions';

    const value = someCV(trueCV());
    // { type: 10, value: { type: 3 } }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    • value: T

      to be converted to OptionalCV clarity type

    Returns OptionalCV<T>

    returns instance of type OptionalCV

  • Constructs and signs a sponsored transaction as the sponsor

    Parameters

    • sponsorOptions: SponsorOptionsOpts

      the sponsor options object

      Returns a signed sponsored transaction.

    Returns Promise<StacksTransaction>

  • Converts stx address in to StandardPrincipalCV clarity type

    example
     import { standardPrincipalCV } from '@stacks/transactions';

    const addr = standardPrincipalCV('SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B');
    // { type: 5, address: { type: 0, version: 22, hash160: 'a5d9d331000f5b79578ce56bd157f29a9056f0d6' } }
    visit

    clarity test cases for more examples

    Parameters

    • addressString: string

    Returns StandardPrincipalCV

    returns instance of type StandardPrincipalCV

  • Converts stx address in to StandardPrincipalCV clarity type

    example
     import { standardPrincipalCVFromAddress, Address  } from '@stacks/transactions';

    const address: Address = {
    type: 0,
    version: 22,
    hash160: 'a5d9d331000f5b79578ce56bd157f29a9056f0d6'
    };

    const principalCV = standardPrincipalCVFromAddress(address);
    // { type: 5, address: { type: 0, version: 22, hash160: 'a5d9d331000f5b79578ce56bd157f29a9056f0d6' } }
    visit

    clarity test cases for more examples

    Parameters

    Returns StandardPrincipalCV

    returns instance of type StandardPrincipalCV

  • Converts ClarityValue to stringAsciiCV

    example
     import { stringAsciiCV } from '@stacks/transactions';

    const stringAscii = stringAsciiCV('test');

    // { type: 13, data: 'hello' }
    visit

    clarity test cases for more examples

    Parameters

    • data: string

    Returns StringAsciiCV

    returns instance of type StringAsciiCV

  • Converts ClarityValue to stringUtf8CV

    example
     import { stringUtf8CV } from '@stacks/transactions';

    const stringUTF8 = stringUtf8CV('test');

    // { type: 13, data: 'hello' }
    visit

    clarity test cases for more examples

    Parameters

    • data: string

    Returns StringUtf8CV

    returns instance of type stringUtf8CV

  • Converts true to BooleanCV clarity type

    example
     import { trueCV } from '@stacks/transactions';

    const trueCV = trueCV();
    // { type: 3 }
    visit

    clarity test cases for more examples

    Returns BooleanCV

    returns instance of type BooleanCV

  • tupleCV<T>(data: TupleData<T>): TupleCV<TupleData<T>>
  • Create tuple of clarity values

    example
     import { tupleCV, trueCV, falseCV } from '@stacks/transactions';

    const tuple = tupleCV({
    c: trueCV(),
    b: falseCV(),
    a: trueCV(),
    });
    // { type: 12, data: { c: { type: 3 }, b: { type: 4 }, a: { type: 3 } } }
    visit

    clarity test cases for more examples

    Type Parameters

    Parameters

    • data: TupleData<T>

    Returns TupleCV<TupleData<T>>

    returns instance of type clarity tuple

  • txidFromData(data: Buffer): string
  • Parameters

    • data: Buffer

    Returns string

  • Converts IntegerType in to IntCV clarity type

    example
     import { uintCV } from '@stacks/transactions';

    const value = uintCV('100'); // parameter any of type: number | string | bigint | Uint8Array | BN
    // { type: 1, value: 100n }
    visit

    clarity test cases for more examples

    Parameters

    Returns UIntCV

    returns instance of type UIntCV

  • Validates a contract-call payload with a contract ABI

    Parameters

    Returns boolean

    true if the payloads functionArgs type check against those in the ABI

  • validateStacksAddress(stacksAddress: string): boolean
  • Parameters

    • stacksAddress: string

    Returns boolean

  • validateTxId(txid: string): boolean
  • Parameters

    • txid: string

    Returns boolean

  • verifyOrigin(auth: Authorization, initialSigHash: string): string
  • Parameters

    Returns string

Generated using TypeDoc