Encoding & Decoding

Convert between Clarity values and JavaScript types.

Overview

Stacks uses Clarity values (CVs) to represent data in smart contracts. When building applications, you'll need to encode JavaScript values into CVs for contract calls and decode CVs back to JavaScript for display. This guide covers all CV types and conversion patterns.

Basic type conversions

Integers

Convert between JavaScript numbers and Clarity integers:

integers.ts
import { 
  intCV, 
  uintCV, 
  cvToValue,
  cvToJSON 
} from '@stacks/transactions';

// Encoding
const positiveInt = uintCV(42);        // u42
const negativeInt = intCV(-100);       // -100
const largeUint = uintCV(1000000);     // u1000000

// Decoding
const jsValue = cvToValue(positiveInt); // 42
const jsonValue = cvToJSON(positiveInt); // { type: 'uint', value: '42' }

// Working with BigInt for large numbers
const bigNumber = uintCV(BigInt('123456789012345678901234567890'));
const decoded = cvToValue(bigNumber); // '123456789012345678901234567890'

Booleans

Simple true/false values:

Strings

Handle ASCII and UTF-8 strings:

Principals

Encode Stacks addresses and contract principals:

Complex type handling

Buffers

Work with binary data:

Optional values

Handle Clarity's optional type:

Response values

Handle contract response types:

Tuples

Create and decode structured data:

Lists

Work with arrays of values:

Advanced encoding patterns

Dynamic type encoding

Build encoders for runtime values:

Type-safe decoding

Create decoders with type validation:

Batch encoding utilities

Encode multiple values efficiently:

Serialization and deserialization

Work with serialized Clarity values:

Common conversion patterns

Contract call arguments

Prepare arguments for contract calls:

Response handling

Process contract responses:

Best practices

  • Validate types: Always check CV types before decoding

  • Handle edge cases: Consider null, undefined, and empty values

  • Use appropriate string types: ASCII for simple text, UTF-8 for international

  • Preserve precision: Use BigInt for large numbers

  • Type narrowing: Use TypeScript type guards for safety

Common mistakes

String type confusion
Number overflow

Last updated

Was this helpful?