<p>A smart contract is a class that implements the <codeclass="docutils literal"><spanclass="pre">Contract</span></code> interface. For now, they have to be a part of the main
codebase, as dynamic loading of contract code is not yet implemented. Therefore, we start by creating a file named
either <cite>CommercialPaper.kt</cite> or <cite>CommercialPaper.java</cite> in the src/contracts directory with the following contents:</p>
<p>Every contract must have at least a <codeclass="docutils literal"><spanclass="pre">getLegalContractReference()</span></code> and a <codeclass="docutils literal"><spanclass="pre">verify()</span></code> method. In Kotlin we express
a getter without a setter as an immutable property (val). The <em>legal contract reference</em> is supposed to be a hash
of a document that describes the legal contract and may take precedence over the code, in case of a dispute.</p>
<p>The verify method returns nothing. This is intentional: the function either completes correctly, or throws an exception,
in which case the transaction is rejected.</p>
<p>We also need to define a constant hash that would, in a real system, be the hash of the program bytecode. For now
we just set it to a dummy value as dynamic loading and sandboxing of bytecode is not implemented. This constant
isn’t shown in the code snippet but is called <cite>CP_PROGRAM_ID</cite>.</p>
<p>So far, so simple. Now we need to define the commercial paper <em>state</em>, which represents the fact of ownership of a
piece of issued paper.</p>
</div>
<divclass="section"id="states">
<h2>States<aclass="headerlink"href="#states"title="Permalink to this headline">¶</a></h2>
<p>A state is a class that stores data that is checked by the contract.</p>
<spanclass="k">return</span><spanclass="n">SecureHash</span><spanclass="o">.</span><spanclass="na">Companion</span><spanclass="o">.</span><spanclass="na">sha256</span><spanclass="o">(</span><spanclass="s">"java commercial paper (this should be a bytecode hash)"</span><spanclass="o">);</span>
<spanclass="s">"the transaction is signed by the owner of the CP"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">command</span><spanclass="p">.</span><spanclass="n">signers</span><spanclass="p">.</span><spanclass="n">contains</span><spanclass="p">(</span><spanclass="n">input</span><spanclass="p">.</span><spanclass="n">owner</span><spanclass="p">))</span>
<spanclass="k">is</span><spanclass="n">Commands</span><spanclass="p">.</span><spanclass="n">Move</span><spanclass="p">-></span><spanclass="n">requireThat</span><spanclass="p">{</span><spanclass="s">"the output state is present"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">output</span><spanclass="p">!=</span><spanclass="k">null</span><spanclass="p">)</span><spanclass="p">}</span>
<spanclass="k">val</span><spanclass="py">received</span><spanclass="p">=</span><spanclass="n">tx</span><spanclass="p">.</span><spanclass="n">outStates</span><spanclass="p">.</span><spanclass="n">sumCashOrNull</span><spanclass="p">()</span><spanclass="o">?:</span><spanclass="k">throw</span><spanclass="n">IllegalStateException</span><spanclass="p">(</span><spanclass="s">"no cash being redeemed"</span><spanclass="p">)</span>
<spanclass="s">"the paper must have matured"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">input</span><spanclass="p">.</span><spanclass="n">maturityDate</span><spanclass="p"><</span><spanclass="n">tx</span><spanclass="p">.</span><spanclass="n">time</span><spanclass="p">)</span>
<spanclass="s">"the received amount equals the face value"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">received</span><spanclass="p">==</span><spanclass="n">input</span><spanclass="p">.</span><spanclass="n">faceValue</span><spanclass="p">)</span>
<spanclass="s">"the paper must be destroyed"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">output</span><spanclass="p">==</span><spanclass="k">null</span><spanclass="p">)</span>
<spanclass="s">"the face value is not zero"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">output</span><spanclass="p">.</span><spanclass="n">faceValue</span><spanclass="p">.</span><spanclass="n">pennies</span><spanclass="p">></span><spanclass="m">0</span><spanclass="p">)</span>
<spanclass="s">"the maturity date is not in the past"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">output</span><spanclass="p">.</span><spanclass="n">maturityDate</span><spanclass="p">></span><spanclass="n">tx</span><spanclass="p">.</span><spanclass="n">time</span><spanclass="p">)</span>
<spanclass="c1">// Don't allow an existing CP state to be replaced by this issuance.</span>
<spanclass="s">"there is no input state"</span><spanclass="k">by</span><spanclass="n">group</span><spanclass="p">.</span><spanclass="n">inputs</span><spanclass="p">.</span><spanclass="n">isEmpty</span><spanclass="p">()</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: the transaction is signed by the owner of the CP"</span><spanclass="o">);</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: the output state is the same as the input state except for owner"</span><spanclass="o">);</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: no cash being redeemed"</span><spanclass="o">);</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: the paper must have matured"</span><spanclass="o">);</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: the received amount equals the face value"</span><spanclass="o">);</span>
<spanclass="k">throw</span><spanclass="k">new</span><spanclass="n">IllegalStateException</span><spanclass="o">(</span><spanclass="s">"Failed requirement: the paper must be destroyed"</span><spanclass="o">);</span>
<p>This loop is the core logic of the contract.</p>
<p>The first line (first three lines in Java) impose a requirement that there be a single piece of commercial paper in
this group. We do not allow multiple units of CP to be split or merged even if they are owned by the same owner. The
<cite>single()</cite> method is a static <em>extension method</em> defined by the Kotlin standard library: given a list, it throws an
exception if the list size is not 1, otherwise it returns the single item in that list. In Java, this appears as a
regular static method of the type familiar from many FooUtils type singleton classes. In Kotlin, it appears as a
method that can be called on any JDK list. The syntax is slightly different but behind the scenes, the code compiles
to the same bytecodes.</p>
<p>Next, we check that the transaction was signed by the public key that’s marked as the current owner of the commercial
paper. Because the platform has already verified all the digital signatures before the contract begins execution,
all we have to do is verify that the owner’s public key was one of the keys that signed the transaction. The Java code
is straightforward. The Kotlin version looks a little odd: we have a <em>requireThat</em> construct that looks like it’s
built into the language. In fact <em>requireThat</em> is an ordinary function provided by the platform’s contract API. Kotlin
supports the creation of <em>domain specific languages</em> through the intersection of several features of the language, and
we use it here to support the natural listing of requirements. To see what it compiles down to, look at the Java version.
Each <cite>“string” by (expression)</cite> statement inside a <cite>requireThat</cite> turns into an assertion that the given expression is
true, with an exception being thrown that contains the string if not. It’s just another way to write out a regular
assertion, but with the English-language requirement being put front and center.</p>
<p>Next, we take one of two paths, depending on what the type of the command object is.</p>
<p>If the command is a <cite>Move</cite> command, then we simply verify that the output state is actually present: a move is not
allowed to delete the CP from the ledger. The grouping logic already ensured that the details are identical and haven’t
been changed, save for the public key of the owner.</p>
<p>If the command is a <cite>Redeem</cite> command, then the requirements are more complex:</p>
<olclass="arabic simple">
<li>We want to see that the face value of the CP is being moved as a cash claim against some institution, that is, the
issuer of the CP is really paying back the face value.</li>
<li>The transaction must be happening after the maturity date.</li>
<li>The commercial paper must <em>not</em> be propagated by this transaction: it must be deleted, by the group having no
output state. This prevents the same CP being considered redeemable multiple times.</li>
</ol>
<p>To calculate how much cash is moving, we use the <cite>sumCashOrNull</cite> utility method. Again, this is an extension method,
so in Kotlin code it appears as if it was a method on the <cite>List<Cash.State></cite> type even though JDK provides no such
method. In Java we see its true nature: it is actually a static method named <cite>CashKt.sumCashOrNull</cite>. This method simply
returns an <cite>Amount</cite> object containing the sum of all the cash states in the transaction output, or null if there were
no such states <em>or</em> if there were different currencies represented in the outputs! So we can see that this contract
imposes a limitation on the structure of a redemption transaction: you are not allowed to move currencies in the same
transaction that the CP does not involve. This limitation could be addressed with better APIs, if it were to be a
<spanclass="n">expectFailureOfTx</span><spanclass="p">(</span><spanclass="m">1</span><spanclass="p">,</span><spanclass="s">"signed by the claimed issuer"</span><spanclass="p">)</span>
<spanclass="p">}</span>
<spanclass="p">}</span>
<spanclass="p">}</span>
</pre></div>
</div>
</div>
<p>We start by defining a commercial paper state. It will be owned by a pre-defined unit test institution, affectionately
called <cite>MEGA_CORP</cite> (this constant, along with many others, is defined in <cite>TestUtils.kt</cite>). Due to Kotin’s extensive
type inference, many types are not written out explicitly in this code and it has the feel of a scripting language.
But the types are there, and you can ask IntelliJ to reveal them by pressing Alt-Enter on a “val” or “var” and selecting
“Specify type explicitly”.</p>
<p>There are a few things that are unusual here:</p>
<ulclass="simple">
<li>We can specify quantities of money by writing 1000.DOLLARS or 1000.POUNDS</li>
<li>We can specify quantities of time by writing 7.days</li>
<li>We can add quantities of time to the TEST_TX_TIME constant, which merely defines an arbitrary java.time.Instant</li>
</ul>
<p>If you examine the code in the actual repository, you will also notice that it makes use of method names with spaces
in them by surrounding the name with backticks, rather than using underscores. We don’t show this here as it breaks the
<p>The <cite>1000.DOLLARS</cite> construct is quite simple: Kotlin allows you to define extension functions on primitive types like
Int or Double. So by writing 7.days, for instance, the compiler will emit a call to a static method that takes an int
and returns a <cite>java.time.Duration</cite>.</p>
<p>As this is JUnit, we must remember to annotate each test method with @Test. Let’s examine the contents of the first test.
We are trying to check that it’s not possible for just anyone to issue commercial paper in MegaCorp’s name. That would
be bad!</p>
<p>The <cite>transactionGroup</cite> function works the same way as the <cite>requireThat</cite> construct above. It is an example of what
Kotlin calls a type safe builder, which you can read about in <aclass="reference external"href="https://kotlinlang.org/docs/reference/type-safe-builders.html">the documentation for builders</a>.
The code block that follows it is run in the scope of a freshly created <cite>TransactionGroupForTest</cite> object, which assists
you with building little transaction graphs and verifying them as a whole. Here, our “group” only actually has a
single transaction in it, with a single output, no inputs, and an Issue command signed by <cite>DUMMY_PUBKEY_1</cite> which is just
an arbitrary public key. As the paper claims to be issued by <cite>MEGA_CORP</cite>, this doesn’t match and should cause a
failure. The <cite>expectFailureOfTx</cite> method takes a 1-based index (in this case we expect the first transaction to fail)
and a string that should appear in the exception message. Then it runs the <cite>TransactionGroup.verify()</cite> method to
invoke all the involved contracts.</p>
<p>It’s worth bearing in mind that even though this code may look like a totally different language to normal Kotlin or
Java, it’s actually not, and so you can embed arbitrary code anywhere inside any of these blocks.</p>
<p>Let’s set up a full trade and ensure it works:</p>
<divclass="codeset container">
<divclass="highlight-kotlin"><divclass="highlight"><pre><spanclass="c1">// Generate a trade lifecycle with various parameters.</span>
<p>In this example we see some new features of the DSL:</p>
<ulclass="simple">
<li>The <cite>roots</cite> construct. Sometimes you don’t want to write transactions that laboriously issue everything you need
in a formally correct way. Inside <cite>roots</cite> you can create a bunch of states without any contract checking what you’re
doing. As states may not exist outside of transactions, each line inside defines a fake/invalid transaction with the
given output states, which may be <em>labelled</em> with a short string. Those labels can be used later to join transactions
together.</li>
<li>The <cite>.CASH</cite> suffix. This is a part of the unit test DSL specific to the cash contract. It takes a monetary amount
like 1000.DOLLARS and then wraps it in a cash ledger state, with some fake data.</li>
<li>The owned_by <aclass="reference external"href="https://kotlinlang.org/docs/reference/functions.html#infix-notation">infix function</a>. This is just
a normal function that we’re allowed to write in a slightly different way, which returns a copy of the cash state
with the owner field altered to be the given public key. <cite>ALICE</cite> is a constant defined by the test utilities that
is, like <cite>DUMMY_PUBKEY_1</cite>, just an arbitrary keypair.</li>
<li>We are now defining several transactions that chain together. We can optionally label any output we create. Obviously
then, the <cite>input</cite> method requires us to give the label of some other output that it connects to.</li>
<li>The <cite>transaction</cite> function can also be given a time, to override the default timestamp on a transaction.</li>
</ul>
<p>The <cite>trade</cite> function is not itself a unit test. Instead it builds up a trade/transaction group, with some slight
differences depending on the parameters provided (Kotlin allows parameters to have default valus). Then it returns
<spanclass="n">trade</span><spanclass="p">(</span><spanclass="n">redemptionTime</span><spanclass="p">=</span><spanclass="n">TEST_TX_TIME</span><spanclass="p">+</span><spanclass="m">2.</span><spanclass="n">days</span><spanclass="p">).</span><spanclass="n">expectFailureOfTx</span><spanclass="p">(</span><spanclass="m">3</span><spanclass="p">,</span><spanclass="s">"must have matured"</span><spanclass="p">)</span>
<spanclass="p">}</span>
</pre></div>
</div>
</div>
<p>That’s pretty simple: we just call <cite>verify</cite> in order to check all the transactions in the group. If any are invalid,
an exception will be thrown indicating which transaction failed and why. In the second case, we call <cite>expectFailureOfTx</cite>
again to ensure the third transaction fails with a message that contains “must have matured” (it doesn’t have to be
<h2>Adding a crafting API to your contract<aclass="headerlink"href="#adding-a-crafting-api-to-your-contract"title="Permalink to this headline">¶</a></h2>
<p>TODO: Write this after the CP contract has had a crafting API actually added.</p>
<h2>Non-asset-oriented based smart contracts<aclass="headerlink"href="#non-asset-oriented-based-smart-contracts"title="Permalink to this headline">¶</a></h2>
<p>It is important to distinguish between the idea of a legal contract vs a code contract. In this document we use the
term <em>contract</em> as a shorthand for code contract: a small module of widely shared, simultaneously executed business
logic that uses standardised APIs and runs in a sandbox.</p>
<p>Although this tutorial covers how to implement an owned asset, there is no requirement that states and code contracts
<em>must</em> be concerned with ownership of an asset. It is better to think of states as representing useful facts about the
world, and (code) contracts as imposing logical relations on how facts combine to produce new facts.</p>
<p>For example, in the case that the transfer of an asset cannot be performed entirely on-ledger, one possible usage of
the model is to implement a delivery-vs-payment lifecycle in which there is a state representing an intention to trade,
another state representing an in-progress delivery, and a final state in which the delivery is marked as complete and
payment is being awaited.</p>
<p>As another example, consider multi-signature transactions, a feature which is commonly used in Bitcoin to implement
various kinds of useful protocols. This technique allows you to lock an asset to ownership of a group, in which a
threshold of signers (e.g. 3 out of 4) must all sign simultaneously to enable the asset to move. It is initially
tempting to simply add this as another feature to each existing contract which someone might want to treat in this way.
But that could lead to unnecessary duplication of work.</p>
<p>A better approach is to model the fact of joint ownership as a new contract with its own state. In this approach, to
lock up your commercial paper under multi-signature ownership you would make a transaction that looks like this:</p>
<ulclass="simple">
<li><strong>Input</strong>: the CP state</li>
<li><strong>Output</strong>: a multi-sig state that contains the list of keys and the signing threshold desired (e.g. 3 of 4). The state has a hash of H.</li>
<li><strong>Output</strong>: the same CP state, with a marker that says a state with hash H must exist in any transaction that spends it.</li>
</ul>
<p>The CP contract then needs to be extended only to verify that a state with the required hash is present as an input.
The logic that implements measurement of the threshold, different signing combinations that may be allowed etc can then
be implemented once in a separate contract, with the controlling data being held in the named state.</p>
<p>Future versions of the prototype will explore these concepts in more depth.</p>
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.