Python SCALE Codec Library

1.2.12 · active · verified Mon Apr 13

The `scalecodec` library is a Python implementation of the Substrate-specific Simple Concatenated Aggregate Little-Endian (SCALE) codec. It provides functionality for encoding and decoding data types used in Substrate-based blockchains, such as Polkadot and Kusama. The library is actively maintained, with frequent updates, and is currently at version 1.2.12, with a major version 2.0.0a (alpha) in development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates encoding and decoding a 'Compact' integer, a common SCALE type for large numbers. It shows the typical pattern of initializing a `RuntimeConfiguration` and using `create_scale_object` for type-specific encoding/decoding in `scalecodec` v1.x. For complex types, you would load a chain's metadata into the `RuntimeConfiguration`.

from scalecodec.base import ScaleBytes
from scalecodec.type_registry import RuntimeConfiguration

# Initialize a runtime configuration (required for decoding types based on metadata)
# For simple types, a basic config can be used.
# For complex types, load a specific chain's metadata using load_type_registry()
runtime_config = RuntimeConfiguration()

# Example: Encode a Compact integer
compact_int_value = 100000000000000
compact_encoder = runtime_config.create_scale_object("Compact<u128>")
encoded_data = compact_encoder.encode(compact_int_value)
print(f"Encoded {compact_int_value} (Compact<u128>): {encoded_data.to_hex()}")

# Example: Decode a Compact integer
encoded_hex_value = "0x0b00407a10f35a" # The SCALE encoding for 100,000,000,000,000
compact_decoder = runtime_config.create_scale_object("Compact<u128>")
decoded_value = compact_decoder.decode(ScaleBytes(encoded_hex_value))
print(f"Decoded {encoded_hex_value} (Compact<u128>): {decoded_value}")

view raw JSON →