<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 <codeclass="docutils literal"><spanclass="pre">CommercialPaper.kt</span></code> or <codeclass="docutils literal"><spanclass="pre">CommercialPaper.java</span></code> 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
<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>
<p>We define a class that implements the <codeclass="docutils literal"><spanclass="pre">ContractState</span></code> and <codeclass="docutils literal"><spanclass="pre">SerializableWithKryo</span></code> interfaces. The
<p>The <codeclass="docutils literal"><spanclass="pre">ContractState</span></code> interface requires us to provide a <codeclass="docutils literal"><spanclass="pre">getProgramRef</span></code> method that is supposed to return a hash of
<li><codeclass="docutils literal"><spanclass="pre">owner</span></code>: the public key of the current owner. This is the same concept as seen in Bitcoin: the public key has no
<li><codeclass="docutils literal"><spanclass="pre">faceValue</span></code>: an <codeclass="docutils literal"><spanclass="pre">Amount</span></code>, which wraps an integer number of pennies and a currency.</li>
<li><codeclass="docutils literal"><spanclass="pre">maturityDate</span></code>: an <aclass="reference external"href="https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html">Instant</a>, which is a type
<p>States are immutable, and thus the class is defined as immutable as well. The <codeclass="docutils literal"><spanclass="pre">data</span></code> modifier in the Kotlin version
familiar with that language. The <codeclass="docutils literal"><spanclass="pre">withoutOwner</span></code> method uses the auto-generated copy method to return a version of
<p>The <codeclass="docutils literal"><spanclass="pre">object</span></code> keyword in Kotlin just defines a singleton object. As the commands don’t need any additional data in our
<p>We start by using the <codeclass="docutils literal"><spanclass="pre">groupStates</span></code> method, which takes a type and a function (in functional programming a function
a command object that inherits from the <codeclass="docutils literal"><spanclass="pre">CommercialPaper.Commands</span></code> supertype, and either returns it, or throws an
<p>The <codeclass="docutils literal"><spanclass="pre">TransactionForVerification.groupStates</span></code> method handles this logic for us: firstly, it selects only states of the
<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="s">"the state is propagated"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">group</span><spanclass="p">.</span><spanclass="n">outputs</span><spanclass="p">.</span><spanclass="n">size</span><spanclass="p">==</span><spanclass="m">1</span><spanclass="p">)</span>
<spanclass="k">if</span><spanclass="p">(</span><spanclass="n">time</span><spanclass="p">==</span><spanclass="k">null</span><spanclass="p">)</span><spanclass="k">throw</span><spanclass="n">IllegalArgumentException</span><spanclass="p">(</span><spanclass="s">"Redemption transactions must be timestamped"</span><spanclass="p">)</span>
<spanclass="s">"the paper must have matured"</span><spanclass="k">by</span><spanclass="p">(</span><spanclass="n">time</span><spanclass="p">></span><spanclass="n">input</span><spanclass="p">.</span><spanclass="n">maturityDate</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="n">group</span><spanclass="p">.</span><spanclass="n">outputs</span><spanclass="p">.</span><spanclass="n">isEmpty</span><spanclass="p">()</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">if</span><spanclass="p">(</span><spanclass="n">time</span><spanclass="p">==</span><spanclass="k">null</span><spanclass="p">)</span><spanclass="k">throw</span><spanclass="n">IllegalArgumentException</span><spanclass="p">(</span><spanclass="s">"Issuance transactions must be timestamped"</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">time</span><spanclass="p"><</span><spanclass="n">output</span><spanclass="p">.</span><spanclass="n">maturityDate</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="p">}</span>
<spanclass="p">}</span>
<spanclass="c1">// TODO: Think about how to evolve contracts over time with new commands.</span>
<divclass="highlight-java"><divclass="highlight"><pre><spanclass="n">Instant</span><spanclass="n">time</span><spanclass="o">=</span><spanclass="n">tx</span><spanclass="o">.</span><spanclass="na">getTime</span><spanclass="o">();</span><spanclass="c1">// Can be null/missing.</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">IllegalArgumentException</span><spanclass="o">(</span><spanclass="s">"Redemption transactions must be timestamped"</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>
check won’t happen if we write e.g. <codeclass="docutils literal"><spanclass="pre">someDate</span><spanclass="pre">></span><spanclass="pre">time</span></code>, it has to be <codeclass="docutils literal"><spanclass="pre">time</span><spanclass="pre"><</span><spanclass="pre">someDate</span></code>. So it’s good practice to
<codeclass="docutils literal"><spanclass="pre">single()</span></code> method is a static <em>extension method</em> defined by the Kotlin standard library: given a list, it throws an
Each <codeclass="docutils literal"><spanclass="pre">"string"</span><spanclass="pre">by</span><spanclass="pre">(expression)</span></code> statement inside a <codeclass="docutils literal"><spanclass="pre">requireThat</span></code> turns into an assertion that the given expression is
<p>If the command is a <codeclass="docutils literal"><spanclass="pre">Move</span></code> command, then we simply verify that the output state is actually present: a move is not
<p>To calculate how much cash is moving, we use the <codeclass="docutils literal"><spanclass="pre">sumCashOrNull</span></code> utility method. Again, this is an extension method,
so in Kotlin code it appears as if it was a method on the <codeclass="docutils literal"><spanclass="pre">List<Cash.State></span></code> type even though JDK provides no such
method. In Java we see its true nature: it is actually a static method named <codeclass="docutils literal"><spanclass="pre">CashKt.sumCashOrNull</span></code>. This method simply
returns an <codeclass="docutils literal"><spanclass="pre">Amount</span></code> object containing the sum of all the cash states in the transaction output, or null if there were
<p>Finally, we support an <codeclass="docutils literal"><spanclass="pre">Issue</span></code> command, to create new instances of commercial paper on the ledger. It likewise
<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>
called <codeclass="docutils literal"><spanclass="pre">MEGA_CORP</span></code> (this constant, along with many others, is defined in <codeclass="docutils literal"><spanclass="pre">TestUtils.kt</span></code>). Due to Kotin’s extensive
<p>The <codeclass="docutils literal"><spanclass="pre">1000.DOLLARS</span></code> construct is quite simple: Kotlin allows you to define extension functions on primitive types like
<p>The <codeclass="docutils literal"><spanclass="pre">transactionGroup</span></code> function works the same way as the <codeclass="docutils literal"><spanclass="pre">requireThat</span></code> construct above.</p>
<divclass="admonition note">
<pclass="first admonition-title">Note</p>
<pclass="last">This DSL 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>. You can mix and match
ordinary code inside such DSLs so please read the linked page to make sure you fully understand what they are capable
of.</p>
</div>
<p>The code block that follows it is run in the scope of a freshly created <codeclass="docutils literal"><spanclass="pre">TransactionGroupForTest</span></code> object, which assists
single transaction in it, with a single output, no inputs, and an Issue command signed by <codeclass="docutils literal"><spanclass="pre">DUMMY_PUBKEY_1</span></code> which is just
an arbitrary public key. As the paper claims to be issued by <codeclass="docutils literal"><spanclass="pre">MEGA_CORP</span></code>, this doesn’t match and should cause a
failure. The <codeclass="docutils literal"><spanclass="pre">expectFailureOfTx</span></code> 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 <codeclass="docutils literal"><spanclass="pre">TransactionGroup.verify()</span></code> method to
<li>The <codeclass="docutils literal"><spanclass="pre">roots</span></code> construct. Sometimes you don’t want to write transactions that laboriously issue everything you need
in a formally correct way. Inside <codeclass="docutils literal"><spanclass="pre">roots</span></code> you can create a bunch of states without any contract checking what you’re
<li>The <codeclass="docutils literal"><spanclass="pre">.CASH</span></code> 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. <codeclass="docutils literal"><spanclass="pre">ALICE</span></code> is a constant defined by the test utilities that
is, like <codeclass="docutils literal"><spanclass="pre">DUMMY_PUBKEY_1</span></code>, just an arbitrary keypair.</li>
then, the <codeclass="docutils literal"><spanclass="pre">input</span></code> method requires us to give the label of some other output that it connects to.</li>
<li>The <codeclass="docutils literal"><spanclass="pre">transaction</span></code> function can also be given a time, to override the default timestamp on a transaction.</li>
<p>The <codeclass="docutils literal"><spanclass="pre">trade</span></code> function is not itself a unit test. Instead it builds up a trade/transaction group, with some slight
<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>
<p>That’s pretty simple: we just call <codeclass="docutils literal"><spanclass="pre">verify</span></code> 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 <codeclass="docutils literal"><spanclass="pre">expectFailureOfTx</span></code>
<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>Contract classes <strong>must</strong> provide a verify function, but they may optionally also provide helper functions to simplify
their usage. A simple class of functions most contracts provide are <em>crafting functions</em>, which either generate or
modify a transaction to perform certain actions (an action is normally mappable 1:1 to a command, but doesn’t have to
be so).</p>
<p>Crafting may involve complex logic. For example, the cash contract has a <codeclass="docutils literal"><spanclass="pre">craftSpend</span></code> method that is given a set of
cash states and chooses a way to combine them together to satisfy the amount of money that is being sent. In the
immutable-state model that we are using ledger entries (states) can only be created and deleted, but never modified.
Therefore to send $1200 when we have only $900 and $500 requires combining both states together, and then creating
two new output states of $1200 and $200 back to ourselves. This latter state is called the <em>change</em> and is a concept
that should be familiar to anyone who has worked with Bitcoin.</p>
<p>As another example, we can imagine code that implements a netting algorithm may craft complex transactions that must
be signed by many people. Whilst such code might be too big for a single utility method (it’d probably be sized more
like a module), the basic concept is the same: preparation of a transaction using complex logic.</p>
<p>For our commercial paper contract however, the things that can be done with it are quite simple. Let’s start with
bookkeeping/reference numbers that we may require. Then the face value of the paper, and the maturity date. It
returns a <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code>. A <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code> is one of the few mutable classes the platform provides.
It allows you to add inputs, outputs and commands to it and is designed to be passed around, potentially between
multiple contracts.</p>
<divclass="admonition note">
<pclass="first admonition-title">Note</p>
<pclass="last">Crafting methods should ideally be written to compose with each other, that is, they should take a
<codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code> as an argument instead of returning one, unless you are sure it doesn’t make sense to
combine this type of transaction with others. In this case, issuing CP at the same time as doing other things
<p>The function we define creates a <codeclass="docutils literal"><spanclass="pre">CommercialPaper.State</span></code> object that mostly just uses the arguments we were given,
<p>The returned partial transaction has a <codeclass="docutils literal"><spanclass="pre">WireCommand</span></code> object as a parameter. This is a container for any object
that implements the <codeclass="docutils literal"><spanclass="pre">Command</span></code> interface, along with a key that is expected to sign this transaction. In this case,
<p>The <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code> constructor we used above takes a variable argument list for convenience. You can pass in
any <codeclass="docutils literal"><spanclass="pre">ContractStateRef</span></code> (input), <codeclass="docutils literal"><spanclass="pre">ContractState</span></code> (output) or <codeclass="docutils literal"><spanclass="pre">Command</span></code> objects and it’ll build up the transaction
for you.</p>
<p>What about moving the paper, i.e. reassigning ownership to someone else?</p>
<p>Here, the method takes a pre-existing <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code> and adds to it. This is correct because typically
you will want to combine a sale of CP atomically with the movement of some other asset, such as cash. So both
craft methods should operate on the same transaction. You can see an example of this being done in the unit tests
for the commercial paper contract.</p>
<p>The paper is given to us as a <codeclass="docutils literal"><spanclass="pre">StateAndRef<CommercialPaper.State></span></code> object. This is exactly what it sounds like:
a small object that has a (copy of) a state object, and also the (txhash, index) that indicates the location of this
<p>The <em>wallet</em> is a concept that may be familiar from Bitcoin and Ethereum. It is simply a set of cash states that are
owned by the caller. Here, we use the wallet to update the partial transaction we are handed with a movement of cash
from the issuer of the commercial paper to the current owner. If we don’t have enough quantity of cash in our wallet,
an exception is thrown. And then we add the paper itself as an input, but, not an output (as we wish to delete it
from the ledger permanently). Finally, we add a Redeem command that should be signed by the owner of the commercial
paper.</p>
<p>A <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code> is not by itself ready to be used anywhere, so first, we must convert it to something that
is recognised by the network. The most important next step is for the participating entities to sign it using the
<codeclass="docutils literal"><spanclass="pre">signWith()</span></code> method. This takes a keypair, serialises the transaction, signs the serialised form and then stores the
signature inside the <codeclass="docutils literal"><spanclass="pre">PartialTransaction</span></code>. Once all parties have signed, you can call <codeclass="docutils literal"><spanclass="pre">PartialTransaction.toSignedTransaction()</span></code>
to get a <codeclass="docutils literal"><spanclass="pre">SignedWireTransaction</span></code> object. This is an immutable form of the transaction that’s ready for <em>timestamping</em>.</p>
<divclass="admonition note">
<pclass="first admonition-title">Note</p>
<pclass="last">Timestamping and passing around of partial transactions for group signing is not yet fully implemented.
This tutorial will be updated once it is.</p>
</div>
<p>You can see how transactions flow through the different stages of construction by examining the commercial paper
<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
<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>.