DAML - An open-source ecosystem for building smart contract based distributed applications

Ameer Rosic

{

DAML is an open-source ecosystem for building full-stack smart contract based distributed applications. Its core smart contract language is a purpose-built functional language specialized in describing composable distributed business workflows. DAML’s unique selling point is simple – focus entirely on the application logic without worrying about the nitty-gritty of the underlying infrastructure, be that distributed ledger, blockchain, or database. Before dabbling in DAML, let’s gain a quick understanding of its underlying technology and smart contracts.

Ledgers, Blockchain and Smart Contracts

A ledger is a time-stamped series of immutable data records. Blockchain is the most well known kind of distributed ledger, one that is managed by a consortium of computers and not owned by any single entity. In a blockchain, ledger entries are packaged into a sequence of blocks, and each block of entries is secured and tied to the previous one via cryptographic principles. Three properties make the blockchain really special:

  • Distributed: The blockchain is hosted by a peer-to-peer network. Every node of this network downloads and maintains a copy of the blockchain within their system. This ensures that all the data that is stored inside the blockchain is shared by everyone and not hoarded by one single, central entity within the system.
  • Transparency: Since every node in the network is storing a version of the blockchain, they can all see the data that’s stored inside them. As such, all the data inside the blockchain is transparent.
  • Immutability: Another exciting thing to remember here is that once something has been entered within the block, it can’t be tampered with. This property of the blockchain is called “immutability.”

As you may already know, blockchain technology came into prominence with the advent of Bitcoin. This was an invention so revolutionary that people began to wonder if there is a set of adjacent, broader technologies beyond trustless value transfer. Ethereum eventually stormed into the crypto market and introduced the world to “smart contracts” flexible enough to write entire distributed applications, or dApps backed by a blockchain. 

Smart Contracts – Bringing the blockchain to the masses

Think of what a contract is and how it works in the traditional sense. A contract is a legally binding document between two parties which is also legally enforceable. A smart contract works similarly, except for two game-changing modifications – the rules defined by the contract are machine readable and executable and they are enforced using a distributed computer system without either party to the contract having enough control to override it alone.

To give you a proper definition – A smart contract is a digital agreement intended to facilitate, verify, or enforce the negotiation or performance of a contract. It allows multiple parties to do so by directly interacting with each other, without going through a third-party.

The term “smart contract” was coined by cryptographer Nick Szabo back in the ’90s in his article “Smart Contracts: Building Blocks for Digital Markets.” To understand the philosophy behind how they work, let’s take Szabo’s vending machine example.

Here is how you usually interact with a vending machine:

  • You choose the item that you want.
  • You put in some cash inside the machine.
  • The machine gives you the item.

Pretty straightforward, right? However, there are two things that you need to note during this entire interaction:

  • Each step can’t be executed until the preceding step has been fulfilled. E.g. you can’t put in the money until you select what you want. Also, the machine can’t give you an item until you put in the money.
  • During this entire interaction, you and the machine are directly interacting with each other. There is no third-party, like a shopkeeper, between the two of you.

These are the core principles behind smart contracts:

  • The two parties bound in a smart contract can directly interact with each other.
  • Each step in a smart contract can only be fulfilled after the execution of the preceding step.

By incorporating this simple innovation, Ethereum was able to create a protocol where users could directly interact with dApps (distributed applications) without going through a third-party. Ethereum uses a language called “Solidity,” to code smart contracts. However, Ethereum, like most other popular smart contract platforms like EOS and TRON, is a public blockchain. A public blockchain has an open network and anyone can join it without reservations. 

If enterprises were to use blockchains, public blockchains wouldn’t always fit their use cases, especially if they desire or require their interactions to be fully private. Enterprises need a special kind of blockchains called “permissioned blockchains.” More about them below. 

What is required of enterprise blockchains?

As opposed to public blockchains, a permissioned/private blockchain is not open for everyone. To take part in the network, you will need to obtain permission to do so from the network. There are some features that these enterprise blockchains will need to fulfill:

  • High Performance: Firstly, enterprises will need a blockchain that can process a high amount of transactions. Most public blockchains can’t even do 100 transactions per second consistently.
  • High level of resilience: Enterprise blockchains must be able to come back from downtime and potential failure scenarios. To ensure high availability, they must be able to avoid issues that may lead to major outages. To have that level of resilience, the system should assume that failures are bound to happen and must be prepared to keep the system running during these situations.
  • Privacy features: A public blockchain, by definition, isn’t private. Institutions need to deal with a lot of confidential data and regulations, as well as keep certain data classified for competitive advantage and intellectual property reasons (which is why they need a closed/permissioned environment in the first place).

Along with an enterprise-friendly environment, they will also require specialized smart contracts. Ethereum’s public smart contract runs on solidity but there are specific features that an enterprise smart contract language should have. We will discuss these properties next.

The properties of enterprise smart contract languages

The main problem with regular smart contract languages is that they are either designed or inspired by languages that were built to execute more traditional systems. They tend to be low level and tightly coupled to the infrastructures they run on. This makes them difficult and slow to program. Developers have consistently created contracts with exploitable bugs, which have caused significant damage to the crypto ecosystem. In 2016, the Ethereum community experienced first-hand what these sub-optimally coded smart contracts could do. The DAO was supposed to be the most important smart contract ever coded on Ethereum. However, a simple bug allowed a hacker to exploit the contract and siphon away over $150 million worth of Ether. This hack was so devastating that the Ethereum protocol eventually got split into Ethereum and Ethereum Classic.

What all this basically tells us is that when coding with a language like Solidity, a coder will need to consider the following:

  • Be careful of attacks like reentrancy, over- and underflows, short address attacks, etc.
  • Every single partial state that the contract will go through should be considered. 
  • The same operation may mean different things in different languages. For example. while solidity borrows heavily from JavaScript, the same operations may act differently in each language.

Long story short, you can’t just randomly pick a language and write your contracts. You’ll need to understand all the potential ramifications of your choice. Digital Asset spent years studying smart contract execution to narrow down the main properties that are required by enterprise smart contract languages:

  • Entering into a  contract needs to be voluntary. When all the parties enter a contract voluntarily, they become obligated to perform all the actions required to the best of their abilities.
  • Only the parties that are affected by a contract should be able to view the consequences affecting them (and only those).
  • The parties should be able to reasonably predict how the contract will pan out in the future. They should be able to predict all the states that the contract can possibly take. 
  • Smart contract developers should be able to use a language that allows them to focus entirely on their business logic, instead of low-level details such as hashing, cryptography and consensus protocols.

What is DAML?

DAML is a smart contract language that has been built specifically for distributed ledgers and enables the safe, unambiguous and high-level specification of real-time business logic. Here are some essential things about DAML that you need to keep in mind:

  • DAML is easy to write and read so a person who understands the business being defined can verify that the code is aligned with their intent.
  • DAML is fast to build and deploy, you can go from zero to an end to end production application extremely quickly.
  • It is a language of contracts, where agreements and parties are native constructs in the language.
  • Developers will be accurately able to describe how contracts are formed and which parties are, directly and indirectly, involved in it.
  • Developers don’t need to worry about low-level constructs and can completely focus on creating business logic.
  • DAML provides high levels of privacy and abstraction. The DAML system will automatically track the parties which are allowed to see the details of each contract. This information will also be passed to the underlying ledger to ensure that only the data a particular party is authorized to see is actually sent to it.
  • Once a DAML program is executed, it creates a well-structured and human-understandable audit trail that will help explain two things: why each action was performed and the role of each party in that smart contract.
  • In DAML, the upgrades are defined in code and can be executed in a non-disruptive manner with zero downtime. You can easily add new roles and workflows to existing solutions without going through any complications.

DAML – A functional language

In contrast with imperative languages, DAML is a functional language. In the coming paragraphs we have a look at what this means.

Imperative Programming Languages

Traditional programming languages like C++, Java and Solidity are imperative programming languages. In an imperative programming language developer needs to write all the instructions that the computer needs to take to reach a goal. Let’s take an example in C++ of what we mean by that. 

Suppose we want to print the numbers from 1 to 100 

int i = 0;

next:

i++;

printf(“%i”, i);

if(i < 100) goto next;

int a = 5;

int b = 3;

int c;

c= a + b;

As you can see, the addition process takes over multiple instructions and each instruction is constantly changing the state of the program as they are all being executed individually.

An addition process took four instructions and these are:

  • Declaring an integer “a” and assigning the value 5 to it.
  • Declaring an integer “b” and assigning the value 3 to it.
  • Declaring an integer “c.”
  • Adding the values of and b and storing them in c.

Functional Programming Languages

In this programming style functions, rather than instructions, take center-stage. Rather than writing instructions on how to calculate a result or execute an algorithm, the desired behaviour is described as in a regular mathematical function, by mapping function’s inputs to outputs,  

Functional programming is especially suited for smart contracts because the way functions are composed is similar to the way contracts interact. A contract saying “If Alice gives Bob $100, Bob gives Alice a Ticket”, is like a function that maps $100 to a Ticket. If there is a second contract saying “If Alice presents a Ticket to Bob, Bob lets Alice through the door”, this is a second function mapping a Ticket to being granted access. Just like functions, these contracts naturally compose: “If Alice gives Bob $100, Bob lets Alice in the door”.

This pure input-output behavior that is independent of a state makes the functional approach easier to reason mathematically: by having functions that solely rely on their inputs to compute their outputs, the developer can focus on the correctness of individual function and the type system enables these to be safely and predictably composed together. This is why functional programs are considered to be a more secure approach to smart contract creation. DAML is a functional language and allows developers to encapsulate business reasoning in strongly-typed mathematical functions. “Strongly-typed” in this context means that the way each and every function works can be automatically checked by DAML’s tooling and runtime. This helps developers reason exactly how each component of the program will affect the state of the ledger.

The DAML code

To try out DAML you can 1) install Visual Studio Code and the DAML SDK or use the 2) webIDE (more for learning purpose)

