├── .github └── workflows │ └── cla.yml ├── .gitignore ├── LICENSE ├── PingPong ├── README.rst ├── daml.yaml ├── daml │ └── PingPong.daml ├── pom.xml ├── src │ └── main │ │ ├── java │ │ └── examples │ │ │ └── pingpong │ │ │ ├── codegen │ │ │ ├── PingPongCodegenMain.java │ │ │ └── PingPongProcessor.java │ │ │ ├── grpc │ │ │ ├── PingPongGrpcMain.java │ │ │ └── PingPongProcessor.java │ │ │ └── reactive │ │ │ ├── PingPongProcessor.java │ │ │ └── PingPongReactiveMain.java │ │ └── resources │ │ └── logback.xml └── start.sh ├── README.rst └── StockExchange ├── README.rst ├── canton_ledger.conf ├── daml.yaml ├── daml └── StockExchange.daml ├── pom.xml ├── setup.sh ├── src └── main │ ├── java │ └── examples │ │ └── stockexchange │ │ ├── Common.java │ │ ├── ParticipantSession.java │ │ └── parties │ │ ├── Bank.java │ │ ├── Buyer.java │ │ ├── Seller.java │ │ └── StockExchange.java │ └── resources │ └── logback.xml └── stock_exchange_bootstrap_script.canton /.github/workflows/cla.yml: -------------------------------------------------------------------------------- 1 | name: "CLA Assistant" 2 | on: 3 | issue_comment: 4 | types: [created] 5 | pull_request_target: 6 | types: [opened,closed,synchronize] 7 | 8 | # explicitly configure permissions, in case your GITHUB_TOKEN workflow permissions are set to read-only in repository settings 9 | permissions: 10 | actions: write 11 | contents: write # this can be 'read' if the signatures are in remote repository 12 | pull-requests: write 13 | statuses: write 14 | 15 | jobs: 16 | CLAAssistant: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: "CLA Assistant" 20 | if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have hereby read the Digital Asset CLA and agree to its terms') || github.event_name == 'pull_request_target' 21 | uses: digital-asset/cla-action@v0.0.2 22 | env: 23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | # the below token should have repo scope and must be manually added by you in the repository's secret 25 | # This token is required only if you have configured to store the signatures in a remote repository/organization 26 | PERSONAL_ACCESS_TOKEN: ${{ secrets.PAT_FG_CCI_VALIDATOR_CLA }} 27 | with: 28 | path-to-document: 'https://github.com/digital-asset/daml/blob/main/CODE_OF_CONDUCT.md' # e.g. a CLA or a DCO document 29 | # branch should not be protected 30 | branch: 'main' 31 | allowlist: bot* 32 | custom-notsigned-prcomment: '🎉 Thank you for your contribution! It appears you have not yet signed the Agreement [DA Contributor License Agreement (CLA)](https://gist.github.com/digitalasset-cla), which is required for your changes to be incorporated into an Open Source Software (OSS) project. Please kindly read the and reply on a new comment with the following text to agree:' 33 | custom-pr-sign-comment: 'I have hereby read the Digital Asset CLA and agree to its terms' 34 | custom-allsigned-prcomment: '✅ All required contributors have signed the CLA for this PR. Thank you!' 35 | # Remote repository storing CLA signatures. 36 | remote-organization-name: DACH-NY 37 | remote-repository-name: cla-action-data 38 | # Branch where CLA signatures are stored. 39 | path-to-signatures: signatures/signatures.json 40 | 41 | # the followings are the optional inputs - If the optional inputs are not given, then default values will be taken 42 | #remote-organization-name: enter the remote organization name where the signatures should be stored (Default is storing the signatures in the same repository) 43 | #remote-repository-name: enter the remote repository name where the signatures should be stored (Default is storing the signatures in the same repository) 44 | #create-file-commit-message: 'For example: Creating file for storing CLA Signatures' 45 | #signed-commit-message: 'For example: $contributorName has signed the CLA in $owner/$repo#$pullRequestNo' 46 | #custom-notsigned-prcomment: 'pull request comment with Introductory message to ask new contributors to sign' 47 | #custom-pr-sign-comment: 'The signature to be committed in order to sign the CLA' 48 | #custom-allsigned-prcomment: 'pull request comment when all contributors has signed, defaults to **CLA Assistant Lite bot** All Contributors have signed the CLA.' 49 | #lock-pullrequest-aftermerge: false - if you don't want this bot to automatically lock the pull request after merging (default - true) 50 | #use-dco-flag: true - If you are using DCO instead of CLA 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020, Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | lib/ 5 | logs/ 6 | log/ 7 | target/ 8 | **/navigator.log 9 | **/sandbox.log 10 | dependency-reduced-pom.xml 11 | .navigator.conf 12 | navigator.history 13 | *.iml 14 | .idea/ 15 | example-ping-pong-java.iml 16 | .vscode/settings.json 17 | **/.daml 18 | StockExchange/temp_stock_exchange_example 19 | StockExchange/src/main/java/examples/codegen 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Digital Asset (Switzerland) GmbH and/or its affiliates 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PingPong/README.rst: -------------------------------------------------------------------------------- 1 | Java Bindings Ping-Pong Example 2 | ------------------------------- 3 | 4 | :: 5 | 6 | Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 7 | SPDX-License-Identifier: Apache-2.0.0 8 | 9 | 10 | This is an example of how a Java application would use the `Java Binding library `_ to connect to and exercise a DAML model running on a ledger. Since there are three levels of interface available, this example builds a similar application with all three levels. 11 | 12 | The application is a simple ``PingPong`` application, which consists of: 13 | 14 | - a DAML model with two contract templates, ``Ping`` and ``Pong`` 15 | - two parties, ``Alice`` and ``Bob`` 16 | 17 | The logic of the application is the following: 18 | 19 | #. The application injects a contract of type ``Ping`` for ``Alice``. 20 | #. ``Alice`` sees this contract and exercises the consuming choice ``RespondPong`` to create a contract 21 | of type ``Pong`` for ``Bob``. 22 | #. ``Bob`` sees this contract and exercises the consuming choice ``RespondPing`` to create a contract 23 | of type ``Ping`` for ``Alice``. 24 | #. Points 1 and 2 are repeated until the maximum number of contracts defined in the DAML is 25 | reached. 26 | 27 | Setting Up the Example Projects 28 | ------------------------------- 29 | 30 | To set a project up: 31 | 32 | #. If you do not have it already, install the DAML SDK by running:: 33 | 34 | curl https://get.daml.com | sh -s 2.8.0 35 | 36 | #. Use the start script for starting a ledger & the java application: 37 | 38 | ./start.sh 39 | 40 | * examples.pingpong.grpc.PingPongGrpcMain 41 | * examples.pingpong.reactive.PingPongReactiveMain 42 | * examples.pingpong.codegen.PingPongCodegenMain 43 | 44 | depending on which example you wish to run. The script will take care of stopping an already running sandbox & start a fresh one on every call. 45 | 46 | Example Project -- Ping Pong with gRPC Bindings 47 | ----------------------------------------------- 48 | 49 | The code for this example is in the package `examples.pingpong.grpc `_. 50 | 51 | PingPongGrpcMain.java 52 | ===================== 53 | 54 | The entry point for the Java code is the main class `PingPongGrpcMain `_. Look at this class to see: 55 | 56 | - how to connect to and interact with the DAML Ledger via the Java Binding library 57 | - how to use the gRPC layer to build an automation for both parties. 58 | 59 | The main function: 60 | 61 | - creates an instance of a ``ManagedChannel`` connecting to an existing ledger 62 | - fetches the ledgerID and packageId from the ledger 63 | - creates ``Identifiers`` for the Ping and Pong templates 64 | - creates and starts instances of `PingPongProcessor `_ that contain the logic of the automation 65 | - injects the initial contracts to start the process 66 | 67 | PingPongProcessor.java 68 | ====================== 69 | 70 | The core of the application is the method `PingPongProcessor.runIndefinitely() `_. 71 | 72 | This method retrieves a gRPC streaming endpoint using the ``GetTransactionsRequest`` request, and then creates a `RxJava `_ ``StreamObserver``, providing implementations of the ``onNext``, ``onError`` and ``onComplete`` observer methods. ``RxJava`` arranges that these methods receive stream events asynchronously. 73 | 74 | The method `onNext `_ is the main driver, extracting the transaction list from each ``GetTransactionResponse``, and passing in to ``processTransaction()`` for processing. This method, and the method ``processTransaction()`` implements the application logic. 75 | 76 | `processTransaction() `_ extracts all creation events from the the transaction and passes them to ``processEvent()``. This produces a list of commands to be sent to the ledger to further the workflow, and these are packages up in a ``Commands`` request and sent to the ledger. 77 | 78 | `processEvent() `_ takes a transaction event and turns it into a stream of commands to be sent back to the ledger. To do this, it examines the event for the correct package and template (it's a create of a ``Ping`` or ``Pong`` template) and then looks at the receiving part to decide if this processor should respond. If so, an exercise command for the correct choice is created and returned in a ``Stream``. 79 | 80 | In all other cases, an empty ``Stream`` is returned, indication no action is required. 81 | 82 | Output 83 | ====== 84 | 85 | The application prints statements similar to these: 86 | 87 | .. code-block:: text 88 | 89 | Bob is exercising RespondPong on #1:0 in workflow Ping-Alice-1 at count 0 90 | Alice is exercising RespondPing on #344:1 in workflow Ping-Alice-7 at count 9 91 | 92 | The first line shows that: 93 | 94 | - ``Bob`` is exercising the ``RespondPong`` choice on the contract with ID ``#1:0`` for the workflow ``Ping-Alice-1``. 95 | - Count ``0`` means that this is the first choice after the initial ``Ping`` contract. 96 | - The workflow ID ``Ping-Alice-1`` conveys that this is the workflow triggered by the second initial ``Ping`` 97 | contract that was created by ``Alice``. 98 | 99 | The second line is analogous to the first one. 100 | 101 | Example Project -- Ping Pong with Reactive Components 102 | ----------------------------------------------------- 103 | 104 | The code for this example is in the package `examples.pingpong.reactive `_. 105 | 106 | PingPongReactiveMain.java 107 | ========================= 108 | 109 | The entry point for the Java code is the main class `PingPongReactiveMain `_. 110 | Look at this class to see: 111 | 112 | - how to connect to and interact with the DAML Ledger via the Java Binding library 113 | - how to use the Reactive layer to build an automation for both parties. 114 | 115 | At high level, the code does the following steps: 116 | 117 | - creates an instance of ``DamlLedgerClient`` connecting to an existing Ledger 118 | - connect this instance to the Ledger with ``DamlLedgerClient.connect()`` 119 | - create two instances of `PingPongProcessor `_, which contain the logic of the automation 120 | - run the ``PingPongProcessor`` forever by connecting them to the incoming transactions 121 | - inject some contracts for each party of both templates 122 | - wait until the application is done 123 | 124 | PingPongProcessor.runIndefinitely 125 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 126 | 127 | The core of the application is the method `PingPongProcessor.runIndefinitely() `_. 128 | 129 | The ``PingPongProcessor`` queries the transactions first via the ``TransactionsClient`` 130 | of the ``DamlLedgerClient``. Then, for each 131 | transaction, it produces ``Commands`` that will be sent to the Ledger via the ``CommandSubmissionClient`` 132 | of the ``DamlLedgerClient``. 133 | 134 | Output 135 | ====== 136 | 137 | The application prints statements similar to these: 138 | 139 | .. code-block:: text 140 | 141 | 14:36:24.789 [client-1] INFO e.p.reactive.PingPongProcessor - Bob is exercising RespondPong on #3136:0 in workflow Ping-Alice-1 at count 0 142 | 14:36:24.791 [client-0] INFO e.p.reactive.PingPongProcessor - Alice is exercising RespondPing on #3139:1 in workflow Ping-Alice-0 at count 1 143 | 144 | The Underlying Library: RxJava 145 | ============================== 146 | 147 | The Java Binding is `RxJava `_, a library for 148 | composing asynchronous and event-based programs using observable sequences for the Java VM. 149 | It is part of the family of libraries called `ReactiveX `_. 150 | 151 | ReactiveX was chosen as the underlying library for the Java Binding because 152 | many services that the DAML Ledger offers are exposed as streams of events. 153 | So an application that wants to interact with the DAML Ledger must react 154 | to one or more DAML Ledger streams. 155 | 156 | Example Project -- Ping Pong with Generated Java Data Layer 157 | ----------------------------------------------------------- 158 | 159 | The code for this example is in the package `examples.pingpong.codegen `_. 160 | 161 | PingPongCodegenMain.java 162 | ======================== 163 | 164 | The entry point for the Java code is the main class `PingPongCodegenMain `_. Look at this class to see: 165 | 166 | - how to connect to and interact with the DAML Ledger via the Java Binding library 167 | - how to use the gRPC layer to build an automation for both parties. 168 | - how to streamline interactions with the ledger types by using auto generated data layer. 169 | 170 | The main function: 171 | 172 | - creates an instance of a ``ManagedChannel`` connecting to an existing ledger 173 | - fetches the ledgerID and packageId from the ledger 174 | - creates ``Identifiers`` for the Ping and Pong templates 175 | - creates and starts instances of `PingPongProcessor `_ that contain the logic of the automation 176 | - injects the initial contracts to start the process 177 | 178 | PingPongProcessor.java 179 | ====================== 180 | 181 | The core of the application is the method `PingPongProcessor.runIndefinitely() `_. 182 | 183 | This method retrieves a gRPC streaming endpoint using the ``GetTransactionsRequest`` request, and then creates a `RxJava `_ ``StreamObserver``, providing implementations of the ``onNext``, ``onError`` and ``onComplete`` observer methods. ``RxJava`` arranges that these methods receive stream events asynchronously. 184 | 185 | The method `onNext `_ is the main driver, extracting the transaction list from each ``GetTransactionResponse``, and passing in to ``processTransaction()`` for processing. This method, and the method ``processTransaction()`` implements the application logic. 186 | 187 | `processTransaction() `_ extracts all creation events from the the transaction and passes them to ``processEvent()``. This produces a list of commands to be sent to the ledger to further the workflow, and these are packages up in a ``Commands`` request and sent to the ledger. 188 | 189 | `processEvent() `_ takes a transaction event and turns it into a stream of commands to be sent back to the ledger. To do this, it examines the event for the correct package and template (it's a create of a ``Ping`` or ``Pong`` template) and then looks at the receiving part to decide if this processor should respond. If so, an exercise command for the correct choice is created and returned in a ``Stream``. 190 | 191 | In all other cases, an empty ``Stream`` is returned, indication no action is required. 192 | 193 | Output 194 | ====== 195 | 196 | The application prints statements similar to these: 197 | 198 | .. code-block:: text 199 | 200 | Bob is exercising RespondPong on #1:0 in workflow Ping-Alice-1 at count 0 201 | Alice is exercising RespondPing on #344:1 in workflow Ping-Alice-7 at count 9 202 | 203 | The first line shows that: 204 | 205 | - ``Bob`` is exercising the ``RespondPong`` choice on the contract with ID ``#1:0`` for the workflow ``Ping-Alice-1``. 206 | - Count ``0`` means that this is the first choice after the initial ``Ping`` contract. 207 | - The workflow ID ``Ping-Alice-1`` conveys that this is the workflow triggered by the second initial ``Ping`` 208 | contract that was created by ``Alice``. 209 | 210 | The second line is analogous to the first one. 211 | 212 | The Generated Data Layer 213 | ======================== 214 | 215 | The ``codegen`` variant of the client application is similar to its ``grpc`` counterpart. Both are written in 216 | a traditional imperative style. What sets them apart is the usage of the generated data layer in the former. 217 | This layer simplifies construction of the ledger api calls and the analysis of the return values. 218 | 219 | - ``PingPongCodegenMain.createInitialContracts`` creates a strongly typed instance of a Ping contract and then embeds it in an equally strongly typed ``CommandsSubmission``. Then, it uses the built in ``toProto`` methods to convert the request into a wire-ready ``protobuf`` structure. 220 | - ``PingPongProcessor.runIndefinitely`` creates a per party inclusive filter by invoking a series of class constructors. Contrast this with the intricate process of defining a filter in the analogous method in the ``grpc`` variant of the application. 221 | - ``PingPongProcessor.processEvent`` starts off by extracting common data fields from the ``grpc`` version of the received events, to be later used for logging purposes. Events are then converted to the corresponding data layer format and passed to the individual template handlers. 222 | - ``PingPongProcessor.processPingPong`` creates a strongly typed representation of the daml contracts by means of the daml contract companions. A strongly typed instance can be used to create a command representing a desired choice exercise. 223 | - ``PingPongProcessor.processTransaction`` is responsible for creating a ledger request enveloping the choice exercises and submitting it to the ledger. 224 | -------------------------------------------------------------------------------- /PingPong/daml.yaml: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | sdk-version: 2.7.0 5 | name: ex-java-bindings 6 | source: daml/PingPong.daml 7 | init-script: PingPong:setup 8 | version: 0.0.2 9 | dependencies: 10 | - daml-prim 11 | - daml-stdlib 12 | - daml-script 13 | codegen: 14 | java: 15 | package-prefix: examples.pingpong.codegen 16 | output-directory: src/main/java/ -------------------------------------------------------------------------------- /PingPong/daml/PingPong.daml: -------------------------------------------------------------------------------- 1 | -- Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | -- SPDX-License-Identifier: Apache-2.0 3 | 4 | module PingPong where 5 | 6 | import Daml.Script 7 | 8 | template Ping 9 | with 10 | sender: Party 11 | receiver: Party 12 | count: Int 13 | where 14 | signatory sender 15 | observer receiver 16 | 17 | choice RespondPong : () 18 | controller receiver 19 | do 20 | if count > 10 then return () 21 | else do 22 | create Pong with sender = receiver; receiver = sender; count = count + 1 23 | return () 24 | 25 | template Pong 26 | with 27 | sender: Party 28 | receiver: Party 29 | count: Int 30 | where 31 | signatory sender 32 | observer receiver 33 | 34 | choice RespondPing : () 35 | controller receiver 36 | do 37 | if count > 10 then return () 38 | else do 39 | create Ping with sender = receiver; receiver = sender; count = count + 1 40 | return () 41 | 42 | setup : Script() 43 | setup = script do 44 | -- Set up parties 45 | alice <- allocatePartyWithHint "Alice" (PartyIdHint "Alice") 46 | bob <- allocatePartyWithHint "Bob" (PartyIdHint "Bob") 47 | 48 | -- Needed in 2.0, see https://docs.daml.com/tools/navigator/index.html 49 | aliceId <- validateUserId "alice" 50 | bobId <- validateUserId "bob" 51 | createUser (User aliceId (Some alice)) [CanActAs alice] 52 | createUser (User bobId (Some bob)) [CanActAs bob] 53 | -------------------------------------------------------------------------------- /PingPong/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.daml.ledger.examples 6 | example-ping-pong-java 7 | jar 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | UTF-8 12 | 11 13 | 11 14 | 2.7.0 15 | 16 | 17 | 18 | 19 | com.daml 20 | bindings-rxjava 21 | ${sdk-version} 22 | 23 | 24 | com.daml 25 | bindings-java 26 | ${sdk-version} 27 | 28 | 29 | ch.qos.logback 30 | logback-classic 31 | 1.4.12 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/codegen/PingPongCodegenMain.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.codegen; 5 | 6 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc; 7 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc.CommandSubmissionServiceFutureStub; 8 | import com.daml.ledger.api.v1.LedgerIdentityServiceGrpc; 9 | import com.daml.ledger.api.v1.LedgerIdentityServiceGrpc.LedgerIdentityServiceBlockingStub; 10 | import com.daml.ledger.api.v1.LedgerIdentityServiceOuterClass.GetLedgerIdentityRequest; 11 | import com.daml.ledger.api.v1.LedgerIdentityServiceOuterClass.GetLedgerIdentityResponse; 12 | import com.daml.ledger.api.v1.admin.UserManagementServiceGrpc; 13 | import com.daml.ledger.api.v1.admin.UserManagementServiceGrpc.UserManagementServiceBlockingStub; 14 | import com.daml.ledger.api.v1.admin.UserManagementServiceOuterClass.GetUserRequest; 15 | import com.daml.ledger.api.v1.admin.UserManagementServiceOuterClass.GetUserResponse; 16 | import com.daml.ledger.javaapi.data.Command; 17 | import com.daml.ledger.javaapi.data.CommandsSubmission; 18 | import com.daml.ledger.javaapi.data.SubmitRequest; 19 | import examples.pingpong.codegen.pingpong.Ping; 20 | import io.grpc.ManagedChannel; 21 | import io.grpc.ManagedChannelBuilder; 22 | 23 | import java.util.List; 24 | import java.util.UUID; 25 | 26 | public class PingPongCodegenMain { 27 | 28 | // application id used for sending commands 29 | public static final String APP_ID = "PingPongCodegenApp"; 30 | 31 | // constants for referring to the users with access to the parties 32 | public static final String ALICE_USER = "alice"; 33 | public static final String BOB_USER = "bob"; 34 | 35 | public static void main(String[] args) { 36 | // Extract host and port from arguments 37 | if (args.length < 2) { 38 | System.err.println("Usage: HOST PORT [NUM_INITIAL_CONTRACTS]"); 39 | System.exit(-1); 40 | } 41 | String host = args[0]; 42 | int port = Integer.parseInt(args[1]); 43 | 44 | // each party will create this number of initial Ping contracts 45 | int numInitialContracts = args.length == 3 ? Integer.parseInt(args[2]) : 10; 46 | 47 | // Initialize a plaintext gRPC channel 48 | ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); 49 | 50 | // fetch the ledger ID, which is used in subsequent requests sent to the ledger 51 | String ledgerId = fetchLedgerId(channel); 52 | 53 | // fetch the party IDs that got created in the Daml init script 54 | String aliceParty = fetchPartyId(channel, ALICE_USER); 55 | String bobParty = fetchPartyId(channel, BOB_USER); 56 | 57 | // initialize the ping pong processors for Alice and Bob 58 | PingPongProcessor aliceProcessor = new PingPongProcessor(aliceParty, ledgerId, channel); 59 | PingPongProcessor bobProcessor = new PingPongProcessor(bobParty, ledgerId, channel); 60 | 61 | // start the processors asynchronously 62 | aliceProcessor.runIndefinitely(); 63 | bobProcessor.runIndefinitely(); 64 | 65 | // send the initial commands for both parties 66 | createInitialContracts(channel, ledgerId, aliceParty, bobParty, numInitialContracts); 67 | createInitialContracts(channel, ledgerId, bobParty, aliceParty, numInitialContracts); 68 | 69 | 70 | try { 71 | // wait a couple of seconds for the processing to finish 72 | Thread.sleep(15000); 73 | System.exit(0); 74 | } catch (InterruptedException e) { 75 | e.printStackTrace(); 76 | } 77 | } 78 | 79 | /** 80 | * Creates numContracts number of Ping contracts. The sender is used as the submitting party. 81 | * 82 | * @param channel the gRPC channel to use for services 83 | * @param ledgerId the previously fetched ledger id 84 | * @param sender the party that sends the initial Ping contract 85 | * @param receiver the party that receives the initial Ping contract 86 | * @param numContracts the number of initial contracts to create 87 | */ 88 | private static void createInitialContracts(ManagedChannel channel, String ledgerId, String sender, String receiver, int numContracts) { 89 | CommandSubmissionServiceFutureStub submissionService = CommandSubmissionServiceGrpc.newFutureStub(channel); 90 | 91 | for (int i = 0; i < numContracts; i++) { 92 | // command that creates the initial Ping contract with the required parameters according to the model 93 | List createCommands = Ping.create(sender, receiver, 0L).commands(); 94 | 95 | // wrap the create command in a command submission 96 | CommandsSubmission commandsSubmission = CommandsSubmission.create( 97 | APP_ID, 98 | UUID.randomUUID().toString(), 99 | createCommands) 100 | .withActAs(List.of(sender)) 101 | .withReadAs(List.of(sender)) 102 | .withWorkflowId(String.format("Ping-%s-%d", sender, i)); 103 | 104 | // convert the command submission to a proto data structure 105 | final var request = SubmitRequest.toProto(ledgerId, commandsSubmission); 106 | // asynchronously send the request 107 | submissionService.submit(request); 108 | } 109 | } 110 | 111 | /** 112 | * Fetches the ledger id via the Ledger Identity Service. 113 | * 114 | * @param channel the gRPC channel to use for services 115 | * @return the ledger id as provided by the ledger 116 | */ 117 | private static String fetchLedgerId(ManagedChannel channel) { 118 | LedgerIdentityServiceBlockingStub ledgerIdService = LedgerIdentityServiceGrpc.newBlockingStub(channel); 119 | GetLedgerIdentityResponse identityResponse = ledgerIdService.getLedgerIdentity(GetLedgerIdentityRequest.getDefaultInstance()); 120 | return identityResponse.getLedgerId(); 121 | } 122 | 123 | private static String fetchPartyId(ManagedChannel channel, String userId) { 124 | UserManagementServiceBlockingStub userManagementService = UserManagementServiceGrpc.newBlockingStub(channel); 125 | GetUserResponse getUserResponse = userManagementService.getUser(GetUserRequest.newBuilder().setUserId(userId).build()); 126 | return getUserResponse.getUser().getPrimaryParty(); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/codegen/PingPongProcessor.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.codegen; 5 | 6 | import com.daml.ledger.api.v1.*; 7 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc.CommandSubmissionServiceBlockingStub; 8 | import com.daml.ledger.api.v1.EventOuterClass.Event; 9 | import com.daml.ledger.api.v1.TransactionOuterClass.Transaction; 10 | import com.daml.ledger.api.v1.TransactionServiceGrpc.TransactionServiceStub; 11 | import com.daml.ledger.api.v1.TransactionServiceOuterClass.GetTransactionsResponse; 12 | import com.daml.ledger.javaapi.data.*; 13 | import com.daml.ledger.javaapi.data.codegen.Contract; 14 | import com.daml.ledger.javaapi.data.codegen.ContractCompanion; 15 | import com.daml.ledger.javaapi.data.codegen.Exercised; 16 | import com.daml.ledger.javaapi.data.codegen.Update; 17 | import examples.pingpong.codegen.pingpong.Ping; 18 | import examples.pingpong.codegen.pingpong.Pong; 19 | import io.grpc.ManagedChannel; 20 | import io.grpc.stub.StreamObserver; 21 | 22 | import java.util.List; 23 | import java.util.Map; 24 | import java.util.Set; 25 | import java.util.UUID; 26 | import java.util.function.Function; 27 | import java.util.stream.Collectors; 28 | import java.util.stream.Stream; 29 | 30 | /** 31 | * This class subscribes to the stream of transactions for a given party and reacts to Ping or Pong contracts. 32 | */ 33 | public class PingPongProcessor { 34 | 35 | private final String party; 36 | private final String ledgerId; 37 | 38 | private final TransactionServiceStub transactionService; 39 | private final CommandSubmissionServiceBlockingStub submissionService; 40 | 41 | private final Identifier pingIdentifier; 42 | private final Identifier pongIdentifier; 43 | 44 | public PingPongProcessor(String party, String ledgerId, ManagedChannel channel) { 45 | this.party = party; 46 | this.ledgerId = ledgerId; 47 | this.transactionService = TransactionServiceGrpc.newStub(channel); 48 | this.submissionService = CommandSubmissionServiceGrpc.newBlockingStub(channel); 49 | this.pingIdentifier = Ping.TEMPLATE_ID; 50 | this.pongIdentifier = Pong.TEMPLATE_ID; 51 | } 52 | 53 | public void runIndefinitely() { 54 | // restrict the subscription to ping and pong template types through an inclusive filter 55 | final var inclusiveFilter = InclusiveFilter 56 | .ofTemplateIds(Set.of(pingIdentifier, pongIdentifier)); 57 | // specify inclusive filter for the party attached to this processor 58 | final var filtersByParty = new FiltersByParty(Map.of(party, inclusiveFilter)); 59 | // assemble the request for the transaction stream 60 | final var getTransactionsRequest = new GetTransactionsRequest( 61 | ledgerId, 62 | LedgerOffset.LedgerBegin.getInstance(), 63 | filtersByParty, 64 | true 65 | ); 66 | 67 | // this StreamObserver reacts to transactions and prints a message if an error occurs or the stream gets closed 68 | StreamObserver transactionObserver = new StreamObserver<>() { 69 | @Override 70 | public void onNext(GetTransactionsResponse value) { 71 | value.getTransactionsList().forEach(PingPongProcessor.this::processTransaction); 72 | } 73 | 74 | @Override 75 | public void onError(Throwable t) { 76 | System.err.printf("%s encountered an error while processing transactions!\n", party); 77 | t.printStackTrace(); 78 | } 79 | 80 | @Override 81 | public void onCompleted() { 82 | System.out.printf("%s's transactions stream completed.\n", party); 83 | } 84 | }; 85 | System.out.printf("%s starts reading transactions.\n", party); 86 | transactionService.getTransactions(getTransactionsRequest.toProto(), transactionObserver); 87 | } 88 | 89 | /** 90 | * Processes a transaction and sends the resulting commands to the Command Submission Service 91 | * 92 | * @param tx the Transaction to process 93 | */ 94 | private void processTransaction(Transaction tx) { 95 | List commands = tx.getEventsList().stream() 96 | .filter(Event::hasCreated).map(Event::getCreated) 97 | .flatMap(e -> processEvent(tx.getWorkflowId(), e)) 98 | .collect(Collectors.toList()); 99 | 100 | if (!commands.isEmpty()) { 101 | CommandsSubmission commandsSubmission = CommandsSubmission.create( 102 | PingPongCodegenMain.APP_ID, 103 | UUID.randomUUID().toString(), 104 | commands) 105 | .withActAs(List.of(party)) 106 | .withReadAs(List.of(party)) 107 | .withWorkflowId(tx.getWorkflowId()); 108 | submissionService.submit(SubmitRequest.toProto(ledgerId, commandsSubmission)); 109 | } 110 | } 111 | 112 | /** 113 | * For each {@link CreatedEvent} where the receiver is 114 | * the current party, exercise the Pong choice of Ping contracts, or the Ping 115 | * choice of Pong contracts. 116 | * 117 | * @param workflowId the workflow the event is part of 118 | * @param protoEvent the {@link CreatedEvent} to process 119 | * @return an empty Stream if this event doesn't trigger any action for this {@link PingPongProcessor}'s 120 | * party 121 | */ 122 | private Stream processEvent(String workflowId, EventOuterClass.CreatedEvent protoEvent) { 123 | String templateName = protoEvent.getTemplateId().getEntityName(); 124 | Map fields = protoEvent 125 | .getCreateArguments() 126 | .getFieldsList() 127 | .stream() 128 | .collect(Collectors.toMap(ValueOuterClass.RecordField::getLabel, ValueOuterClass.RecordField::getValue)); 129 | 130 | // check that this party is set as the receiver of the contract 131 | boolean thisPartyIsReceiver = fields.get("receiver").getParty().equals(party); 132 | 133 | if (!thisPartyIsReceiver) return Stream.empty(); 134 | 135 | String contractId = protoEvent.getContractId(); 136 | boolean isPing = templateName.equals(pingIdentifier.getEntityName()); 137 | String choice = isPing ? "RespondPong" : "RespondPing"; 138 | 139 | Long count = fields.get("count").getInt64(); 140 | System.out.printf("%s is exercising %s on %s in workflow %s at count %d\n", party, choice, contractId, workflowId, count); 141 | 142 | final var event = CreatedEvent.fromProto(protoEvent); 143 | 144 | return Stream.concat( 145 | processPingPong( 146 | Ping.COMPANION, 147 | Ping.Exercises::exerciseRespondPong, 148 | event), 149 | processPingPong( 150 | Pong.COMPANION, 151 | Pong.Exercises::exerciseRespondPing, 152 | event) 153 | ); 154 | } 155 | 156 | private , Id, Data> 157 | Stream processPingPong( 158 | ContractCompanion companion, 159 | Function>> createUpdate, 160 | CreatedEvent event) { 161 | if (!event.getTemplateId().getEntityName().equals(companion.TEMPLATE_ID.getEntityName())) 162 | return Stream.empty(); 163 | Ct ct = companion.fromCreatedEvent(event); 164 | Update> update = createUpdate.apply(ct.id); 165 | return update.commands().stream(); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/grpc/PingPongGrpcMain.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.grpc; 5 | 6 | import java.util.Optional; 7 | import java.util.UUID; 8 | 9 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc; 10 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc.CommandSubmissionServiceFutureStub; 11 | import com.daml.ledger.api.v1.CommandSubmissionServiceOuterClass.SubmitRequest; 12 | import com.daml.ledger.api.v1.CommandsOuterClass.Command; 13 | import com.daml.ledger.api.v1.CommandsOuterClass.Commands; 14 | import com.daml.ledger.api.v1.CommandsOuterClass.CreateCommand; 15 | import com.daml.ledger.api.v1.LedgerIdentityServiceGrpc; 16 | import com.daml.ledger.api.v1.LedgerIdentityServiceGrpc.LedgerIdentityServiceBlockingStub; 17 | import com.daml.ledger.api.v1.LedgerIdentityServiceOuterClass.GetLedgerIdentityRequest; 18 | import com.daml.ledger.api.v1.LedgerIdentityServiceOuterClass.GetLedgerIdentityResponse; 19 | import com.daml.ledger.api.v1.ValueOuterClass.Identifier; 20 | import com.daml.ledger.api.v1.ValueOuterClass.Record; 21 | import com.daml.ledger.api.v1.ValueOuterClass.RecordField; 22 | import com.daml.ledger.api.v1.ValueOuterClass.Value; 23 | import com.daml.ledger.api.v1.admin.UserManagementServiceGrpc; 24 | import com.daml.ledger.api.v1.admin.UserManagementServiceGrpc.UserManagementServiceBlockingStub; 25 | import com.daml.ledger.api.v1.admin.UserManagementServiceOuterClass.GetUserRequest; 26 | import com.daml.ledger.api.v1.admin.UserManagementServiceOuterClass.GetUserResponse; 27 | 28 | import io.grpc.ManagedChannel; 29 | import io.grpc.ManagedChannelBuilder; 30 | 31 | public class PingPongGrpcMain { 32 | 33 | // application id used for sending commands 34 | public static final String APP_ID = "PingPongGrpcApp"; 35 | 36 | // constants for referring to the users with access to the parties 37 | public static final String ALICE_USER = "alice"; 38 | public static final String BOB_USER = "bob"; 39 | 40 | public static void main(String[] args) { 41 | // Extract host and port from arguments 42 | if (args.length < 2) { 43 | System.err.println("Usage: HOST PORT [NUM_INITIAL_CONTRACTS]"); 44 | System.exit(-1); 45 | } 46 | String host = args[0]; 47 | int port = Integer.parseInt(args[1]); 48 | 49 | // each party will create this number of initial Ping contracts 50 | int numInitialContracts = args.length == 3 ? Integer.parseInt(args[2]) : 10; 51 | 52 | // Initialize a plaintext gRPC channel 53 | ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); 54 | 55 | // fetch the ledger ID, which is used in subsequent requests sent to the ledger 56 | String ledgerId = fetchLedgerId(channel); 57 | 58 | // fetch the party IDs that got created in the Daml init script 59 | String aliceParty = fetchPartyId(channel, ALICE_USER); 60 | String bobParty = fetchPartyId(channel, BOB_USER); 61 | 62 | String packageId = Optional.ofNullable(System.getProperty("package.id")) 63 | .orElseThrow(() -> new RuntimeException("package.id must be specified via sys properties")); 64 | 65 | Identifier pingIdentifier = Identifier.newBuilder() 66 | .setPackageId(packageId) 67 | .setModuleName("PingPong") 68 | .setEntityName("Ping") 69 | .build(); 70 | Identifier pongIdentifier = Identifier.newBuilder() 71 | .setPackageId(packageId) 72 | .setModuleName("PingPong") 73 | .setEntityName("Pong") 74 | .build(); 75 | 76 | // initialize the ping pong processors for Alice and Bob 77 | PingPongProcessor aliceProcessor = new PingPongProcessor(aliceParty, ledgerId, channel, pingIdentifier, pongIdentifier); 78 | PingPongProcessor bobProcessor = new PingPongProcessor(bobParty, ledgerId, channel, pingIdentifier, pongIdentifier); 79 | 80 | // start the processors asynchronously 81 | aliceProcessor.runIndefinitely(); 82 | bobProcessor.runIndefinitely(); 83 | 84 | // send the initial commands for both parties 85 | createInitialContracts(channel, ledgerId, aliceParty, bobParty, pingIdentifier, numInitialContracts); 86 | createInitialContracts(channel, ledgerId, bobParty, aliceParty, pingIdentifier, numInitialContracts); 87 | 88 | 89 | try { 90 | // wait a couple of seconds for the processing to finish 91 | Thread.sleep(15000); 92 | System.exit(0); 93 | } catch (InterruptedException e) { 94 | e.printStackTrace(); 95 | } 96 | } 97 | 98 | /** 99 | * Creates numContracts number of Ping contracts. The sender is used as the submitting party. 100 | * 101 | * @param channel the gRPC channel to use for services 102 | * @param ledgerId the previously fetched ledger id 103 | * @param sender the party that sends the initial Ping contract 104 | * @param receiver the party that receives the initial Ping contract 105 | * @param pingIdentifier the PingPong.Ping template identifier 106 | * @param numContracts the number of initial contracts to create 107 | */ 108 | private static void createInitialContracts(ManagedChannel channel, String ledgerId, String sender, String receiver, Identifier pingIdentifier, int numContracts) { 109 | CommandSubmissionServiceFutureStub submissionService = CommandSubmissionServiceGrpc.newFutureStub(channel); 110 | 111 | for (int i = 0; i < numContracts; i++) { 112 | // command that creates the initial Ping contract with the required parameters according to the model 113 | Command createCommand = Command.newBuilder().setCreate( 114 | CreateCommand.newBuilder() 115 | .setTemplateId(pingIdentifier) 116 | .setCreateArguments( 117 | Record.newBuilder() 118 | // the identifier for a template's record is the same as the identifier for the template 119 | .setRecordId(pingIdentifier) 120 | .addFields(RecordField.newBuilder().setLabel("sender").setValue(Value.newBuilder().setParty(sender))) 121 | .addFields(RecordField.newBuilder().setLabel("receiver").setValue(Value.newBuilder().setParty(receiver))) 122 | .addFields(RecordField.newBuilder().setLabel("count").setValue(Value.newBuilder().setInt64(0))) 123 | ) 124 | ).build(); 125 | 126 | 127 | SubmitRequest submitRequest = SubmitRequest.newBuilder().setCommands(Commands.newBuilder() 128 | .setLedgerId(ledgerId) 129 | .setCommandId(UUID.randomUUID().toString()) 130 | .setWorkflowId(String.format("Ping-%s-%d", sender, i)) 131 | .setParty(sender) 132 | .setApplicationId(APP_ID) 133 | .addCommands(createCommand) 134 | ).build(); 135 | 136 | // asynchronously send the commands 137 | submissionService.submit(submitRequest); 138 | } 139 | } 140 | 141 | /** 142 | * Fetches the ledger id via the Ledger Identity Service. 143 | * 144 | * @param channel the gRPC channel to use for services 145 | * @return the ledger id as provided by the ledger 146 | */ 147 | private static String fetchLedgerId(ManagedChannel channel) { 148 | LedgerIdentityServiceBlockingStub ledgerIdService = LedgerIdentityServiceGrpc.newBlockingStub(channel); 149 | GetLedgerIdentityResponse identityResponse = ledgerIdService.getLedgerIdentity(GetLedgerIdentityRequest.getDefaultInstance()); 150 | return identityResponse.getLedgerId(); 151 | } 152 | 153 | private static String fetchPartyId(ManagedChannel channel, String userId) { 154 | UserManagementServiceBlockingStub userManagementService = UserManagementServiceGrpc.newBlockingStub(channel); 155 | GetUserResponse getUserResponse = userManagementService.getUser(GetUserRequest.newBuilder().setUserId(userId).build()); 156 | return getUserResponse.getUser().getPrimaryParty(); 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/grpc/PingPongProcessor.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.grpc; 5 | 6 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc; 7 | import com.daml.ledger.api.v1.CommandSubmissionServiceGrpc.CommandSubmissionServiceBlockingStub; 8 | import com.daml.ledger.api.v1.CommandSubmissionServiceOuterClass.SubmitRequest; 9 | import com.daml.ledger.api.v1.CommandsOuterClass.Command; 10 | import com.daml.ledger.api.v1.CommandsOuterClass.Commands; 11 | import com.daml.ledger.api.v1.CommandsOuterClass.ExerciseCommand; 12 | import com.daml.ledger.api.v1.EventOuterClass.CreatedEvent; 13 | import com.daml.ledger.api.v1.EventOuterClass.Event; 14 | import com.daml.ledger.api.v1.LedgerOffsetOuterClass.LedgerOffset; 15 | import com.daml.ledger.api.v1.LedgerOffsetOuterClass.LedgerOffset.LedgerBoundary; 16 | import com.daml.ledger.api.v1.TransactionFilterOuterClass.Filters; 17 | import com.daml.ledger.api.v1.TransactionFilterOuterClass.InclusiveFilters; 18 | import com.daml.ledger.api.v1.TransactionFilterOuterClass.TransactionFilter; 19 | import com.daml.ledger.api.v1.TransactionOuterClass.Transaction; 20 | import com.daml.ledger.api.v1.TransactionServiceGrpc; 21 | import com.daml.ledger.api.v1.TransactionServiceGrpc.TransactionServiceStub; 22 | import com.daml.ledger.api.v1.TransactionServiceOuterClass.GetTransactionsRequest; 23 | import com.daml.ledger.api.v1.TransactionServiceOuterClass.GetTransactionsResponse; 24 | import com.daml.ledger.api.v1.ValueOuterClass.Identifier; 25 | import com.daml.ledger.api.v1.ValueOuterClass.Record; 26 | import com.daml.ledger.api.v1.ValueOuterClass.RecordField; 27 | import com.daml.ledger.api.v1.ValueOuterClass.Value; 28 | import io.grpc.ManagedChannel; 29 | import io.grpc.stub.StreamObserver; 30 | 31 | import java.util.List; 32 | import java.util.Map; 33 | import java.util.UUID; 34 | import java.util.stream.Collectors; 35 | import java.util.stream.Stream; 36 | 37 | /** 38 | * This class subscribes to the stream of transactions for a given party and reacts to Ping or Pong contracts. 39 | */ 40 | public class PingPongProcessor { 41 | 42 | private final String party; 43 | private final String ledgerId; 44 | 45 | private final TransactionServiceStub transactionService; 46 | private final CommandSubmissionServiceBlockingStub submissionService; 47 | 48 | private final Identifier pingIdentifier; 49 | private final Identifier pongIdentifier; 50 | 51 | public PingPongProcessor(String party, String ledgerId, ManagedChannel channel, Identifier pingIdentifier, Identifier pongIdentifier) { 52 | this.party = party; 53 | this.ledgerId = ledgerId; 54 | this.transactionService = TransactionServiceGrpc.newStub(channel); 55 | this.submissionService = CommandSubmissionServiceGrpc.newBlockingStub(channel); 56 | this.pingIdentifier = pingIdentifier; 57 | this.pongIdentifier = pongIdentifier; 58 | } 59 | 60 | public void runIndefinitely() { 61 | // restrict the subscription to ping and pong template types through an inclusive filter 62 | final var filtersByParty = TransactionFilter.newBuilder() 63 | .putFiltersByParty(party, 64 | Filters.newBuilder() 65 | .setInclusive( 66 | InclusiveFilters.newBuilder() 67 | .addTemplateIds(pingIdentifier) 68 | .addTemplateIds(pongIdentifier) 69 | .build()) 70 | .build()); 71 | // assemble the request for the transaction stream 72 | GetTransactionsRequest transactionsRequest = GetTransactionsRequest.newBuilder() 73 | .setLedgerId(ledgerId) 74 | .setBegin(LedgerOffset.newBuilder().setBoundary(LedgerBoundary.LEDGER_BEGIN)) 75 | .setFilter(filtersByParty) 76 | .setVerbose(true) 77 | .build(); 78 | 79 | // this StreamObserver reacts to transactions and prints a message if an error occurs or the stream gets closed 80 | StreamObserver transactionObserver = new StreamObserver() { 81 | @Override 82 | public void onNext(GetTransactionsResponse value) { 83 | value.getTransactionsList().forEach(PingPongProcessor.this::processTransaction); 84 | } 85 | 86 | @Override 87 | public void onError(Throwable t) { 88 | System.err.printf("%s encountered an error while processing transactions!\n", party); 89 | t.printStackTrace(); 90 | } 91 | 92 | @Override 93 | public void onCompleted() { 94 | System.out.printf("%s's transactions stream completed.\n", party); 95 | } 96 | }; 97 | System.out.printf("%s starts reading transactions.\n", party); 98 | transactionService.getTransactions(transactionsRequest, transactionObserver); 99 | } 100 | 101 | /** 102 | * Processes a transaction and sends the resulting commands to the Command Submission Service 103 | * 104 | * @param tx the Transaction to process 105 | */ 106 | private void processTransaction(Transaction tx) { 107 | List commands = tx.getEventsList().stream() 108 | .filter(Event::hasCreated).map(Event::getCreated) 109 | .flatMap(e -> processEvent(tx.getWorkflowId(), e)) 110 | .collect(Collectors.toList()); 111 | 112 | if (!commands.isEmpty()) { 113 | SubmitRequest request = SubmitRequest.newBuilder() 114 | .setCommands(Commands.newBuilder() 115 | .setCommandId(UUID.randomUUID().toString()) 116 | .setWorkflowId(tx.getWorkflowId()) 117 | .setLedgerId(ledgerId) 118 | .setParty(party) 119 | .setApplicationId(PingPongGrpcMain.APP_ID) 120 | .addAllCommands(commands) 121 | .build()) 122 | .build(); 123 | submissionService.submit(request); 124 | } 125 | } 126 | 127 | /** 128 | * For each {@link CreatedEvent} where the receiver is 129 | * the current party, exercise the Pong choice of Ping contracts, or the Ping 130 | * choice of Pong contracts. 131 | * 132 | * @param workflowId the workflow the event is part of 133 | * @param event the {@link CreatedEvent} to process 134 | * @return an empty Stream if this event doesn't trigger any action for this {@link PingPongProcessor}'s 135 | * party 136 | */ 137 | private Stream processEvent(String workflowId, CreatedEvent event) { 138 | Identifier template = event.getTemplateId(); 139 | 140 | boolean isPingPongModule = template.getModuleName().equals(pingIdentifier.getModuleName()); 141 | 142 | boolean isPing = template.getEntityName().equals(pingIdentifier.getEntityName()); 143 | boolean isPong = template.getEntityName().equals(pongIdentifier.getEntityName()); 144 | 145 | if (!isPingPongModule || !isPing && !isPong) return Stream.empty(); 146 | 147 | Map fields = event 148 | .getCreateArguments() 149 | .getFieldsList() 150 | .stream() 151 | .collect(Collectors.toMap(RecordField::getLabel, RecordField::getValue)); 152 | 153 | // check that this party is set as the receiver of the contract 154 | boolean thisPartyIsReceiver = fields.get("receiver").getParty().equals(party); 155 | 156 | if (!thisPartyIsReceiver) return Stream.empty(); 157 | 158 | String contractId = event.getContractId(); 159 | String choice = isPing ? "RespondPong" : "RespondPing"; 160 | 161 | Long count = fields.get("count").getInt64(); 162 | System.out.printf("%s is exercising %s on %s in workflow %s at count %d\n", party, choice, contractId, workflowId, count); 163 | 164 | // assemble the exercise command 165 | Command cmd = Command 166 | .newBuilder() 167 | .setExercise(ExerciseCommand 168 | .newBuilder() 169 | .setTemplateId(template) 170 | .setContractId(contractId) 171 | .setChoice(choice) 172 | .setChoiceArgument(Value.newBuilder().setRecord(Record.getDefaultInstance()))) 173 | .build(); 174 | 175 | return Stream.of(cmd); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/reactive/PingPongProcessor.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.reactive; 5 | 6 | import com.daml.ledger.javaapi.data.*; 7 | import com.daml.ledger.rxjava.LedgerClient; 8 | import com.google.protobuf.Empty; 9 | 10 | import io.reactivex.Flowable; 11 | import io.reactivex.Single; 12 | import io.reactivex.subjects.SingleSubject; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.util.*; 18 | import java.util.stream.Collectors; 19 | import java.util.stream.Stream; 20 | 21 | /** 22 | * This class subscribes to the stream of transactions for a given party and reacts to Ping or Pong contracts. 23 | */ 24 | public class PingPongProcessor { 25 | 26 | private static final Logger logger = LoggerFactory.getLogger(PingPongProcessor.class); 27 | 28 | private final String party; 29 | private final String ledgerId; 30 | private LedgerClient client; 31 | 32 | private final Identifier pingIdentifier; 33 | private final Identifier pongIdentifier; 34 | 35 | public PingPongProcessor(String party, LedgerClient client, Identifier pingIdentifier, Identifier pongIdentifier) { 36 | this.party = party; 37 | this.ledgerId = client.getLedgerId(); 38 | this.client = client; 39 | this.pingIdentifier = pingIdentifier; 40 | this.pongIdentifier = pongIdentifier; 41 | } 42 | 43 | public void runIndefinitely() { 44 | // assemble the request for the transaction stream 45 | Flowable transactions = client.getTransactionsClient().getTransactions( 46 | LedgerOffset.LedgerEnd.getInstance(), 47 | new FiltersByParty(Collections.singletonMap(party, NoFilter.instance)), true); 48 | transactions.forEach(this::processTransaction); 49 | } 50 | 51 | /** 52 | * Processes a transaction and sends the resulting commands to the Command Submission Service 53 | * 54 | * @param tx the Transaction to process 55 | */ 56 | private Single processTransaction(Transaction tx) { 57 | List exerciseCommands = tx.getEvents().stream() 58 | .filter(e -> { 59 | return e instanceof CreatedEvent; 60 | }).map(e -> (CreatedEvent) e) 61 | .flatMap(e -> processEvent(tx.getWorkflowId(), e)) 62 | .collect(Collectors.toList()); 63 | 64 | if (!exerciseCommands.isEmpty()) { 65 | return client.getCommandClient().submitAndWait( 66 | tx.getWorkflowId(), 67 | PingPongReactiveMain.APP_ID, 68 | UUID.randomUUID().toString(), 69 | party, 70 | exerciseCommands); 71 | } else return SingleSubject.create(); 72 | } 73 | 74 | /** 75 | * For each {@link CreatedEvent} where the receiver is 76 | * the current party, exercise the Pong choice of Ping contracts, or the Ping 77 | * choice of Pong contracts. 78 | * 79 | * @param workflowId the workflow the event is part of 80 | * @param event the {@link CreatedEvent} to process 81 | * @return an empty Stream if this event doesn't trigger any action for this {@link PingPongProcessor}'s 82 | * party 83 | */ 84 | private Stream processEvent(String workflowId, CreatedEvent event) { 85 | Identifier template = event.getTemplateId(); 86 | 87 | boolean isPing = template.equals(pingIdentifier); 88 | boolean isPong = template.equals(pongIdentifier); 89 | 90 | if (!isPing && !isPong) return Stream.empty(); 91 | 92 | Map fields = event.getArguments().getFieldsMap(); 93 | 94 | // check that this party is set as the receiver of the contract 95 | boolean thisPartyIsReceiver = fields.get("receiver").asParty().map(receiver -> receiver.getValue().equals(party)) 96 | .orElseThrow(() -> new IllegalStateException("expected 'receiver' to be a party, found " + fields.get("receiver"))); 97 | 98 | if (!thisPartyIsReceiver) return Stream.empty(); 99 | 100 | String contractId = event.getContractId(); 101 | String choice = isPing ? "RespondPong" : "RespondPing"; 102 | 103 | Optional count = fields.get("count").asInt64().map(Int64::getValue); 104 | 105 | logger.info("{} is exercising {} on {} in workflow {} at count {}", party, choice, contractId, workflowId, count.orElse(-1L)); 106 | 107 | // assemble the exercise command 108 | Command cmd = new ExerciseCommand( 109 | template, 110 | contractId, 111 | choice, 112 | new DamlRecord(Collections.emptyList())); 113 | 114 | return Stream.of(cmd); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /PingPong/src/main/java/examples/pingpong/reactive/PingPongReactiveMain.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package examples.pingpong.reactive; 5 | 6 | import java.util.Collections; 7 | import java.util.Optional; 8 | import java.util.UUID; 9 | 10 | import com.daml.ledger.api.v1.CommandsOuterClass.Command; 11 | import com.daml.ledger.api.v1.CommandsOuterClass.CreateCommand; 12 | import com.daml.ledger.api.v1.ValueOuterClass.Identifier; 13 | import com.daml.ledger.api.v1.ValueOuterClass.Record; 14 | import com.daml.ledger.api.v1.ValueOuterClass.RecordField; 15 | import com.daml.ledger.api.v1.ValueOuterClass.Value; 16 | import com.daml.ledger.javaapi.data.GetUserRequest; 17 | import com.daml.ledger.rxjava.DamlLedgerClient; 18 | import com.daml.ledger.rxjava.LedgerClient; 19 | 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | public class PingPongReactiveMain { 24 | 25 | private final static Logger logger = LoggerFactory.getLogger(PingPongReactiveMain.class); 26 | 27 | // application id used for sending commands 28 | public static final String APP_ID = "PingPongReactiveApp"; 29 | 30 | // constants for referring to users with access to the parties 31 | public static final String ALICE_USER = "alice"; 32 | public static final String BOB_USER = "bob"; 33 | 34 | public static void main(String[] args) { 35 | // Extract host and port from arguments 36 | if (args.length < 2) { 37 | System.err.println("Usage: HOST PORT [NUM_INITIAL_CONTRACTS]"); 38 | System.exit(-1); 39 | } 40 | String host = args[0]; 41 | int port = Integer.parseInt(args[1]); 42 | 43 | // each party will create this number of initial Ping contracts 44 | int numInitialContracts = args.length == 3 ? Integer.parseInt(args[2]) : 10; 45 | 46 | // create a client object to access services on the ledger 47 | DamlLedgerClient client = DamlLedgerClient.newBuilder(host, port).build(); 48 | 49 | // Connects to the ledger and runs initial validation 50 | client.connect(); 51 | 52 | var userManagementClient = client.getUserManagementClient(); 53 | String aliceParty = userManagementClient.getUser(new GetUserRequest(ALICE_USER)).blockingGet().getUser().getPrimaryParty().get(); 54 | String bobParty = userManagementClient.getUser(new GetUserRequest(BOB_USER)).blockingGet().getUser().getPrimaryParty().get(); 55 | 56 | String packageId = Optional.ofNullable(System.getProperty("package.id")).orElseThrow(() -> new RuntimeException("package.id must be specified via sys properties")); 57 | var pingIdentifier = com.daml.ledger.javaapi.data.Identifier.fromProto(Identifier.newBuilder() 58 | .setPackageId(packageId).setModuleName("PingPong").setEntityName("Ping").build()); 59 | var pongIdentifier = com.daml.ledger.javaapi.data.Identifier.fromProto(Identifier.newBuilder() 60 | .setPackageId(packageId).setModuleName("PingPong").setEntityName("Pong").build()); 61 | // initialize the ping pong processors for Alice and Bob 62 | PingPongProcessor aliceProcessor = new PingPongProcessor(aliceParty, client, pingIdentifier, pongIdentifier); 63 | PingPongProcessor bobProcessor = new PingPongProcessor(bobParty, client, pingIdentifier, pongIdentifier); 64 | 65 | // start the processors asynchronously 66 | aliceProcessor.runIndefinitely(); 67 | bobProcessor.runIndefinitely(); 68 | 69 | // send the initial commands for both parties 70 | createInitialContracts(client, aliceParty, bobParty, pingIdentifier.toProto(), numInitialContracts); 71 | createInitialContracts(client, bobParty, aliceParty, pingIdentifier.toProto(), numInitialContracts); 72 | 73 | try { 74 | // wait a couple of seconds for the processing to finish 75 | Thread.sleep(20000); 76 | System.exit(0); 77 | } catch (InterruptedException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | 82 | /** 83 | * Creates numContracts number of Ping contracts. The sender is used as the 84 | * submitting party. 85 | * 86 | * @param client the {@link LedgerClient} object to use for services 87 | * @param sender the party that sends the initial Ping contract 88 | * @param receiver the party that receives the initial Ping contract 89 | * @param pingIdentifier the PingPong.Ping template identifier 90 | * @param numContracts the number of initial contracts to create 91 | */ 92 | private static void createInitialContracts(LedgerClient client, String sender, String receiver, 93 | Identifier pingIdentifier, int numContracts) { 94 | 95 | for (int i = 0; i < numContracts; i++) { 96 | // command that creates the initial Ping contract with the required parameters 97 | // according to the model 98 | 99 | Command createCommand = Command.newBuilder().setCreate( 100 | CreateCommand.newBuilder() 101 | .setTemplateId(pingIdentifier) 102 | .setCreateArguments( 103 | Record.newBuilder() 104 | // the identifier for a template's record is the same as the identifier for 105 | // the template 106 | .setRecordId(pingIdentifier) 107 | .addFields(RecordField.newBuilder().setLabel("sender") 108 | .setValue(Value.newBuilder().setParty(sender))) 109 | .addFields(RecordField.newBuilder().setLabel("receiver") 110 | .setValue(Value.newBuilder().setParty(receiver))) 111 | .addFields(RecordField.newBuilder().setLabel("count") 112 | .setValue(Value.newBuilder().setInt64(0))))) 113 | .build(); 114 | 115 | // asynchronously send the commands 116 | client.getCommandClient().submitAndWait( 117 | String.format("Ping-%s-%d", sender, i), 118 | APP_ID, 119 | UUID.randomUUID().toString(), 120 | sender, 121 | Collections.singletonList(com.daml.ledger.javaapi.data.Command.fromProtoCommand(createCommand))) 122 | .blockingGet(); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /PingPong/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 15 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /PingPong/start.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | function getSandboxPid(){ 5 | ss -lptn 'sport = :7575' | grep -P -o '(?<=pid=)([0-9]+)' 6 | } 7 | function cleanup(){ 8 | sandboxPID=$(ss -lptn 'sport = :7575' | grep -P -o '(?<=pid=)([0-9]+)') 9 | if [[ $sandboxPID ]]; then 10 | # kill the sandbox which is running in the background 11 | kill $sandboxPID 12 | fi 13 | } 14 | 15 | trap cleanup ERR EXIT 16 | 17 | echo "Compiling daml" 18 | daml build 19 | packageId=$(daml damlc inspect-dar --json .daml/dist/ex-java-bindings-0.0.2.dar | jq '.main_package_id' -r) 20 | 21 | 22 | echo "Generating java code" 23 | daml codegen java 24 | 25 | echo "Compiling code" 26 | mvn compile 27 | 28 | # Could also run this manually in another terminal without the redirects 29 | echo "Starting sandbox" 30 | daml start --start-navigator false --sandbox-port 7600 > sandbox.log 2>&1 & PID=$! 31 | 32 | 33 | while [[ "$(getSandboxPid)" -eq '' ]] 34 | do 35 | sleep 1 36 | done 37 | 38 | # Run java program 39 | mvn exec:java -Dexec.mainClass=$1 -Dpackage.id=$packageId -Dexec.args="localhost 7600" 40 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Java Bindings Examples 2 | ---------------------- 3 | 4 | :: 5 | 6 | Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 7 | SPDX-License-Identifier: Apache-2.0.0 8 | 9 | This repository contains two subprojects that demonstrate building of Daml client applications with the usage of Java Bindings: 10 | 11 | - `Ping-Pong `_ is a collection of three examples that shows how a Java application would use the `Java Binding library `_ to connect to and exercise a Daml model running on a ledger 12 | - `Stock Exchange `_ shows an advanced use-case of the Java bindings for building a Daml client application that leverages off-ledger data distribution by using `Explicit Contract Disclosure `_ 13 | -------------------------------------------------------------------------------- /StockExchange/README.rst: -------------------------------------------------------------------------------- 1 | Example of Explicit Disclosure with Java Bindings 2 | ---------------------------------------------- 3 | 4 | :: 5 | 6 | Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 7 | SPDX-License-Identifier: Apache-2.0.0 8 | 9 | This project demonstrates the usage of `Explicit Contract Disclosure `_ 10 | in Daml client applications built with the `Java Binding library `_. 11 | 12 | In this example, four parties, each hosted on their own participant (see the topology configuration in `canton_ledger.conf `_), are involved in a simplified trade. 13 | Each party interacts with the Canton ledger via a standalone Java application. The example interaction flow is modelled as follows: 14 | 15 | - Party **Bank** (see `Bank `_) issues ``IOU`` as units of cash to the **Buyer** 16 | - Party **StockExchange** (see `StockExchange `_) issues ``Stock`` as on-ledger asset to the **Seller** party. 17 | Additionally, it issues price ticks for the stock as ``PriceQuotation``. Since **StockExchange** is the sole stakeholder of the ``PriceQuotation``, 18 | it discloses the contract for usage as reference data in commands requiring it as an input. 19 | - Then, party **Seller** (see `Seller `_) owns a unit of ``Stock`` issued by the **StockExchange**. 20 | **Seller** creates an ``Offer`` contract on-ledger that can be accepted by any interested party (see ``Offer_Accept`` in the Daml model). 21 | Similarly to the **StockExchange**, the **Seller** discloses its ``Stock`` and ``Offer`` contracts off-ledger 22 | for interested parties. 23 | - **Buyer** (see `Buyer `_) owns an amount of ``IOU`` issued by **Bank**. 24 | **Buyer** wants to exchange with the **Seller** and accepts its ``Offer`` on-ledger at the correct ``IOU`` market value in exchange of **Seller** s ``Stock``. 25 | In the command submission that exercises ``Offer_Accept``, the **Buyer** uses contracts previously disclosed by the **Seller** and **StockExchange**. 26 | 27 | **Note**: For illustration, the disclosed contracts in this project are shared via files. 28 | (see `Common.shareDisclosedContract `_). 29 | 30 | The Daml model for the templates involved is located in `daml/StockExchange.daml `_`. 31 | 32 | For a better understanding of the explicit disclosure concept and off-ledger data sharing, refer to the 33 | `Explicit Contract Disclosure `_ documentation 34 | where this example's flow is also presented in more detail. 35 | 36 | Running the example 37 | =================== 38 | 39 | #. If you do not have it already, download and unzip `Canton open-source `_ or a later version into a location of your choice. 40 | 41 | #. Use the setup script for exposing the bash example utility functions in two shell terminal windows 42 | 43 | source setup.sh 44 | 45 | #. In one terminal, build the project 46 | 47 | build_example 48 | 49 | #. In the other terminal, start the Canton ledger and wait for initialization until the process prints *Canton server initialization DONE* 50 | 51 | start_canton 52 | 53 | #. In the first terminal, run the example 54 | 55 | run_stock_exchange 56 | -------------------------------------------------------------------------------- /StockExchange/canton_ledger.conf: -------------------------------------------------------------------------------- 1 | canton { 2 | participants { 3 | stockExchangeParticipant { 4 | storage.type = memory 5 | admin-api.port = 5012 6 | ledger-api.port = 5011 7 | } 8 | bankParticipant { 9 | storage.type = memory 10 | admin-api.port = 5022 11 | ledger-api.port = 5021 12 | } 13 | buyerParticipant { 14 | storage.type = memory 15 | admin-api.port = 5032 16 | ledger-api.port = 5031 17 | } 18 | sellerParticipant { 19 | storage.type = memory 20 | admin-api.port = 5042 21 | ledger-api.port = 5041 22 | } 23 | } 24 | domains { 25 | mydomain { 26 | storage.type = memory 27 | public-api.port = 5018 28 | admin-api.port = 5019 29 | } 30 | } 31 | // enable ledger_api commands for setup simplicity of the Ledger API 32 | features.enable-testing-commands = yes 33 | } 34 | -------------------------------------------------------------------------------- /StockExchange/daml.yaml: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | sdk-version: 2.8.0 5 | name: ex-java-bindings-stock-exchange 6 | source: daml/StockExchange.daml 7 | version: 0.0.1 8 | dependencies: 9 | - daml-prim 10 | - daml-stdlib 11 | codegen: 12 | java: 13 | package-prefix: examples.codegen 14 | output-directory: src/main/java/ 15 | -------------------------------------------------------------------------------- /StockExchange/daml/StockExchange.daml: -------------------------------------------------------------------------------- 1 | module StockExchange where 2 | 3 | import DA.Assert 4 | import DA.Action 5 | 6 | template IOU 7 | with 8 | issuer: Party 9 | owner: Party 10 | value: Int 11 | where 12 | signatory issuer 13 | observer owner 14 | 15 | choice IOU_Transfer: () 16 | with 17 | target: Party 18 | amount: Int 19 | controller owner 20 | do 21 | -- Check that the transferred amount is not higher than the current IOU value 22 | assert (value >= amount) 23 | create this with issuer = issuer, owner = target, value = amount 24 | -- No need to create a new IOU for owner if the full value is transferred 25 | if value == amount then pure () 26 | else void $ create this with issuer = issuer, owner = owner, value = value - amount 27 | pure () 28 | 29 | template Stock 30 | with 31 | issuer: Party 32 | owner: Party 33 | stockName: Text 34 | where 35 | signatory issuer 36 | observer owner 37 | 38 | choice Stock_Transfer: () 39 | with 40 | newOwner: Party 41 | controller owner 42 | do 43 | create this with owner = newOwner 44 | pure () 45 | 46 | template PriceQuotation 47 | with 48 | issuer: Party 49 | stockName: Text 50 | value: Int 51 | where 52 | signatory issuer 53 | 54 | nonconsuming choice PriceQuotation_Fetch: PriceQuotation 55 | with fetcher: Party 56 | controller fetcher 57 | do pure this 58 | 59 | template Offer 60 | with 61 | seller: Party 62 | quotationProducer: Party 63 | offeredAssetCid: ContractId Stock 64 | where 65 | signatory seller 66 | 67 | choice Offer_Accept: () 68 | with 69 | priceQuotationCid: ContractId PriceQuotation 70 | buyer: Party 71 | buyerIou: ContractId IOU 72 | controller buyer 73 | do 74 | priceQuotation <- exercise 75 | priceQuotationCid PriceQuotation_Fetch with 76 | fetcher = buyer 77 | asset <- fetch offeredAssetCid 78 | 79 | -- Assert the quotation issuer and asset name 80 | priceQuotation.issuer === quotationProducer 81 | priceQuotation.stockName === asset.stockName 82 | 83 | _ <- exercise 84 | offeredAssetCid Stock_Transfer with 85 | newOwner = buyer 86 | 87 | _ <- exercise 88 | buyerIou IOU_Transfer with target = seller, amount = priceQuotation.value 89 | pure () 90 | -------------------------------------------------------------------------------- /StockExchange/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.daml.ledger.examples 6 | example-stock-exchange-java 7 | jar 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | UTF-8 12 | 11 13 | 11 14 | 2.8.0 15 | 16 | 17 | 18 | 19 | com.daml 20 | bindings-rxjava 21 | ${sdk-version} 22 | 23 | 24 | com.daml 25 | bindings-java 26 | ${sdk-version} 27 | 28 | 29 | ch.qos.logback 30 | logback-classic 31 | 1.4.12 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /StockExchange/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -o pipefail 3 | 4 | function build_example() { 5 | echo "Compiling daml" 6 | daml build 7 | 8 | echo "Generating java code" 9 | daml codegen java 10 | 11 | echo "Compiling code" 12 | mvn compile 13 | } 14 | 15 | function start_canton() { 16 | CANTON_PATH=$1 17 | if [[ -z "$CANTON_PATH" ]]; then 18 | echo "Pass the path to the Canton install dir" 19 | else 20 | echo "Starting Canton" 21 | "$CANTON_PATH"/bin/canton daemon -c canton_ledger.conf --bootstrap stock_exchange_bootstrap_script.canton 22 | fi 23 | } 24 | 25 | function run_stock_exchange() { 26 | echo "Running StockExchange" 27 | stockExchangePartiesFile="temp_stock_exchange_example/stock_exchange_parties.txt" 28 | if [ -e "$stockExchangePartiesFile" ]; then 29 | buyerPartyId=$(sed -n "3p" $stockExchangePartiesFile) 30 | sellerPartyId=$(sed -n "4p" $stockExchangePartiesFile) 31 | stockExchangePartyId=$(sed -n "1p" $stockExchangePartiesFile) 32 | mvn exec:java -Dexec.mainClass=examples.stockexchange.parties.Bank -Dexec.args="5021 Bank ""$buyerPartyId"" 10" 33 | mvn exec:java -Dexec.mainClass=examples.stockexchange.parties.StockExchange -Dexec.args="5011 StockExchange ""$sellerPartyId"" Daml 3" 34 | mvn exec:java -Dexec.mainClass=examples.stockexchange.parties.Seller -Dexec.args="5041 Seller ""$stockExchangePartyId""" 35 | mvn exec:java -Dexec.mainClass=examples.stockexchange.parties.Buyer -Dexec.args="5031 Buyer" 36 | echo "Finished StockExchange example" 37 | else 38 | echo "'$stockExchangePartiesFile' does not exist. Check that the current user has write rights in the current dir and run start_canton before running this function" 39 | fi 40 | } 41 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/Common.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange; 2 | 3 | import com.daml.ledger.javaapi.data.*; 4 | import com.daml.ledger.rxjava.DamlLedgerClient; 5 | import com.google.protobuf.ByteString; 6 | import java.io.*; 7 | import java.util.Base64; 8 | import java.util.Collections; 9 | import java.util.Optional; 10 | 11 | public class Common { 12 | public static final String APP_ID = "StockExchangeApp"; 13 | public static final String PRICE_QUOTATION_DISCLOSED_CONTRACT_FILE = 14 | "temp_stock_exchange_example/price_quotation_disclosed_contract.txt"; 15 | public static final String STOCK_DISCLOSED_CONTRACT_FILE = 16 | "temp_stock_exchange_example/stock_disclosed_contract.txt"; 17 | public static final String OFFER_DISCLOSED_CONTRACT_FILE = 18 | "temp_stock_exchange_example/offer_disclosed_contract.txt"; 19 | 20 | public static DisclosedContract fetchContractForDisclosure( 21 | DamlLedgerClient client, String reader, Identifier templateId) { 22 | CreatedEvent event = 23 | client 24 | .getActiveContractSetClient() 25 | .getActiveContracts( 26 | new FiltersByParty( 27 | Collections.singletonMap( 28 | reader, 29 | new InclusiveFilter( 30 | Collections.emptyMap(), 31 | Collections.singletonMap( 32 | templateId, Filter.Template.INCLUDE_CREATED_EVENT_BLOB)))), 33 | false) 34 | .blockingFirst() 35 | .getCreatedEvents() 36 | .get(0); 37 | return new DisclosedContract( 38 | event.getTemplateId(), event.getContractId(), event.getCreatedEventBlob()); 39 | } 40 | 41 | public static void shareDisclosedContract(DisclosedContract disclosedContract, String fileName) 42 | throws IOException { 43 | try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, false))) { 44 | writer.append( 45 | String.format( 46 | "%s,%s,%s,%s,%s", 47 | disclosedContract.contractId, 48 | disclosedContract.templateId.getPackageId(), 49 | disclosedContract.templateId.getModuleName(), 50 | disclosedContract.templateId.getEntityName(), 51 | Base64.getEncoder() 52 | .encodeToString(disclosedContract.createdEventBlob.toByteArray()))); 53 | } 54 | } 55 | 56 | public static DisclosedContract readDisclosedContract(String fileName) throws IOException { 57 | try (FileReader fr = new FileReader(fileName); 58 | BufferedReader bufferedReader = new BufferedReader(fr)) { 59 | return Optional.ofNullable(bufferedReader.readLine()) 60 | .map( 61 | line -> { 62 | String[] splitted = line.split(","); 63 | return new DisclosedContract( 64 | new Identifier(splitted[1], splitted[2], splitted[3]), 65 | splitted[0], 66 | ByteString.copyFrom(Base64.getDecoder().decode(splitted[4]))); 67 | }) 68 | .orElseThrow( 69 | () -> new IllegalArgumentException(String.format("File %s was empty", fileName))); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/ParticipantSession.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange; 2 | 3 | import com.daml.ledger.javaapi.data.GetUserRequest; 4 | import com.daml.ledger.rxjava.DamlLedgerClient; 5 | 6 | public class ParticipantSession implements AutoCloseable { 7 | private final String partyId; 8 | private final DamlLedgerClient damlLedgerClient; 9 | 10 | public ParticipantSession(int ledgerApiPort, String userId) { 11 | damlLedgerClient = DamlLedgerClient.newBuilder("127.0.0.1", ledgerApiPort).build(); 12 | damlLedgerClient.connect(); 13 | this.partyId = 14 | damlLedgerClient 15 | .getUserManagementClient() 16 | .getUser(new GetUserRequest(userId)) 17 | .blockingGet() 18 | .getUser() 19 | .getPrimaryParty() 20 | .orElseThrow( 21 | () -> 22 | new RuntimeException( 23 | String.format("Primary party not set for user id %s", userId))); 24 | } 25 | 26 | public String getPartyId() { 27 | return partyId; 28 | } 29 | 30 | public DamlLedgerClient getDamlLedgerClient() { 31 | return damlLedgerClient; 32 | } 33 | 34 | @Override 35 | public void close() throws Exception { 36 | damlLedgerClient.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/parties/Bank.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange.parties; 2 | 3 | import com.daml.ledger.javaapi.data.Command; 4 | import com.daml.ledger.javaapi.data.CommandsSubmission; 5 | import examples.codegen.stockexchange.IOU; 6 | import examples.stockexchange.Common; 7 | import examples.stockexchange.ParticipantSession; 8 | import java.util.List; 9 | import java.util.UUID; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | public class Bank { 14 | private static final Logger logger = LoggerFactory.getLogger(Bank.class); 15 | 16 | public static void main(String[] args) throws Exception { 17 | if (args.length < 4) 18 | throw new IllegalArgumentException( 19 | "Arguments: "); 20 | int ledgerApiPort = Integer.parseInt(args[0]); 21 | String userId = args[1]; 22 | String buyerPartyId = args[2]; 23 | long issuedIouValue = Long.parseLong(args[3]); 24 | 25 | logger.info("BANK: Initializing"); 26 | 27 | try (ParticipantSession participantSession = new ParticipantSession(ledgerApiPort, userId)) { 28 | issueIou(participantSession, buyerPartyId, issuedIouValue); 29 | } 30 | } 31 | 32 | private static void issueIou( 33 | ParticipantSession participantSession, String buyerPartyId, long issuedIouValue) { 34 | List newIouCommand = 35 | new IOU(participantSession.getPartyId(), buyerPartyId, issuedIouValue).create().commands(); 36 | CommandsSubmission commandsSubmission = 37 | CommandsSubmission.create(Common.APP_ID, UUID.randomUUID().toString(), newIouCommand) 38 | .withWorkflowId("Bank-issue-IOU") 39 | .withActAs(participantSession.getPartyId()); 40 | 41 | logger.info("BANK: Issuing IOU with value {} to {}", issuedIouValue, buyerPartyId); 42 | participantSession 43 | .getDamlLedgerClient() 44 | .getCommandClient() 45 | .submitAndWait(commandsSubmission) 46 | .blockingGet(); 47 | 48 | logger.info("BANK: Done"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/parties/Buyer.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange.parties; 2 | 3 | import com.daml.ledger.javaapi.data.*; 4 | import examples.codegen.stockexchange.IOU; 5 | import examples.codegen.stockexchange.Offer; 6 | import examples.codegen.stockexchange.PriceQuotation; 7 | import examples.stockexchange.Common; 8 | import examples.stockexchange.ParticipantSession; 9 | import java.io.IOException; 10 | import java.util.Collections; 11 | import java.util.List; 12 | import java.util.UUID; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | public class Buyer { 17 | private static final Logger logger = LoggerFactory.getLogger(Buyer.class); 18 | 19 | public static void main(String[] args) throws Exception { 20 | if (args.length < 2) 21 | throw new IllegalArgumentException("Arguments: "); 22 | int ledgerApiPort = Integer.parseInt(args[0]); 23 | String userId = args[1]; 24 | 25 | logger.info("BUYER: Initializing"); 26 | 27 | try (ParticipantSession participantSession = new ParticipantSession(ledgerApiPort, userId)) { 28 | acceptOffer(participantSession); 29 | } 30 | } 31 | 32 | private static void acceptOffer(ParticipantSession participantSession) throws IOException { 33 | logger.info("BUYER: Fetching contract-id of owned IOU"); 34 | FiltersByParty getIousAcsFilter = 35 | new FiltersByParty( 36 | Collections.singletonMap( 37 | participantSession.getPartyId(), 38 | new InclusiveFilter( 39 | Collections.emptyMap(), 40 | Collections.singletonMap( 41 | IOU.TEMPLATE_ID, Filter.Template.HIDE_CREATED_EVENT_BLOB)))); 42 | 43 | IOU.ContractId iouCid = 44 | new IOU.ContractId( 45 | participantSession 46 | .getDamlLedgerClient() 47 | .getActiveContractSetClient() 48 | .getActiveContracts(getIousAcsFilter, false) 49 | .blockingFirst() 50 | .getCreatedEvents() 51 | .get(0) 52 | .getContractId()); 53 | 54 | logger.info("BUYER: Reading shared disclosed contracts"); 55 | DisclosedContract offer = Common.readDisclosedContract(Common.OFFER_DISCLOSED_CONTRACT_FILE); 56 | DisclosedContract priceQuotation = 57 | Common.readDisclosedContract(Common.PRICE_QUOTATION_DISCLOSED_CONTRACT_FILE); 58 | DisclosedContract stock = Common.readDisclosedContract(Common.STOCK_DISCLOSED_CONTRACT_FILE); 59 | 60 | List disclosedContracts = new java.util.ArrayList<>(); 61 | disclosedContracts.add(priceQuotation); 62 | disclosedContracts.add(offer); 63 | disclosedContracts.add(stock); 64 | 65 | List exerciseAcceptOfferCommand = 66 | new Offer.ContractId(offer.contractId) 67 | .exerciseOffer_Accept( 68 | new PriceQuotation.ContractId(priceQuotation.contractId), 69 | participantSession.getPartyId(), 70 | iouCid) 71 | .commands(); 72 | 73 | CommandsSubmission commandsSubmission = 74 | CommandsSubmission.create( 75 | Common.APP_ID, UUID.randomUUID().toString(), exerciseAcceptOfferCommand) 76 | .withWorkflowId("Buyer-buy-stock") 77 | .withDisclosedContracts(disclosedContracts) 78 | .withActAs(participantSession.getPartyId()); 79 | 80 | logger.info("BUYER: Submitting command for offer acceptance"); 81 | participantSession 82 | .getDamlLedgerClient() 83 | .getCommandClient() 84 | .submitAndWait(commandsSubmission) 85 | .blockingGet(); 86 | 87 | logger.info("BUYER: Success"); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/parties/Seller.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange.parties; 2 | 3 | import com.daml.ledger.javaapi.data.*; 4 | import examples.codegen.stockexchange.Offer; 5 | import examples.codegen.stockexchange.Stock; 6 | import examples.stockexchange.Common; 7 | import examples.stockexchange.ParticipantSession; 8 | import java.io.IOException; 9 | import java.util.Collections; 10 | import java.util.List; 11 | import java.util.UUID; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | public class Seller { 16 | private static final Logger logger = LoggerFactory.getLogger(Seller.class); 17 | 18 | public static void main(String[] args) throws Exception { 19 | logger.info("SELLER: Initializing"); 20 | 21 | if (args.length < 3) 22 | throw new IllegalArgumentException( 23 | "Arguments: "); 24 | 25 | int ledgerApiPort = Integer.parseInt(args[0]); 26 | String userId = args[1]; 27 | String stockExchangePartyId = args[2]; 28 | 29 | try (ParticipantSession participantSession = new ParticipantSession(ledgerApiPort, userId)) { 30 | announceStockSaleOffer(stockExchangePartyId, participantSession); 31 | } 32 | } 33 | 34 | private static void announceStockSaleOffer( 35 | String stockExchangePartyId, ParticipantSession participantSession) throws IOException { 36 | logger.info("SELLER: Fetching contract-id of owned Stock"); 37 | FiltersByParty getStockAcsFilter = 38 | new FiltersByParty( 39 | Collections.singletonMap( 40 | participantSession.getPartyId(), 41 | new InclusiveFilter( 42 | Collections.emptyMap(), 43 | Collections.singletonMap( 44 | Stock.TEMPLATE_ID, Filter.Template.HIDE_CREATED_EVENT_BLOB)))); 45 | 46 | Stock.ContractId stockCid = 47 | new Stock.ContractId( 48 | participantSession 49 | .getDamlLedgerClient() 50 | .getActiveContractSetClient() 51 | .getActiveContracts(getStockAcsFilter, false) 52 | .blockingFirst() 53 | .getCreatedEvents() 54 | .get(0) 55 | .getContractId()); 56 | 57 | List createOfferCommand = 58 | new Offer(participantSession.getPartyId(), stockExchangePartyId, stockCid) 59 | .create() 60 | .commands(); 61 | 62 | CommandsSubmission commandsSubmission = 63 | CommandsSubmission.create(Common.APP_ID, UUID.randomUUID().toString(), createOfferCommand) 64 | .withWorkflowId("Seller-Offer") 65 | .withActAs(participantSession.getPartyId()); 66 | 67 | logger.info("SELLER: Creating on-ledger Offer for selling owned Stock"); 68 | participantSession 69 | .getDamlLedgerClient() 70 | .getCommandClient() 71 | .submitAndWait(commandsSubmission) 72 | .blockingGet(); 73 | 74 | logger.info("SELLER: Fetching Stock disclosed contract for sharing"); 75 | DisclosedContract stockDisclosedContract = 76 | Common.fetchContractForDisclosure( 77 | participantSession.getDamlLedgerClient(), 78 | participantSession.getPartyId(), 79 | Stock.TEMPLATE_ID); 80 | 81 | logger.info("SELLER: Fetching Offer disclosed contract for sharing"); 82 | DisclosedContract offerDisclosedContract = 83 | Common.fetchContractForDisclosure( 84 | participantSession.getDamlLedgerClient(), 85 | participantSession.getPartyId(), 86 | Offer.TEMPLATE_ID); 87 | 88 | logger.info("SELLER: Sharing Stock disclosed contract"); 89 | Common.shareDisclosedContract(stockDisclosedContract, Common.STOCK_DISCLOSED_CONTRACT_FILE); 90 | 91 | logger.info("SELLER: Sharing Offer disclosed contract"); 92 | Common.shareDisclosedContract(offerDisclosedContract, Common.OFFER_DISCLOSED_CONTRACT_FILE); 93 | 94 | logger.info("SELLER: Done"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /StockExchange/src/main/java/examples/stockexchange/parties/StockExchange.java: -------------------------------------------------------------------------------- 1 | package examples.stockexchange.parties; 2 | 3 | import static examples.stockexchange.Common.APP_ID; 4 | import static examples.stockexchange.Common.fetchContractForDisclosure; 5 | 6 | import com.daml.ledger.javaapi.data.Command; 7 | import com.daml.ledger.javaapi.data.CommandsSubmission; 8 | import com.daml.ledger.javaapi.data.DisclosedContract; 9 | import examples.codegen.stockexchange.PriceQuotation; 10 | import examples.codegen.stockexchange.Stock; 11 | import examples.stockexchange.Common; 12 | import examples.stockexchange.ParticipantSession; 13 | import java.io.IOException; 14 | import java.util.List; 15 | import java.util.UUID; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | 19 | public class StockExchange { 20 | private static final Logger logger = LoggerFactory.getLogger(StockExchange.class); 21 | 22 | public static void main(String[] args) throws Exception { 23 | logger.info("STOCK_EXCHANGE: Initializing"); 24 | 25 | if (args.length < 5) 26 | throw new IllegalArgumentException( 27 | "Arguments: "); 28 | int ledgerApiPort = Integer.parseInt(args[0]); 29 | String userId = args[1]; 30 | String sellerPartyId = args[2]; 31 | String issuedStockName = args[3]; 32 | long issuedStockPriceQuotation = Long.parseLong(args[4]); 33 | 34 | try (ParticipantSession participantSession = new ParticipantSession(ledgerApiPort, userId)) { 35 | issueStockAndPriceQuotation( 36 | sellerPartyId, issuedStockName, issuedStockPriceQuotation, participantSession); 37 | } 38 | } 39 | 40 | private static void issueStockAndPriceQuotation( 41 | String sellerPartyId, 42 | String issuedStockName, 43 | long issuedStockPriceQuotation, 44 | ParticipantSession participantSession) 45 | throws IOException { 46 | List createStockCommand = 47 | new Stock(participantSession.getPartyId(), sellerPartyId, issuedStockName) 48 | .create() 49 | .commands(); 50 | 51 | CommandsSubmission issueStockSubmission = 52 | CommandsSubmission.create(APP_ID, UUID.randomUUID().toString(), createStockCommand) 53 | .withWorkflowId("Stock-issue") 54 | .withActAs(participantSession.getPartyId()); 55 | 56 | logger.info("STOCK_EXCHANGE: Issuing stock with name {} to {}", issuedStockName, sellerPartyId); 57 | participantSession 58 | .getDamlLedgerClient() 59 | .getCommandClient() 60 | .submitAndWait(issueStockSubmission) 61 | .blockingGet(); 62 | 63 | List createPriceQuotationCommand = 64 | new PriceQuotation( 65 | participantSession.getPartyId(), issuedStockName, issuedStockPriceQuotation) 66 | .create() 67 | .commands(); 68 | 69 | CommandsSubmission emitPriceQuotationSubmission = 70 | CommandsSubmission.create(APP_ID, UUID.randomUUID().toString(), createPriceQuotationCommand) 71 | .withWorkflowId("PriceQuotation-issue") 72 | .withActAs(participantSession.getPartyId()); 73 | 74 | logger.info( 75 | "STOCK_EXCHANGE: Emitting price quotation for {} at value {}", 76 | issuedStockName, 77 | issuedStockPriceQuotation); 78 | participantSession 79 | .getDamlLedgerClient() 80 | .getCommandClient() 81 | .submitAndWaitForTransaction(emitPriceQuotationSubmission) 82 | .blockingGet() 83 | .getEvents() 84 | .get(0) 85 | .getContractId(); 86 | 87 | logger.info( 88 | "STOCK_EXCHANGE: Fetching PriceQuotation for stock with name {} for disclosure", 89 | issuedStockName); 90 | DisclosedContract priceQuotationDisclosedContract = 91 | fetchContractForDisclosure( 92 | participantSession.getDamlLedgerClient(), 93 | participantSession.getPartyId(), 94 | PriceQuotation.TEMPLATE_ID); 95 | 96 | logger.info("STOCK_EXCHANGE: Sharing PriceQuotation disclosed contract"); 97 | Common.shareDisclosedContract( 98 | priceQuotationDisclosedContract, Common.PRICE_QUOTATION_DISCLOSED_CONTRACT_FILE); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /StockExchange/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 15 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /StockExchange/stock_exchange_bootstrap_script.canton: -------------------------------------------------------------------------------- 1 | import java.nio.file.{Paths, Files, StandardOpenOption} 2 | import java.nio.charset.StandardCharsets 3 | 4 | nodes.local.start() 5 | 6 | val javaBindingsDarPath = ".daml/dist/ex-java-bindings-stock-exchange-0.0.1.dar" 7 | 8 | stockExchangeParticipant.domains.connect_local(mydomain) 9 | bankParticipant.domains.connect_local(mydomain) 10 | buyerParticipant.domains.connect_local(mydomain) 11 | sellerParticipant.domains.connect_local(mydomain) 12 | 13 | stockExchangeParticipant.dars.upload(javaBindingsDarPath) 14 | bankParticipant.dars.upload(javaBindingsDarPath) 15 | buyerParticipant.dars.upload(javaBindingsDarPath) 16 | sellerParticipant.dars.upload(javaBindingsDarPath) 17 | 18 | val stockExchange = stockExchangeParticipant.parties.enable("stockExchange") 19 | val bank = bankParticipant.parties.enable("bank") 20 | val buyer = buyerParticipant.parties.enable("buyer") 21 | val seller = sellerParticipant.parties.enable("seller") 22 | 23 | // Write party ids to a file for allowing easy discovery 24 | val partiesFileContent = s"${stockExchange.toPrim}\n${bank.toPrim}\n${buyer.toPrim}\n${seller.toPrim}" 25 | Files.createDirectories(Paths.get("temp_stock_exchange_example")); 26 | Files.write(Paths.get("temp_stock_exchange_example/stock_exchange_parties.txt"), partiesFileContent.getBytes(StandardCharsets.UTF_8)) 27 | 28 | println("Waiting for the parties to appear on their hosting participants' Ledger API...") 29 | utils.retry_until_true(buyerParticipant.ledger_api.parties.list().exists(_.party.toPrim.toString.startsWith("buyer::"))) 30 | utils.retry_until_true(sellerParticipant.ledger_api.parties.list().exists(_.party.toPrim.toString.startsWith("seller::"))) 31 | utils.retry_until_true(bankParticipant.ledger_api.parties.list().exists(_.party.toPrim.toString.startsWith("bank::"))) 32 | utils.retry_until_true(stockExchangeParticipant.ledger_api.parties.list().exists(_.party.toPrim.toString.startsWith("stockExchange::"))) 33 | 34 | stockExchangeParticipant.ledger_api.users.create("StockExchange", actAs = Set(stockExchange), primaryParty = Some(stockExchange)) 35 | bankParticipant.ledger_api.users.create("Bank", actAs = Set(bank), primaryParty = Some(bank)) 36 | buyerParticipant.ledger_api.users.create("Buyer", actAs = Set(buyer), primaryParty = Some(buyer)) 37 | sellerParticipant.ledger_api.users.create("Seller", actAs = Set(seller), primaryParty = Some(seller)) 38 | 39 | println("Canton server initialization DONE") 40 | --------------------------------------------------------------------------------