Corda R3 — New States of Art

On the previous post we learned about Corda main components, and one of them was the state component.

In this article we will implement in code the specified components and build and run the nodes and query a random node to find if the states were created as they were supposed.

You will notice that the Corda project is split into multiple modules, the first one we will take a look is the contracts module. In this module we will find two classes already created as templates, TemplateContract inside the contracts package, and TemplateState inside the states package.

On this article we will be working on the state package and creating our own states. Kotlin language offers the data class objects, that is plain objects that hold values for us. This type of class offers a copy() function out of the box, that is useful when working for states that evolve in the ledge.

We will create four data classes and some enumerates .

To make a data class a state, one must implement the ContractState interface provided by the Corda framework. it’s a way to tell the corda that this object can be persisted on the ledger. By implementing ContractState we are forced to implement the participants field. Corda uses the participants field to know in which vaults/node it should persist the state.

Because there are some common behaviours that developers usually implement, Corda offers a set of sub-interfaces for the ContractState, this way altering and further customising the behaviour of the states.

On our project we are using a LinearState, this interface is used to represent a state that can evolve in a linear fashion, by updating it’s contents values but not changing the linearId field. That’s where the copy() function of data classes are useful.

Every state on our application must be annotated with @BelongsToContract. This annotation let the framework know which smart contract owns this state and is responsible to validate the content for a certain transaction depending on the commands associated with it.

We will implement the contract classes later on this series, for now we can create an empty contract class by implementing the Contract interface.

Usual systems would represent a quantity of money by the use of two fields, one for the amount, such as an BigDecimal, and one for the currency, such as String. Corda makes available an object called Amount<T> — Where T is the type of the object represented by this quantity. — which is the way the framework allows the developers to represent quantities on the ledger in a better way.

But Amount has an drawback that only allows the use of positive quantities. Which makes sense, because you can not own -5 euros for example. Because of that we created a class called Balance provided on my github. Balance is basically a copy of Amount with that restriction removed to allow us to have negative values. Instead we look at the previous sentence like you owe the platform 5 euros.