template Token

  with

    owner : Party

  where

    signatory owner

What you see above is a straightforward DAML template. A template defines a type of a contract that can be created and who has the right to do so. Contracts are instances of templates. In the example above, the name of the template is “Token”. The data contained within the Contracts are called “arguments”. So, let’s look at the arguments declared within this contract.

  • The “with” block defines the data type of the arguments within the template by listing the field names and their types. The template above has a single field named “owner” of type “Party”.
  • The “where” block declares the scope of the field. In our template, the “where” block declares the field “owner” as a signatory of the contract. Once declared a signatory, a field will gain the authority to create or archive the contract. 

A typical contract code in DAML has four components to it:

  • Data Model: Use DAML to easily model complex data schemas for your application (what type of data is needed for the contract)
  • Fine-grained Permissions: Specify the permissions within the contract (who can create and archive the contract, who can see certain execution steps etc.)
  • Business Logic: Describing the actions within the contract (what does the contract actually do and what are the steps in executing it)
  • Scenario-based Testing: Test the business logic you specified and the various workflows.

Now that we know the four components and template creation let’s look at a full-fledged DAML code. 

template Cash

  with

    issuer : Party

    owner : Party

    amount : Decimal

  where

    signatory issuer

    controller owner can

      Transfer : ContractId Cash

        with

          newOwner: Party

        do create this with owner = newOwner

 

