Skip to main content

StateKey and State Keys

Fabric state is a key-value store with range queries by prefix. There is no "secondary index" in the usual sense here: all we have is the key and the ability to enumerate records that share a common beginning. Therefore the way we build the key entirely determines which queries against the data will be possible at all.

StateKey from @hlf-core/common is a builder of composite keys for a single namespace. It can do two things. The key(...items) method assembles the exact key of a record, joining the parts with the ~ separator. The prefix(...items) method assembles a prefix for a range query and, importantly, always terminates it with the separator.

The key thought is that you can search only by the left part of a composite key. This means the order of the parts, from general to specific, is what defines the available "slices" of the data: whatever we want to enumerate by must stand on the left. And a prefix must end with the separator — otherwise a range query will capture neighboring records, and enumeration by RUB will quietly pull in RUB2 as well.

const key = new StateKey('→coin~account');
key.key('coin_RUB', 'user_abc'); // →coin~account:coin_RUB~user_abc (exact record)
key.prefix('coin_RUB'); // →coin~account:coin_RUB~ (enumeration)

The relationships between entities are built on this same mechanics — they are covered in @hlf-core/chaincode.