Skip to main content

@hlf-core/chaincode

This is a high-level, ORM-like library for developing chaincode. It takes over the work with Fabric’s key-value store and gives you familiar concepts instead — entities, parent-child relations, pagination, automatic serialization, and validation. Put simply, we stop thinking in keys and start thinking in objects.

At the core lies IStub — an abstraction over ChaincodeStub from fabric-shim. Reads and writes, range queries, and pagination all go through it, and user, requestId, and transaction are accessible through it as well. On top of IStub sits DatabaseManager — the base key-value manager — and above it EntityManager<T> and its implementation EntityManagerImpl<T> with CRUD over entities. In the typical case it is enough for us to implement two methods: toEntity(item), which reconstructs an entity from raw data, and prefix, which defines the key namespace.

Relations between entities are described by EntityRelation and EntityRelationChild<T, M>. They are arranged so that two keys are written for each relation — a forward one and a reverse one — and this is not redundancy but necessity: the forward key lets you select children by parent, the reverse one lets you remove the relation knowing only the child. Cascading deletion works on the same pair.

class UserManager extends EntityManagerImpl<User> {
public toEntity(item: any): User {
return TransformUtil.toClass(User, item);
}
public get prefix(): string {
return 'user:';
}
}

await userManager.save(user);
const page = await userManager.findPaginated({pageSize: 20, pageBookmark: bm});

The keys that all of this rests on are built by StateKey from @hlf-core/common, and the receiving of the commands themselves in chaincode is provided by @hlf-core/transport-chaincode.