template TicketAgreement

  with

    organizer : Party

    owner : Party

  where

    signatory organizer, owner

 

template TicketOffer

  with

    organizer : Party

    buyer : Party

    price : Decimal

  where

    signatory organizer

    observer buyer

    controller buyer can

      Accept : ContractId TicketAgreement

        with

          cashId : ContractId Cash

        do

          cash <- fetch cashId

          assert (cash.amount == price)

          exercise cashId Transfer with

            newOwner = organizer

          create TicketAgreement with

            organizer; owner = buyer

 

validateTicketPurchase = scenario do

  issuer <- getParty “Issuer”

  organizer <- getParty “Organizer”

  buyer <- getParty “Buyer”

  cash <- submit issuer do

    create Cash with

      issuer; owner = buyer; amount = 20.0

  offer <- submit organizer do

    create TicketOffer with

      organizer; buyer; price = 20.0

  submit buyer do

    exercise offer Accept with

      cashId = cash

 

Alright, so we have a series of templates here that are working together to create a contract where a user buys a ticket from an organizer. So, going by the color code, we have four specific blocks in the code above:

 

Data Model – Red 

 

As mentioned previously, templates have data fields that are necessary for its declaration and execution. Let’s look at the TicketOffer template:

 

template TicketOffer

  with

    organizer : Party

    buyer : Party

    price : Decimal

This template declares  three fields:

  • “organizer” and “buyer” of type “Party. As the name suggests, these two are parties of this contract.
  • Then we have the “price” which is of type decimal.

Fine-grained Permissions – Green

  where

    signatory organizer

    observer buyer

    controller buyer can

      Accept : ContractId TicketAgreement

