Documentation Index
Fetch the complete documentation index at: https://docs.canton.network/llms.txt
Use this file to discover all available pages before exploring further.
Compose choices
It’s time to put everything you’ve learned so far together into a complete and secure Daml model for asset issuance, management, transfer, and trading. This application will have capabilities similar to the one in/app-dev/bindings-java/quickstart. In the process you will learn about a few more concepts:
- Daml projects, packages, and modules
- Composition of transactions
- Observers and stakeholders
- Daml’s execution model
- Privacy
Daml projects
Daml is organized in projects, packages, and modules. A Daml project is specified using a singledaml.yaml file, and compiles into a package in Daml’s intermediate language, or bytecode equivalent, Daml-LF. Each Daml file within a project becomes a Daml module, which is a bit like a namespace. Each Daml project has a source root specified in the source parameter in the project’s daml.yaml file. The package will include all modules specified in *.daml files beneath that source directory.
You can start a new project with a skeleton structure using dpm new project-name in the terminal. A minimal project would contain just a daml.yaml file and an empty directory of source files.
Take a look at the daml.yaml for the this chapter’s project:
name and version freely to describe your project. dependencies does what the name suggests: it includes dependencies. You should always include daml-prim and daml-stdlib. The former contains internals of the compiler and the Daml Runtime, the latter gives access to the Daml standard library. daml-script contains the types and functions for Daml Script.
You compile a Daml project by running dpm build from the project root directory. This creates a DAR file in .daml/dist/dist/${project_name}-${project_version}.dar. A DAR file is Daml’s equivalent of a JAR file in Java: it’s the artifact that gets deployed to a ledger to load the package and its dependencies. dar files are fully self-contained in that they contain all dependencies of the main package. More on all of this in Building and Packaging.
Project structure
This project contains an asset holding model for transferable, fungible assets and a separate trade workflow. The templates are structured in three modules:Intro.Asset, Intro.Asset.Role, and Intro.Asset.Trade.
In addition, there are tests in modules Test.Intro.Asset, Test.Intro.Asset.Role, and Test.Intro.Asset.Trade.
All but the last .-separated segment in module names correspond to paths relative to the project source directory, and the last one to a file name. The folder structure therefore looks like this:
daml/Intro/Asset/Role.daml:
import keyword. The LibraryModules module imports all six modules:
Project overview
The project both changes and adds to theIou model presented in Authorization:
-
Assets are fungible in the sense that they have
MergeandSplitchoices that allow theownerto manage their holdings. -
Transfer proposals now need the authorities of both
issuerandnewOwnerto accept. This makesAssetsafer thanIoufrom the issuer’s point of view. With theIoumodel, anissuercould end up owing cash to anyone as transfers were authorized by justownerandnewOwner. In this project, only parties having anAssetHoldercontract can end up owning assets. This allows theissuerto determine which parties may own their assets. -
The
Tradetemplate adds a swap of two assets to the model.
Composed choices and scripts
This project showcases how you can put theUpdate and Script actions you learned about in Authorization to good use. For example, the Merge and Split choices each perform several actions in their consequences.
- Two create actions in case of
Split - One create and one archive action in case of
Merge
return function used in Split is available in any Action context. The result of return x is a no-op containing the value x. It has an alias pure, indicating that it’s a pure value, as opposed to a value with side-effects. The return name makes sense when it’s used as the last statement in a do block as its argument is indeed the “return”-value of the do block in that case.
Taking transaction composition a step further, the Trade_Settle choice on Trade composes two exercise actions:
test_trade script in Test.Intro.Asset.Trade:
test_issuance script in Test.Intro.Asset.Role uses the output of the setupRoles script in the same module.
The same line shows a new kind of pattern matching. Rather than writing setupResult <- setupRoles and then accessing the components of setupResult using _1, _2, etc., you can give them names. It’s equivalent to writing:
(alice, bob, bank, aha, ahb) <- setupRoles would also be legal, but setupResult is used in the return value of test_issuance so it makes sense to give it a name, too. The notation with @ allows you to give both the whole value as well as its constituents names in one go.
Daml’s execution model
Daml’s execution model is fairly easy to understand, but has some important consequences. You can imagine the life of a transaction as follows: Command submission A user submits a list of commands via the Ledger API of a participant node, acting as aParty hosted on that node. That party is called the requester.
Interpretation
Each command corresponds to one or more actions. During this step, the Update corresponding to each action is evaluated in the context of the ledger to calculate all consequences, including transitive ones (consequences of consequences, etc.). The result of this is a complete transaction. Together with its requestor, this is also known as a commit.
Blinding
On ledgers with strong privacy, projections (see Privacy Model) for all involved parties are created. This is also called projecting.
Transaction submission
The transaction/commit is submitted to the network.
Validation
The transaction/commit is validated by the network. Who exactly validates can differ from implementation to implementation. Validation also involves scheduling and collision detection, ensuring that the transaction has a well-defined place in the (partial) ordering of commits, and no double spends occur.
Commitment
The commit is actually committed according to the commit or consensus protocol of the ledger.
Confirmation
The network sends confirmations of the commitment back to all involved participant nodes.
Completion
The user gets back a confirmation through the Ledger API of the submitting participant node.
The first important consequence of the above is that all transactions are committed atomically. Either a transaction is committed as a whole and for all participants, or it fails.
That’s important in the context of the Trade_Settle choice shown above. The choice transfers a baseAsset one way and a quoteAsset the other way. Thanks to transaction atomicity, there is no chance that either party is left out of pocket.
The second consequence is that the requester of a transaction knows all consequences of their submitted transaction — there are no surprises in Daml. However, it also means that the requester must have all the information to interpret the transaction. We also refer to this as Principle 2 a bit later on this page.
That’s also important in the context of Trade. In order to allow Bob to interpret a transaction that transfers Alice’s cash to Bob, Bob needs to know both about Alice’s Asset contract, as well as about some way for Alice to accept a transfer — remember, accepting a transfer needs the authority of issuer in this example.
Observers
Observers are Daml’s mechanism to disclose contracts to other parties. They are declared just like signatories, but using theobserver keyword, as shown in the Asset template:
Asset template also gives the owner a choice to set the observers, and you can see how Alice uses it to show her Asset to Bob just before proposing the trade. You can try out what happens if she didn’t do that by removing that transaction:
AssetHolder contract, and using that to authorize the transfer in Trade_Settle, Alice creates a one-time authorization in the form of a TransferAuthorization. If Alice had lots of counterparties, she would otherwise end up leaking them to each other.
Choice controllers are not automatically made observers, as they can only be calculated at the point in time when the choice arguments are known.
Privacy
Daml’s privacy model is based on two principles: Principle 1. Parties see those actions that they have a stake in. Principle 2. Every party that sees an action sees its (transitive) consequences. Principle 2 is necessary to ensure that every party can independently verify the validity of every transaction they see. A party has a stake in an action if- they are a required authorizer of it
- they are a signatory of the contract on which the action is performed
- they are an observer on the contract, and the action creates or archives it
exercise tradeCid Trade_Settle action from test_trade?
Alice is the signatory of tradeCid and Bob a required authorizer of the Trade_Settled action, so both of them see it. According to principle 2 above, that means they get to see everything in the transaction.
The consequences contain, next to some fetch actions, two exercise actions of the choice TransferApproval_Transfer.
Each of the two involved TransferApproval contracts is signed by a different issuer, which see the action on “their” contract. So the EUR_Bank sees the TransferApproval_Transfer action for the EUR Asset and the USD_Bank sees the TransferApproval_Transfer action for the USD Asset.
Some Daml ledgers, like the script runner and the Sandbox, work on the principle of “data minimization”, meaning nothing more than the above information is distributed. That is, the “projection” of the overall transaction that gets distributed to EUR_Bank in step 4 of execution_model would consist only of the TransferApproval_Transfer and its consequences.
Other implementations, in particular those on public blockchains, may have weaker privacy constraints.
Divulgence
Note that principle 2 of the privacy model means that sometimes parties see contracts that they are not signatories or observers on. If you look at the final ledger state of thetest_trade script, for example, you may notice that both Alice and Bob now see both assets, as indicated by the Xs in their respective columns:
| Alice | Bob | EUR_Bank | USD_Bank | id | status | issuer | owner | symbol | quantity |
|---|---|---|---|---|---|---|---|---|---|
| X | X | - | X | #15:6 | active | USD_Bank | Bob | USD | 100.0 |
| X | X | X | - | #15:10 | active | EUR_Bank | Alice | EUR | 90.0 |
create action of these contracts are in the transitive consequences of the Trade_Settle action both of them have a stake in. This kind of disclosure is often called “divulgence” and needs to be considered when designing Daml models for privacy sensitive applications.
Common Daml design patterns
Beyond the composition patterns above, this section covers common multi-party workflow patterns used in Daml. All examples below use aCoin asset model to illustrate each pattern.
Propose-Accept
The most common way to get multiple parties to agree on a shared contract. One party creates a proposal contract that the other party can accept, reject, or let expire. TheIouProposal in the authorization module is another example of this pattern.
The issuer creates a CoinMaster contract, then uses it to invite an owner. The invitation is a proposal contract with the issuer as signatory and the owner as observer:
Reject and Counter choices:
Delegation
Gives one party the right to exercise a choice on behalf of another. The principal creates a delegation contract that authorizes an agent to act for them, without the principal committing each action. This models real-world custodian relationships where a bank holds securities and settles transactions on a client’s behalf. The delegation contract (CoinPoA — Power of Attorney) has the principal as signatory. The attorney controls a TransferCoin choice that exercises Transfer on the principal’s coin:
Disclose choice on Coin:
Authorization
Verifies that a controlling party has the right permissions before they take certain actions. An authorization contract serves as proof — the choice body checks for its existence and validity before proceeding. For example, an issuer wants to ensure that only accredited parties can receive coin transfers. The issuer creates an authorization token for approved owners:AcceptTransfer choice on TransferProposal requires the new owner to supply their authorization token. The asserts verify the token matches the issuer and the new owner:
Locking
Prevents choices from being exercised on a contract while it is in a locked state. Useful for scenarios like securities settlement where assets must be frozen during clearing. One approach is locking by state change — the contract carries alocker field. When owner == locker, the coin is unlocked and can be transferred. When they differ, a third-party locker controls the unlock:
LockedCoin wrapper with Unlock and Clawback choices) and locking by safekeeping (transfer custody to a trusted third party who controls the unlock).
Multiple party agreement
Collects signatures from more than two parties. APending contract wraps the final Agreement and tracks who has signed. Each party signs by exercising a Sign choice, and once all parties have signed, any of them can Finalize to create the agreement.
The final agreement contract has multiple signatories:
Pending contract collects signatures one by one. It is observable by all required signatories, so each can see when it is their turn to sign:
Pending contract listing only themselves as signed. The others sign in any order, and once complete, any signatory can finalize:
Compose choices
It’s time to put everything you’ve learned so far together into a complete and secure Daml model for asset issuance, management, transfer, and trading. This application will have capabilities similar to the one in/app-dev/bindings-java/quickstart. In the process you will learn about a few more concepts:
- Daml projects, packages, and modules
- Composition of transactions
- Observers and stakeholders
- Daml’s execution model
- Privacy
Daml projects
Daml is organized in projects, packages, and modules. A Daml project is specified using a singledaml.yaml file, and compiles into a package in Daml’s intermediate language, or bytecode equivalent, Daml-LF. Each Daml file within a project becomes a Daml module, which is a bit like a namespace. Each Daml project has a source root specified in the source parameter in the project’s daml.yaml file. The package will include all modules specified in *.daml files beneath that source directory.
You can start a new project with a skeleton structure using dpm new project-name in the terminal. A minimal project would contain just a daml.yaml file and an empty directory of source files.
Take a look at the daml.yaml for the this chapter’s project:
name and version freely to describe your project. dependencies does what the name suggests: it includes dependencies. You should always include daml-prim and daml-stdlib. The former contains internals of the compiler and the Daml Runtime, the latter gives access to the Daml standard library. daml-script contains the types and functions for Daml Script.
You compile a Daml project by running dpm build from the project root directory. This creates a DAR file in .daml/dist/dist/${project_name}-${project_version}.dar. A DAR file is Daml’s equivalent of a JAR file in Java: it’s the artifact that gets deployed to a ledger to load the package and its dependencies. dar files are fully self-contained in that they contain all dependencies of the main package. More on all of this in dependencies.
Project structure
This project contains an asset holding model for transferable, fungible assets and a separate trade workflow. The templates are structured in three modules:Intro.Asset, Intro.Asset.Role, and Intro.Asset.Trade.
In addition, there are tests in modules Test.Intro.Asset, Test.Intro.Asset.Role, and Test.Intro.Asset.Trade.
All but the last .-separated segment in module names correspond to paths relative to the project source directory, and the last one to a file name. The folder structure therefore looks like this:
daml/Intro/Asset/Role.daml:
import keyword. The LibraryModules module imports all six modules:
Project overview
The project both changes and adds to theIou model presented in parties:
-
Assets are fungible in the sense that they have
MergeandSplitchoices that allow theownerto manage their holdings. -
Transfer proposals now need the authorities of both
issuerandnewOwnerto accept. This makesAssetsafer thanIoufrom the issuer’s point of view. With theIoumodel, anissuercould end up owing cash to anyone as transfers were authorized by justownerandnewOwner. In this project, only parties having anAssetHoldercontract can end up owning assets. This allows theissuerto determine which parties may own their assets. -
The
Tradetemplate adds a swap of two assets to the model.
Composed choices and scripts
This project showcases how you can put theUpdate and Script actions you learned about in parties to good use. For example, the Merge and Split choices each perform several actions in their consequences.
- Two create actions in case of
Split - One create and one archive action in case of
Merge
return function used in Split is available in any Action context. The result of return x is a no-op containing the value x. It has an alias pure, indicating that it’s a pure value, as opposed to a value with side-effects. The return name makes sense when it’s used as the last statement in a do block as its argument is indeed the “return”-value of the do block in that case.
Taking transaction composition a step further, the Trade_Settle choice on Trade composes two exercise actions:
test_trade script in Test.Intro.Asset.Trade:
test_issuance script in Test.Intro.Asset.Role uses the output of the setupRoles script in the same module.
The same line shows a new kind of pattern matching. Rather than writing setupResult <- setupRoles and then accessing the components of setupResult using _1, _2, etc., you can give them names. It’s equivalent to writing:
(alice, bob, bank, aha, ahb) <- setupRoles would also be legal, but setupResult is used in the return value of test_issuance so it makes sense to give it a name, too. The notation with @ allows you to give both the whole value as well as its constituents names in one go.
Daml’s execution model
Daml’s execution model is fairly easy to understand, but has some important consequences. You can imagine the life of a transaction as follows: Command submission A user submits a list of commands via the Ledger API of a participant node, acting as aParty hosted on that node. That party is called the requester.
Interpretation
Each command corresponds to one or more actions. During this step, the Update corresponding to each action is evaluated in the context of the ledger to calculate all consequences, including transitive ones (consequences of consequences, etc.). The result of this is a complete transaction. Together with its requestor, this is also known as a commit.
Blinding
On ledgers with strong privacy, projections (see privacy) for all involved parties are created. This is also called projecting.
Transaction submission
The transaction/commit is submitted to the network.
Validation
The transaction/commit is validated by the network. Who exactly validates can differ from implementation to implementation. Validation also involves scheduling and collision detection, ensuring that the transaction has a well-defined place in the (partial) ordering of commits, and no double spends occur.
Commitment
The commit is actually committed according to the commit or consensus protocol of the ledger.
Confirmation
The network sends confirmations of the commitment back to all involved participant nodes.
Completion
The user gets back a confirmation through the Ledger API of the submitting participant node.
The first important consequence of the above is that all transactions are committed atomically. Either a transaction is committed as a whole and for all participants, or it fails.
That’s important in the context of the Trade_Settle choice shown above. The choice transfers a baseAsset one way and a quoteAsset the other way. Thanks to transaction atomicity, there is no chance that either party is left out of pocket.
The second consequence is that the requester of a transaction knows all consequences of their submitted transaction — there are no surprises in Daml. However, it also means that the requester must have all the information to interpret the transaction. We also refer to this as Principle 2 a bit later on this page.
That’s also important in the context of Trade. In order to allow Bob to interpret a transaction that transfers Alice’s cash to Bob, Bob needs to know both about Alice’s Asset contract, as well as about some way for Alice to accept a transfer — remember, accepting a transfer needs the authority of issuer in this example.
Observers
Observers are Daml’s mechanism to disclose contracts to other parties. They are declared just like signatories, but using theobserver keyword, as shown in the Asset template:
Asset template also gives the owner a choice to set the observers, and you can see how Alice uses it to show her Asset to Bob just before proposing the trade. You can try out what happens if she didn’t do that by removing that transaction:
AssetHolder contract, and using that to authorize the transfer in Trade_Settle, Alice creates a one-time authorization in the form of a TransferAuthorization. If Alice had lots of counterparties, she would otherwise end up leaking them to each other.
Choice controllers are not automatically made observers, as they can only be calculated at the point in time when the choice arguments are known.
Privacy
Daml’s privacy model is based on two principles: Principle 1. Parties see those actions that they have a stake in. Principle 2. Every party that sees an action sees its (transitive) consequences. Principle 2 is necessary to ensure that every party can independently verify the validity of every transaction they see. A party has a stake in an action if- they are a required authorizer of it
- they are a signatory of the contract on which the action is performed
- they are an observer on the contract, and the action creates or archives it
exercise tradeCid Trade_Settle action from test_trade?
Alice is the signatory of tradeCid and Bob a required authorizer of the Trade_Settled action, so both of them see it. According to principle 2 above, that means they get to see everything in the transaction.
The consequences contain, next to some fetch actions, two exercise actions of the choice TransferApproval_Transfer.
Each of the two involved TransferApproval contracts is signed by a different issuer, which see the action on “their” contract. So the EUR_Bank sees the TransferApproval_Transfer action for the EUR Asset and the USD_Bank sees the TransferApproval_Transfer action for the USD Asset.
Some Daml ledgers, like the script runner and the Sandbox, work on the principle of “data minimization”, meaning nothing more than the above information is distributed. That is, the “projection” of the overall transaction that gets distributed to EUR_Bank in step 4 of execution_model would consist only of the TransferApproval_Transfer and its consequences.
Other implementations, in particular those on public blockchains, may have weaker privacy constraints.
Divulgence
Note that principle 2 of the privacy model means that sometimes parties see contracts that they are not signatories or observers on. If you look at the final ledger state of thetest_trade script, for example, you may notice that both Alice and Bob now see both assets, as indicated by the Xs in their respective columns:
This is because the create action of these contracts are in the transitive consequences of the Trade_Settle action both of them have a stake in. This kind of disclosure is often called “divulgence” and needs to be considered when designing Daml models for privacy sensitive applications.
Next up
Inexceptions, we will learn about how errors in your model can be handled in Daml.