After declaring the fields within the template, this section declares the permissions given to party arguments. So, in this template, the organizer is the only signatory and has the power to initiate or archive the contract.

The buyer is both the observer and controller. An observer is someone who can see all the states that the contract is going through. Also, as declared in the template, the buyer can accept the ticket contract, which will result in archiving it and creating a new “TicketAgreement” contract instead.

Business Logic – Pink

    do

          cash <- fetch cashId

          assert (cash.amount == price)

          exercise cashId Transfer with

            newOwner = organizer

          create TicketAgreement with

            organizer; owner = buyer

So, we declared the fields and assigned them their visibility within the contract. Now, it’s time to declare the business logic and workflow of this template. The contract will first check if the cash taken from the buyer is equal to the price of the ticket or not. If it is, then the ownership of the ticket is passed on to the buyer, while the money is passed on to the organizer.

Scenario-based Testing – Blue

validateTicketPurchase = scenario do

  issuer <- getParty “Issuer”

  organizer <- getParty “Organizer”

  buyer <- getParty “Buyer”

  cash <- submit issuer do

    create Cash with

      issuer; owner = buyer; amount = 20.0

  offer <- submit organizer do

    create TicketOffer with

      organizer; buyer; price = 20.0

  submit buyer do

    exercise offer Accept with

      cashId = cash

Finally, you can test the business logic and workflows in this section to check in real-time whether your code is working or not. This real-time is going to be especially helpful for developers. You can interact with the ledger using multiple parties and verify the effects of your transactions instantly. Scenario results from the above example will look like this

DAML - An open-source ecosystem for building smart contract based distributed applications

If you’re interested in learning DAML check out their documentation.

Real World Use Case – Replacing ASX’s CHESS

DAML has already found a real-world use case. The Australian Securities Exchange, (ASX), is one of the world’s leading financial market exchanges. It is one of the top 10 global securities exchanges by value and the largest interest rate derivatives market in Asia. Since it’s the first major financial market that opens every single day, it consistently ranks among the top five exchanges in the world.

Today, CHESS is the core system that performs the processes of clearing, settlement, asset registration, and some other post trade services which are critical to the orderly functioning of the Australian market. CHESS continues to be stable and to effectively deliver these services as demonstrated by CHESS’s average monthly service availability over the last five years of 99.99%. While there is nothing to indicate that CHESS will not continue to provide services at this service level, ASX has decided to replace CHESS with distributed ledger technology (DLT) which will provide a broader range of benefits to a wider cross section of the market. ASX explains on its website the many reasons why it chose DAML:

  • Issuers and end investors will gain a greater transparency over their market activities through timely, secure and simplified access to the register of holders (for issuers), financial assets (end investors) and associated information.
  • New levels of functionality and flexible technology will help ASX to respond to the changing markets more efficiently.
  • Easy integration with upstream and downstream business systems, streamlining functions and workflows.
  • Remove the need for expensive reconciliation processes and instead leverage a single source of truth.
  • Completely assure the availability of the solution.
  • Ensure 100% availability to those who are authorized to use it with no discrimination.
  • Provide a system that is traceable and secure.

Conclusion

Shaul Kfir, co-founder and CTO of Digital Asset, pointed out that the emergence of blockchain and distributed ledger technology today has a lot of parallels to the emergence of the Web in the 1990s. The internet was such a radically new platform that it couldn’t deliver its full potential using traditional systems. It was only when new architectural programming styles, like REST, were developed to match the properties of the Web that it truly took off. This is exactly what DAML can do to enterprise blockchain platforms.

As of right now, the blockchain space has several smart contract languages. This leads to different kinds of smart contracts that inhibit interoperability, and by extension, scalability. DAML has the properties required for institutions to adopt it as their main language while building their platform of choice. Digital Asset has announced that DAML will be integrated with multiple distributed ledgers and traditional database platforms including VMWare Blockchain, Hyperledger Sawtooth and Fabric, Corda and Amazon’s QLDB and Aurora databases. 

Start writing your smart-contracts with DAML and download the DAML SDK here

Like what you read? Give us one like or share it to your friends and get +16

176
Hungry for knowledge?
New guides and courses each week
Looking to invest?
Market data, analysis, and reports
Just curious?
A community of blockchain experts to help

Get started today and earn 128 bonus blocks

Already have an account? Sign In