├── .eslintrc.json ├── .github ├── settings.yml └── workflows │ ├── release.yml │ └── setlatest.yml ├── .gitignore ├── .npmignore ├── .prettierrc.json ├── CHANGELOG.md ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── MAINTAINERS.md ├── README.md ├── SECURITY.md ├── examples ├── datatypes │ └── index.ts ├── messages │ └── index.ts └── websocket │ └── index.ts ├── images └── hyperledger_firefly_logo.png ├── lib ├── firefly.ts ├── http.ts ├── index.ts ├── interfaces.ts ├── logger.ts ├── schema.ts └── websocket.ts ├── package-lock.json ├── package.json ├── scripts └── parseSchema.ts ├── test └── logger.ts └── tsconfig.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "parserOptions": { 4 | "project": "tsconfig.json", 5 | "sourceType": "module" 6 | }, 7 | "plugins": [ 8 | "@typescript-eslint/eslint-plugin", 9 | "eslint-plugin-import" 10 | ], 11 | "extends": [ 12 | "eslint:recommended", 13 | "plugin:@typescript-eslint/recommended", 14 | "plugin:import/errors", 15 | "plugin:import/warnings", 16 | "plugin:import/typescript" 17 | ], 18 | "root": true, 19 | "env": { 20 | "node": true 21 | }, 22 | "ignorePatterns": [ 23 | ".eslintrc.js", 24 | "lib/schema.ts" 25 | ], 26 | "rules": { 27 | "@typescript-eslint/interface-name-prefix": "off", 28 | "@typescript-eslint/explicit-function-return-type": "off", 29 | "@typescript-eslint/explicit-module-boundary-types": "off", 30 | "@typescript-eslint/no-explicit-any": "off", 31 | "@typescript-eslint/no-floating-promises": "error", 32 | "@typescript-eslint/require-await": "error", 33 | "@typescript-eslint/unbound-method": "error", 34 | "@typescript-eslint/no-unsafe-call": "warn", 35 | "@typescript-eslint/no-unsafe-return": "warn", 36 | "@typescript-eslint/ban-types": "warn", 37 | "@typescript-eslint/no-unused-vars": [ 38 | "warn", 39 | { 40 | "varsIgnorePattern": "^_" 41 | } 42 | ], 43 | "import/first": "warn", 44 | "import/no-duplicates": "warn", 45 | "import/order": "warn", 46 | "semi": [ 47 | "warn", 48 | "always" 49 | ], 50 | "eqeqeq": "error", 51 | "eol-last": "warn", 52 | "no-trailing-spaces": "warn" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | repository: 2 | name: firefly-sdk-nodejs 3 | default_branch: main 4 | has_downloads: false 5 | has_issues: true 6 | has_projects: false 7 | has_wiki: false 8 | archived: false 9 | private: false 10 | allow_squash_merge: false 11 | allow_merge_commit: false 12 | allow_rebase_merge: true 13 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: npm Release 2 | 3 | on: 4 | release: 5 | types: [released, prereleased] 6 | 7 | jobs: 8 | publish: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | # Setup .npmrc file to publish to npm 13 | - uses: actions/setup-node@v4 14 | with: 15 | node-version: '16.x' 16 | registry-url: 'https://registry.npmjs.org' 17 | - run: npm ci 18 | - run: npm publish 19 | env: 20 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 21 | -------------------------------------------------------------------------------- /.github/workflows/setlatest.yml: -------------------------------------------------------------------------------- 1 | name: npm Set Latest 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: 'Version' 8 | required: true 9 | type: string 10 | 11 | jobs: 12 | publish: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/setup-node@v4 16 | with: 17 | node-version: '16.x' 18 | registry-url: 'https://registry.npmjs.org' 19 | - run: npm dist-tag add @hyperledger/firefly-sdk@${{ inputs.version }} latest 20 | env: 21 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | .vscode -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | lib/ 2 | examples/ 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "all" 5 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | The changelog will be updated with the next release 4 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | 3 | # firefly-ui maintainers 4 | * @hyperledger/firefly-sdk-nodejs-maintainers 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | Hyperledger is a collaborative project at The Linux Foundation. It is an open-source and open community project where participants choose to work together, and in that process experience differences in language, location, nationality, and experience. In such a diverse environment, misunderstandings and disagreements happen, which in most cases can be resolved informally. In rare cases, however, behavior can intimidate, harass, or otherwise disrupt one or more people in the community, which Hyperledger will not tolerate. 4 | 5 | A **Code of Conduct** is useful to define accepted and acceptable behaviors and to promote high standards of professional practice. It also provides a benchmark for self evaluation and acts as a vehicle for better identity of the organization. 6 | 7 | This code (**CoC**) applies to any member of the Hyperledger community - developers, participants in meetings, teleconferences, mailing lists, conferences or functions, etc. Note that this code complements rather than replaces legal rights and obligations pertaining to any particular situation. 8 | 9 | # Statement of Intent 10 | 11 | Hyperledger is committed to maintain a **positive** [working environment](#work-environment). This commitment calls for a workplace where [participants](#participant) at all levels behave according to the rules of the following code. A foundational concept of this code is that we all share responsibility for our work environment. 12 | 13 | # Code 14 | 15 | 1. Treat each other with [respect](#respect), professionalism, fairness, and sensitivity to our many differences and strengths, including in situations of high pressure and urgency. 16 | 17 | 2. Never [harass](#harassment) or [bully](#workplace-bullying) anyone verbally, physically or [sexually](#sexual-harassment). 18 | 19 | 3. Never [discriminate](#discrimination) on the basis of personal characteristics or group membership. 20 | 21 | 4. Communicate constructively and avoid [demeaning](#demeaning-behavior) or [insulting](#insulting-behavior) behavior or language. 22 | 23 | 5. Seek, accept, and offer objective work criticism, and [acknowledge](#acknowledgement) properly the contributions of others. 24 | 25 | 6. Be honest about your own qualifications, and about any circumstances that might lead to conflicts of interest. 26 | 27 | 7. Respect the privacy of others and the confidentiality of data you access. 28 | 29 | 8. With respect to cultural differences, be conservative in what you do and liberal in what you accept from others, but not to the point of accepting disrespectful, unprofessional or unfair or [unwelcome behavior](#unwelcome-behavior) or [advances](#unwelcome-sexual-advance). 30 | 31 | 9. Promote the rules of this Code and take action (especially if you are in a [leadership position](#leadership-position)) to bring the discussion back to a more civil level whenever inappropriate behaviors are observed. 32 | 33 | 10. Stay on topic: Make sure that you are posting to the correct channel and avoid off-topic discussions. Remember when you update an issue or respond to an email you are potentially sending to a large number of people. 34 | 35 | 11. Step down considerately: Members of every project come and go, and Hyperledger is no different. When you leave or disengage from the project, in whole or in part, we ask that you do so in a way that minimizes disruption to the project. This means you should tell people you are leaving and take the proper steps to ensure that others can pick up where you left off. 36 | 37 | # Glossary 38 | 39 | ## Demeaning Behavior 40 | 41 | is acting in a way that reduces another person's dignity, sense of self-worth or respect within the community. 42 | 43 | ## Discrimination 44 | 45 | is the prejudicial treatment of an individual based on criteria such as: physical appearance, race, ethnic origin, genetic differences, national or social origin, name, religion, gender, sexual orientation, family or health situation, pregnancy, disability, age, education, wealth, domicile, political view, morals, employment, or union activity. 46 | 47 | ## Insulting Behavior 48 | 49 | is treating another person with scorn or disrespect. 50 | 51 | ## Acknowledgement 52 | 53 | is a record of the origin(s) and author(s) of a contribution. 54 | 55 | ## Harassment 56 | 57 | is any conduct, verbal or physical, that has the intent or effect of interfering with an individual, or that creates an intimidating, hostile, or offensive environment. 58 | 59 | ## Leadership Position 60 | 61 | includes group Chairs, project maintainers, staff members, and Board members. 62 | 63 | ## Participant 64 | 65 | includes the following persons: 66 | 67 | * Developers 68 | 69 | * Member representatives 70 | 71 | * Staff members 72 | 73 | * Anyone from the Public partaking in the Hyperledger work environment (e.g. contribute code, comment on our code or specs, email us, attend our conferences, functions, etc) 74 | 75 | ## Respect 76 | 77 | is the genuine consideration you have for someone (if only because of their status as participant in Hyperledger, like yourself), and that you show by treating them in a polite and kind way. 78 | 79 | ## Sexual Harassment 80 | 81 | includes visual displays of degrading sexual images, sexually suggestive conduct, offensive remarks of a sexual nature, requests for sexual favors, unwelcome physical contact, and sexual assault. 82 | 83 | ## Unwelcome Behavior 84 | 85 | Hard to define? Some questions to ask yourself are: 86 | 87 | * how would I feel if I were in the position of the recipient? 88 | 89 | * would my spouse, parent, child, sibling or friend like to be treated this way? 90 | 91 | * would I like an account of my behavior published in the organization's newsletter? 92 | 93 | * could my behavior offend or hurt other members of the work group? 94 | 95 | * could someone misinterpret my behavior as intentionally harmful or harassing? 96 | 97 | * would I treat my boss or a person I admire at work like that? 98 | 99 | _Summary_: if you are unsure whether something might be welcome or unwelcome, don't do it. 100 | 101 | ## Unwelcome Sexual Advance 102 | 103 | includes requests for sexual favors, and other verbal or physical conduct of a sexual nature, where: 104 | 105 | * submission to such conduct is made either explicitly or implicitly a term or condition of an individual's employment, 106 | 107 | * submission to or rejection of such conduct by an individual is used as a basis for employment decisions affecting the individual, 108 | 109 | * such conduct has the purpose or effect of unreasonably interfering with an individual's work performance or creating an intimidating hostile or offensive working environment. 110 | 111 | ## Workplace Bullying 112 | 113 | is a tendency of individuals or groups to use persistent aggressive or unreasonable behavior (e.g. verbal or written abuse, offensive conduct or any interference which undermines or impedes work) against a co-worker or any professional relations. 114 | 115 | ## Work Environment 116 | 117 | is the set of all available means of collaboration, including, but not limited to messages to mailing lists, private correspondence, Web pages, chat channels, phone and video teleconferences, and any kind of face-to-face meetings or discussions. 118 | 119 | # Incident Procedure 120 | 121 | To report incidents or to appeal reports of incidents, send email to Mike Dolan ([mdolan@linuxfoundation.org](mailto:mdolan@linuxfoundation.org)) or Angela Brown ([angela@linuxfoundation.org](mailto:angela@linuxfoundation.org)). Please include any available relevant information, including links to any publicly accessible material relating to the matter. Every effort will be taken to ensure a safe and collegial environment in which to collaborate on matters relating to the Project. In order to protect the community, the Project reserves the right to take appropriate action, potentially including the removal of an individual from any and all participation in the project. The Project will work towards an equitable resolution in the event of a misunderstanding. 122 | 123 | # Credits 124 | 125 | This code is based on the [W3C's Code of Ethics and Professional Conduct](https://www.w3.org/Consortium/cepc) with some additions from the [Cloud Foundry](https://www.cloudfoundry.org/)'s Code of Conduct. 126 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | We welcome contributions to the FireFly Project in many forms, and 4 | there's always plenty to do! 5 | 6 | Please visit the 7 | [contributors guide](https://hyperledger.github.io/firefly/latest/contributors/index) in the 8 | docs to learn how to make contributions to this exciting project. 9 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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. -------------------------------------------------------------------------------- /MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | # Maintainers 2 | 3 | The following is the list of current maintainers this repo: 4 | 5 | | Name | GitHub | Email | LFID | 6 | | ----------------- | --------------- | ---------------------------- | ----------------- | 7 | | Alex Shorsher | shorsher | alex.shorsher@kaleido.io | shorsher | 8 | | Peter Broadhurst | peterbroadhurst | peter.broadhurst@kaleido.io | peterbroadhurst | 9 | | Andrew Richardson | awrichar | andrew.richardson@kaleido.io | Andrew.Richardson | 10 | | David Echelberger | eberger727 | david.echelberger@kaleido.io | dech727 | 11 | 12 | This list is to be kept up to date as maintainers are added or removed. 13 | 14 | # Expectations of Maintainers 15 | 16 | Maintainers are expected to regularly: 17 | 18 | - Make contributions to FireFly code repositories including code or documentation 19 | - Review pull requests 20 | - Investigate open GitHub issues 21 | - Participate in Community Calls 22 | 23 | # Becoming a Maintainer 24 | 25 | The FireFly Project welcomes and encourages people to become maintainers of the project if they are interested and meet the following criteria: 26 | 27 | ## Criteria for becoming a member 28 | 29 | - Expressed interest and commitment to meet the expectations of a maintainer for at least 6 months 30 | - A consistent track record of contributions to FireFly code repositories which could be: 31 | - Enhancements 32 | - Bug fixes 33 | - Tests 34 | - Documentation 35 | - A consistent track record of helpful code reviews on FireFly code repositories 36 | - Regular participation in Community Calls 37 | - A demonstrated interest and aptitude in thought leadership within the FireFly Project 38 | - Sponsorship from an existing maintainer 39 | 40 | There is no specific quantity of contributions or pull requests, or a specific time period over which the candidate must prove their track record. This will be left up to the discretion of the existing maintainers. 41 | 42 | ## Process for becoming a maintainer 43 | 44 | Once the above criteria have been met, the sponsoring maintainer shall propose the addition of the new maintainer at a public Community Call. Existing maintainers shall vote at the next public Community Call whether the new maintainer should be added or not. Proxy votes may be submitted via email _before_ the meeting. A simple majority of the existing maintainers is required for the vote to pass. 45 | 46 | ## Maintainer resignation 47 | 48 | While maintainers are expected in good faith to be committed to the project for a significant period of time, they are under no binding obligation to do so. Maintainers may resign at any time for any reason. If a maintainer wishes to resign they shall open a pull request to update the maintainers list removing themselves from the list. 49 | 50 | ## Maintainer inactivity 51 | 52 | If a maintainer has remained inactive (not meeting the expectations of a maintainer) for a period of time (at least several months), an email should be sent to that maintainer noting their inactivity and asking if they still wish to be a maintainer. If they continue to be inactive after being notified via email, an existing maintainer may propose to remove the inactive maintainer at a public Community Call. Existing maintainers shall vote at the next public Community Call whether the inactive maintainer should be removed or not. Proxy votes may be submitted via email _before_ the meeting. A simple majority of the existing maintainers is required for the vote to pass. 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FireFly Node.js SDK 2 | 3 | ![version](https://img.shields.io/github/package-json/v/hyperledger/firefly-sdk-nodejs?label=firefly-sdk-nodejs) 4 | [![FireFly Documentation](https://img.shields.io/static/v1?label=FireFly&message=documentation&color=informational)](https://hyperledger.github.io/firefly/latest) 5 | 6 | ![Hyperledger FireFly](./images/hyperledger_firefly_logo.png) 7 | 8 | This is the client SDK for Node.js, allowing you to build your own applications on top of Hyperledger FireFly. 9 | 10 | ## Installation 11 | 12 | ```bash 13 | npm install @hyperledger/firefly-sdk 14 | ``` 15 | 16 | ## Usage 17 | 18 | ```typescript 19 | import FireFly from '@hyperledger/firefly-sdk'; 20 | 21 | async function main() { 22 | const firefly = new FireFly({ host: 'http://localhost:5000' }); 23 | await firefly.sendBroadcast({ 24 | data: [ 25 | { 26 | value: 'test-message', 27 | }, 28 | ], 29 | }); 30 | } 31 | 32 | if (require.main === module) { 33 | main().catch((err) => console.error(`Error: ${err}`)); 34 | } 35 | ``` 36 | 37 | (This example was taken from the [examples](examples) folder where you will find some other basic samples) 38 | 39 | ## Generated schemas 40 | 41 | The types for FireFly requests and responses are generated from the OpenAPI schema for FireFly. If you have 42 | the `firefly` repository cloned in a folder parallel to this one, you can run the following to re-generate 43 | the TypeScript interfaces from the latest FireFly definitions: 44 | 45 | ```bash 46 | npm run schema 47 | ``` 48 | 49 | ## Git repositories 50 | 51 | There are multiple Git repos making up the Hyperledger FireFly project. Some others 52 | that may be helpful to reference: 53 | 54 | - Core - https://github.com/hyperledger/firefly 55 | - Command Line Interface (CLI) - https://github.com/hyperledger/firefly-cli 56 | - FireFly Sandbox - https://github.com/hyperledger/firefly-sandbox 57 | 58 | ## Contributing 59 | 60 | Interested in contributing to the community? 61 | 62 | Check out our [Contributor Guide](https://hyperledger.github.io/firefly/latest/contributors/index), and welcome! 63 | 64 | Please adhere to this project's [Code of Conduct](CODE_OF_CONDUCT.md). 65 | 66 | ## License 67 | 68 | Hyperledger Project source code files are made available under the Apache License, Version 2.0 (Apache-2.0), located in the [LICENSE](LICENSE) file. 69 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Hyperledger Security Policy 2 | 3 | ## Reporting a Security Bug 4 | 5 | If you think you have discovered a security issue in any of the Hyperledger projects, we'd love to 6 | hear from you. We will take all security bugs seriously and if confirmed upon investigation we will 7 | patch it within a reasonable amount of time and release a public security bulletin discussing the 8 | impact and credit the discoverer. 9 | 10 | There are two ways to report a security bug. The easiest is to email a description of the flaw and 11 | any related information (e.g. reproduction steps, version) to 12 | [security at hyperledger dot org](mailto:security@hyperledger.org). 13 | 14 | The other way is to file a confidential security bug in our 15 | [JIRA bug tracking system](https://jira.hyperledger.org). Be sure to set the “Security Level” to 16 | “Security issue”. 17 | 18 | The process by which the Hyperledger Security Team handles security bugs is documented further in 19 | our [Defect Response page](https://wiki.hyperledger.org/display/SEC/Defect+Response) on our 20 | [wiki](https://wiki.hyperledger.org). -------------------------------------------------------------------------------- /examples/datatypes/index.ts: -------------------------------------------------------------------------------- 1 | import FireFly from '../..'; 2 | 3 | async function main() { 4 | const firefly = new FireFly({ host: 'http://localhost:5000' }); 5 | const datatypes = await firefly.getDatatypes(); 6 | console.log(JSON.stringify(datatypes, null, 2)); 7 | } 8 | 9 | if (require.main === module) { 10 | main().catch((err) => console.error(`Error: ${err}`)); 11 | } 12 | -------------------------------------------------------------------------------- /examples/messages/index.ts: -------------------------------------------------------------------------------- 1 | import FireFly from '../..'; 2 | 3 | async function main() { 4 | const firefly = new FireFly({ host: 'http://localhost:5000' }); 5 | await firefly.sendBroadcast({ 6 | data: [ 7 | { 8 | value: 'test-message', 9 | }, 10 | ], 11 | }); 12 | } 13 | 14 | if (require.main === module) { 15 | main().catch((err) => console.error(`Error: ${err}`)); 16 | } 17 | -------------------------------------------------------------------------------- /examples/websocket/index.ts: -------------------------------------------------------------------------------- 1 | import FireFly from '../..'; 2 | 3 | const SUB_NAME = 'test-sub'; 4 | 5 | async function main() { 6 | const firefly = new FireFly({ host: 'http://localhost:5000' }); 7 | const subscriptions = await firefly.getSubscriptions({ name: SUB_NAME }); 8 | if (subscriptions.length > 0) { 9 | await firefly.deleteSubscription(subscriptions[0].id); 10 | } 11 | const subscription = await firefly.createOrUpdateSubscription({ 12 | name: SUB_NAME, 13 | options: { firstEvent: '0' }, 14 | }); 15 | console.log(JSON.stringify(subscription, null, 2)); 16 | 17 | const listener = firefly.listen(SUB_NAME, (socket, event) => { 18 | // do nothing 19 | }); 20 | setTimeout(() => listener.close(), 2000); 21 | } 22 | 23 | if (require.main === module) { 24 | main().catch((err) => console.error(`Error: ${err}`)); 25 | } 26 | -------------------------------------------------------------------------------- /images/hyperledger_firefly_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledger/firefly-sdk-nodejs/53a36b1be14aafbdba2ae0054196a17c9acc75ef/images/hyperledger_firefly_logo.png -------------------------------------------------------------------------------- /lib/firefly.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from 'stream'; 2 | import * as http from 'http'; 3 | import * as FormData from 'form-data'; 4 | import * as WebSocket from 'ws'; 5 | import { 6 | FireFlyStatusResponse, 7 | FireFlyPrivateSendOptions, 8 | FireFlyCreateOptions, 9 | FireFlyGetOptions, 10 | FireFlyWebSocketOptions, 11 | FireFlySubscriptionBase, 12 | FireFlyBatchFilter, 13 | FireFlyContractListenerFilter, 14 | FireFlyOrganizationResponse, 15 | FireFlyVerifierResponse, 16 | FireFlyOrganizationFilter, 17 | FireFlyVerifierFilter, 18 | FireFlyNodeFilter, 19 | FireFlyNodeResponse, 20 | FireFlyBroadcastMessageRequest, 21 | FireFlyMessageResponse, 22 | FireFlyMessageFilter, 23 | FireFlyPrivateMessageRequest, 24 | FireFlyTokenTransferRequest, 25 | FireFlyTokenMintRequest, 26 | FireFlyTokenBurnRequest, 27 | FireFlyDatatypeResponse, 28 | FireFlyDatatypeFilter, 29 | FireFlyDatatypeRequest, 30 | FireFlyBatchResponse, 31 | FireFlyDataResponse, 32 | FireFlyTokenTransferResponse, 33 | FireFlyTokenBalanceResponse, 34 | FireFlyTokenBalanceFilter, 35 | FireFlySubscriptionFilter, 36 | FireFlySubscriptionResponse, 37 | FireFlySubscriptionRequest, 38 | FireFlyTokenPoolRequest, 39 | FireFlyTokenPoolResponse, 40 | FireFlyTokenPoolFilter, 41 | FireFlyTransactionResponse, 42 | FireFlyContractListenerRequest, 43 | FireFlyContractListenerResponse, 44 | FireFlyContractInterfaceRequest, 45 | FireFlyContractInterfaceResponse, 46 | FireFlyContractGenerateRequest, 47 | FireFlyContractAPIRequest, 48 | FireFlyContractAPIResponse, 49 | FireFlyContractInterfaceFilter, 50 | FireFlyContractAPIFilter, 51 | FireFlyTransactionFilter, 52 | FireFlyOperationFilter, 53 | FireFlyOperationResponse, 54 | FireFlyTokenTransferFilter, 55 | FireFlyContractInvokeResponse, 56 | FireFlyContractQueryResponse, 57 | FireFlyContractAPIInvokeRequest, 58 | FireFlyContractAPIQueryRequest, 59 | FireFlyContractInvokeRequest, 60 | FireFlyContractQueryRequest, 61 | FireFlyDataRequest, 62 | FireFlyIdentityFilter, 63 | FireFlyIdentityResponse, 64 | FireFlyIdentitiesResponse, 65 | FireFlyDataFilter, 66 | FireFlyIdentityRequest, 67 | FireFlyGroupResponse, 68 | FireFlyBlockchainEventFilter, 69 | FireFlyBlockchainEventResponse, 70 | FireFlyDataBlobRequest, 71 | FireFlyDataBlobRequestDefaults, 72 | FireFlyVerifierResolveRequest, 73 | FireFlyVerifierResolveResponse, 74 | FireFlyTokenApprovalRequest, 75 | FireFlyNamespaceResponse, 76 | FireFlyUpdateIdentityRequest, 77 | FireFlyReplaceOptions, 78 | FireFlyUpdateOptions, 79 | FireFlyDeleteOptions, 80 | FireFlyTokenApprovalFilter, 81 | FireFlyTokenApprovalResponse, 82 | FireFlyDeployContractRequest, 83 | FireFlyDeployContractResponse, 84 | FireFlyWebSocketConnectCallback, 85 | FireFlyGetWithStatus, 86 | } from './interfaces'; 87 | import { FireFlyWebSocket, FireFlyWebSocketCallback } from './websocket'; 88 | import HttpBase, { mapConfig } from './http'; 89 | 90 | export default class FireFly extends HttpBase { 91 | private queue = Promise.resolve(); 92 | 93 | async getStatus(options?: FireFlyGetOptions): Promise { 94 | const response = await this.http.get('/status', mapConfig(options)); 95 | return response.data; 96 | } 97 | 98 | getIdentities( 99 | filter?: FireFlyIdentityFilter, 100 | options?: FireFlyGetOptions, 101 | ): Promise { 102 | return this.getMany('/identities', filter, options); 103 | } 104 | 105 | getIdentity( 106 | id: string, 107 | options?: FireFlyGetOptions, 108 | ): Promise { 109 | return this.getOne(`/identities/${id}`, options); 110 | } 111 | 112 | createIdentity( 113 | identity: FireFlyIdentityRequest, 114 | options?: FireFlyCreateOptions, 115 | ): Promise { 116 | return this.createOne(`/identities`, identity, options); 117 | } 118 | 119 | updateIdentity( 120 | id: string, 121 | update: FireFlyUpdateIdentityRequest, 122 | options?: FireFlyUpdateOptions, 123 | ): Promise { 124 | return this.updateOne(`/identities/${id}`, update, options); 125 | } 126 | 127 | getOrganizations( 128 | filter?: FireFlyOrganizationFilter, 129 | options?: FireFlyGetOptions, 130 | ): Promise { 131 | return this.getMany('/network/organizations', filter, options); 132 | } 133 | 134 | getOrganization( 135 | nameOrId: string, 136 | options?: FireFlyGetOptions, 137 | ): Promise { 138 | return this.getOne(`/network/organizations/${nameOrId}`, options); 139 | } 140 | 141 | getNodes( 142 | filter?: FireFlyNodeFilter, 143 | options?: FireFlyGetOptions, 144 | ): Promise { 145 | return this.getMany('/network/nodes', filter, options); 146 | } 147 | 148 | getNode( 149 | nameOrId: string, 150 | options?: FireFlyGetOptions, 151 | ): Promise { 152 | return this.getOne(`/network/nodes/${nameOrId}`, options); 153 | } 154 | 155 | getVerifiers( 156 | namespace?: string, 157 | filter?: FireFlyVerifierFilter, 158 | options?: FireFlyGetOptions, 159 | ): Promise { 160 | return namespace 161 | ? this.getMany( 162 | `/namespaces/${namespace}/verifiers`, 163 | filter, 164 | options, 165 | true, 166 | ) 167 | : this.getMany(`/verifiers`, filter, options); 168 | } 169 | 170 | getNamespace( 171 | name: string, 172 | options?: FireFlyGetOptions, 173 | ): Promise { 174 | return this.getOne(`/namespaces/${name}`, undefined, options, true); 175 | } 176 | 177 | getNamespaces(options?: FireFlyGetOptions): Promise { 178 | return this.getMany('/namespaces', undefined, options, true); 179 | } 180 | 181 | getDatatypes( 182 | filter?: FireFlyDatatypeFilter, 183 | options?: FireFlyGetOptions, 184 | ): Promise { 185 | return this.getMany('/datatypes', filter, options); 186 | } 187 | 188 | getDatatype( 189 | name: string, 190 | version: string, 191 | options?: FireFlyGetOptions, 192 | ): Promise { 193 | return this.getOne(`/datatypes/${name}/${version}`, options); 194 | } 195 | 196 | createDatatype( 197 | req: FireFlyDatatypeRequest, 198 | options?: FireFlyCreateOptions, 199 | ): Promise { 200 | return this.createOne('/datatypes', req, options); 201 | } 202 | 203 | getSubscriptions( 204 | filter?: FireFlySubscriptionFilter, 205 | options?: FireFlyGetOptions, 206 | ): Promise { 207 | return this.getMany('/subscriptions', filter, options); 208 | } 209 | 210 | getSubscription( 211 | id: string, 212 | options?: FireFlyGetWithStatus, 213 | ): Promise { 214 | return this.getOne(`/subscriptions/${id}`, options); 215 | } 216 | 217 | replaceSubscription( 218 | sub: FireFlySubscriptionRequest, 219 | options?: FireFlyReplaceOptions, 220 | ): Promise { 221 | return this.replaceOne('/subscriptions', sub, options); 222 | } 223 | 224 | async deleteSubscription(subId: string, options?: FireFlyDeleteOptions) { 225 | await this.deleteOne(`/subscriptions/${subId}`, options); 226 | } 227 | 228 | getData(id: string, options?: FireFlyGetOptions): Promise { 229 | return this.getOne(`/data/${id}`, options); 230 | } 231 | 232 | findData( 233 | filter?: FireFlyDataFilter | URLSearchParams, 234 | options?: FireFlyGetOptions, 235 | ): Promise { 236 | return this.getMany(`/data`, filter, options); 237 | } 238 | 239 | async getDataBlob(id: string, options?: FireFlyGetOptions): Promise { 240 | const response = await this.wrapError( 241 | this.http.get(`/data/${id}/blob`, { 242 | ...mapConfig(options), 243 | responseType: 'stream', 244 | }), 245 | ); 246 | return response.data; 247 | } 248 | 249 | uploadData( 250 | data: FireFlyDataRequest, 251 | options?: FireFlyCreateOptions, 252 | ): Promise { 253 | return this.createOne('/data', data, options); 254 | } 255 | 256 | publishData(id: string, options?: FireFlyCreateOptions): Promise { 257 | return this.createOne(`/data/${id}/value/publish`, {}, options); 258 | } 259 | 260 | async uploadDataBlob( 261 | blob: string | Buffer | Readable, 262 | blobOptions?: FormData.AppendOptions, 263 | dataOptions?: FireFlyDataBlobRequest, 264 | options?: FireFlyCreateOptions, 265 | ): Promise { 266 | dataOptions = { ...FireFlyDataBlobRequestDefaults, ...dataOptions }; 267 | const formData = new FormData(); 268 | for (const key in dataOptions) { 269 | const val = dataOptions[key as keyof FireFlyDataBlobRequest]; 270 | if (val !== undefined) { 271 | formData.append(key, val); 272 | } 273 | } 274 | formData.append('file', blob, blobOptions); 275 | const requestOptions = mapConfig(options); 276 | const response = await this.wrapError( 277 | this.http.post('/data', formData, { 278 | ...requestOptions, 279 | headers: { 280 | ...requestOptions.headers, 281 | ...formData.getHeaders(), 282 | 'Content-Length': formData.getLengthSync(), 283 | }, 284 | }), 285 | ); 286 | return response.data; 287 | } 288 | 289 | publishDataBlob(id: string, options?: FireFlyCreateOptions): Promise { 290 | return this.createOne(`/data/${id}/blob/publish`, {}, options); 291 | } 292 | 293 | async deleteData(id: string, options?: FireFlyDeleteOptions) { 294 | await this.deleteOne(`/data/${id}`, options); 295 | } 296 | 297 | getBatches( 298 | filter?: FireFlyBatchFilter, 299 | options?: FireFlyGetOptions, 300 | ): Promise { 301 | return this.getMany(`/batches`, filter, options); 302 | } 303 | 304 | getMessages( 305 | filter?: FireFlyMessageFilter, 306 | options?: FireFlyGetOptions, 307 | ): Promise { 308 | return this.getMany(`/messages`, filter, options); 309 | } 310 | 311 | getMessage(id: string, options?: FireFlyGetOptions): Promise { 312 | return this.getOne(`/messages/${id}`, options); 313 | } 314 | 315 | sendBroadcast( 316 | message: FireFlyBroadcastMessageRequest, 317 | options?: FireFlyCreateOptions, 318 | ): Promise { 319 | return this.createOne('/messages/broadcast', message, options); 320 | } 321 | 322 | sendPrivateMessage( 323 | message: FireFlyPrivateMessageRequest, 324 | options?: FireFlyPrivateSendOptions, 325 | ): Promise { 326 | const url = options?.requestReply ? '/messages/requestreply' : '/messages/private'; 327 | return this.createOne(url, message, options); 328 | } 329 | 330 | getGroup(hash: string, options?: FireFlyGetOptions): Promise { 331 | return this.getOne(`/groups/${hash}`, options); 332 | } 333 | 334 | createTokenPool( 335 | pool: FireFlyTokenPoolRequest, 336 | options?: FireFlyCreateOptions, 337 | ): Promise { 338 | return this.createOne('/tokens/pools', pool, options); 339 | } 340 | 341 | getTokenPools( 342 | filter?: FireFlyTokenPoolFilter, 343 | options?: FireFlyGetOptions, 344 | ): Promise { 345 | return this.getMany(`/tokens/pools`, filter, options); 346 | } 347 | 348 | getTokenPool( 349 | nameOrId: string, 350 | options?: FireFlyGetOptions, 351 | ): Promise { 352 | return this.getOne(`/tokens/pools/${nameOrId}`, options); 353 | } 354 | 355 | async deleteTokenPool(nameOrId: string, options?: FireFlyDeleteOptions) { 356 | await this.deleteOne(`/tokens/pools/${nameOrId}`, options); 357 | } 358 | 359 | mintTokens(transfer: FireFlyTokenMintRequest, options?: FireFlyCreateOptions) { 360 | return this.createOne('/tokens/mint', transfer, options); 361 | } 362 | 363 | transferTokens( 364 | transfer: FireFlyTokenTransferRequest, 365 | options?: FireFlyCreateOptions, 366 | ): Promise { 367 | return this.createOne('/tokens/transfers', transfer, options); 368 | } 369 | 370 | approveTokens( 371 | approval: FireFlyTokenApprovalRequest, 372 | options?: FireFlyCreateOptions, 373 | ): Promise { 374 | return this.createOne('/tokens/approvals', approval, options); 375 | } 376 | 377 | getTokenApprovals( 378 | filter?: FireFlyTokenApprovalFilter, 379 | options?: FireFlyGetOptions, 380 | ): Promise { 381 | return this.getMany(`/tokens/approvals`, filter, options); 382 | } 383 | 384 | burnTokens( 385 | transfer: FireFlyTokenBurnRequest, 386 | options?: FireFlyCreateOptions, 387 | ): Promise { 388 | return this.createOne('/tokens/burn', transfer, options); 389 | } 390 | 391 | resolveVerifier( 392 | input: FireFlyVerifierResolveRequest, 393 | namespace?: string, 394 | ): Promise { 395 | return this.createOne(`/verifiers/resolve`, input); 396 | } 397 | 398 | getTokenTransfers( 399 | filter?: FireFlyTokenTransferFilter, 400 | options?: FireFlyGetOptions, 401 | ): Promise { 402 | return this.getMany(`/tokens/transfers`, filter, options); 403 | } 404 | 405 | getTokenTransfer( 406 | id: string, 407 | options?: FireFlyGetOptions, 408 | ): Promise { 409 | return this.getOne(`/tokens/transfers/${id}`, options); 410 | } 411 | 412 | getTokenBalances( 413 | filter?: FireFlyTokenBalanceFilter, 414 | options?: FireFlyGetOptions, 415 | ): Promise { 416 | return this.getMany('/tokens/balances', filter, options); 417 | } 418 | 419 | deployContract( 420 | request: FireFlyDeployContractRequest, 421 | options?: FireFlyCreateOptions, 422 | ): Promise { 423 | return this.createOne('/contracts/deploy', request, options); 424 | } 425 | 426 | generateContractInterface( 427 | request: FireFlyContractGenerateRequest, 428 | options?: FireFlyCreateOptions, 429 | ): Promise { 430 | return this.createOne( 431 | '/contracts/interfaces/generate', 432 | request, 433 | options, 434 | ); 435 | } 436 | 437 | createContractInterface( 438 | ffi: FireFlyContractInterfaceRequest, 439 | options?: FireFlyCreateOptions, 440 | ): Promise { 441 | return this.createOne('/contracts/interfaces', ffi, options); 442 | } 443 | 444 | getContractInterfaces( 445 | filter?: FireFlyContractInterfaceFilter, 446 | options?: FireFlyGetOptions, 447 | ): Promise { 448 | return this.getMany( 449 | '/contracts/interfaces', 450 | filter, 451 | options, 452 | ); 453 | } 454 | 455 | getContractInterface( 456 | id: string, 457 | fetchchildren?: boolean, 458 | options?: FireFlyGetOptions, 459 | ): Promise { 460 | return this.getOne(`/contracts/interfaces/${id}`, options, { 461 | fetchchildren, 462 | }); 463 | } 464 | 465 | createContractAPI( 466 | api: FireFlyContractAPIRequest, 467 | options?: FireFlyCreateOptions, 468 | ): Promise { 469 | return this.createOne('/apis', api, options); 470 | } 471 | 472 | getContractAPIs( 473 | filter?: FireFlyContractAPIFilter, 474 | options?: FireFlyGetOptions, 475 | ): Promise { 476 | return this.getMany('/apis', filter, options); 477 | } 478 | 479 | getContractAPI( 480 | name: string, 481 | options?: FireFlyGetOptions, 482 | ): Promise { 483 | return this.getOne(`/apis/${name}`, options); 484 | } 485 | 486 | invokeContract( 487 | request: FireFlyContractInvokeRequest, 488 | options?: FireFlyCreateOptions, 489 | ): Promise { 490 | return this.createOne('/contracts/invoke', request, options); 491 | } 492 | 493 | queryContract( 494 | request: FireFlyContractQueryRequest, 495 | options?: FireFlyCreateOptions, 496 | ): Promise { 497 | return this.createOne('/contracts/query', request, options); 498 | } 499 | 500 | invokeContractAPI( 501 | apiName: string, 502 | methodPath: string, 503 | request: FireFlyContractAPIInvokeRequest, 504 | options?: FireFlyCreateOptions, 505 | ): Promise { 506 | return this.createOne( 507 | `/apis/${apiName}/invoke/${methodPath}`, 508 | request, 509 | options, 510 | ); 511 | } 512 | 513 | queryContractAPI( 514 | apiName: string, 515 | methodPath: string, 516 | request: FireFlyContractAPIQueryRequest, 517 | options?: FireFlyCreateOptions, 518 | ): Promise { 519 | return this.createOne( 520 | `/apis/${apiName}/query/${methodPath}`, 521 | request, 522 | options, 523 | ); 524 | } 525 | 526 | createContractListener( 527 | listener: FireFlyContractListenerRequest, 528 | options?: FireFlyCreateOptions, 529 | ): Promise { 530 | return this.createOne( 531 | '/contracts/listeners', 532 | listener, 533 | options, 534 | ); 535 | } 536 | 537 | getContractListeners( 538 | filter?: FireFlyContractListenerFilter, 539 | options?: FireFlyGetOptions, 540 | ): Promise { 541 | return this.getMany('/contracts/listeners', filter, options); 542 | } 543 | 544 | async deleteContractListener(id: string, options?: FireFlyDeleteOptions) { 545 | await this.deleteOne(`/contracts/listeners/${id}`, options); 546 | } 547 | 548 | getContractAPIListeners( 549 | apiName: string, 550 | eventPath: string, 551 | options?: FireFlyGetOptions, 552 | ): Promise { 553 | return this.getMany( 554 | `/apis/${apiName}/listeners/${eventPath}`, 555 | {}, 556 | options, 557 | ); 558 | } 559 | 560 | createContractAPIListener( 561 | apiName: string, 562 | eventPath: string, 563 | listener: FireFlyContractListenerRequest, 564 | options?: FireFlyCreateOptions, 565 | ) { 566 | return this.createOne( 567 | `/apis/${apiName}/listeners/${eventPath}`, 568 | listener, 569 | options, 570 | ); 571 | } 572 | 573 | getOperations( 574 | filter?: FireFlyOperationFilter, 575 | options?: FireFlyGetOptions, 576 | ): Promise { 577 | return this.getMany('/operations', filter, options); 578 | } 579 | 580 | getOperation( 581 | id: string, 582 | options?: FireFlyGetWithStatus, 583 | ): Promise { 584 | const params = { fetchstatus: options?.fetchstatus }; 585 | return this.getOne(`/operations/${id}`, options, params); 586 | } 587 | 588 | retryOperation(id: string, options?: FireFlyCreateOptions): Promise { 589 | return this.createOne(`/operations/${id}/retry`, {}, options); 590 | } 591 | 592 | getTransactions( 593 | filter?: FireFlyTransactionFilter, 594 | options?: FireFlyGetOptions, 595 | ): Promise { 596 | return this.getMany('/transactions', filter, options); 597 | } 598 | 599 | getTransaction( 600 | id: string, 601 | options?: FireFlyGetOptions, 602 | ): Promise { 603 | return this.getOne(`/transactions/${id}`, options); 604 | } 605 | 606 | getBlockchainEvents( 607 | filter?: FireFlyBlockchainEventFilter, 608 | options?: FireFlyGetOptions, 609 | ): Promise { 610 | return this.getMany('/blockchainevents', filter, options); 611 | } 612 | 613 | getBlockchainEvent( 614 | id: string, 615 | options?: FireFlyGetOptions, 616 | ): Promise { 617 | return this.getOne(`/blockchainevents/${id}`, options); 618 | } 619 | 620 | listen( 621 | subscriptions: string | string[] | FireFlySubscriptionBase, 622 | callback: FireFlyWebSocketCallback, 623 | socketOptions?: WebSocket.ClientOptions | http.ClientRequestArgs, 624 | fireflySocketOptions?: Partial | FireFlyWebSocketConnectCallback, 625 | ): FireFlyWebSocket { 626 | if (typeof fireflySocketOptions === 'function') { 627 | // Legacy compatibility (afterConnect callback passed as 4th arg) 628 | fireflySocketOptions = { 629 | afterConnect: fireflySocketOptions, 630 | }; 631 | } 632 | const options: FireFlyWebSocketOptions = { 633 | host: this.options.websocket.host, 634 | namespace: this.options.namespace, 635 | username: this.options.username, 636 | password: this.options.password, 637 | reconnectDelay: this.options.websocket.reconnectDelay, 638 | heartbeatInterval: this.options.websocket.heartbeatInterval, 639 | autoack: false, 640 | ...fireflySocketOptions, 641 | socketOptions, 642 | subscriptions: [], 643 | }; 644 | 645 | const handler: FireFlyWebSocketCallback = (socket, event) => { 646 | this.queue = this.queue.finally(() => callback(socket, event)); 647 | if (!options.noack) { 648 | this.queue.then(() => { 649 | socket.ack(event); 650 | }); 651 | } 652 | }; 653 | 654 | if (Array.isArray(subscriptions)) { 655 | options.subscriptions = subscriptions; 656 | } else if (typeof subscriptions === 'string') { 657 | options.subscriptions = [subscriptions]; 658 | } else { 659 | options.ephemeral = { ...subscriptions, namespace: this.options.namespace }; 660 | } 661 | 662 | return new FireFlyWebSocket(options, handler); 663 | } 664 | } 665 | -------------------------------------------------------------------------------- /lib/http.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; 2 | import { 3 | FireFlyOptions, 4 | FireFlyOptionsInput, 5 | FireFlyCreateOptions, 6 | FireFlyGetOptions, 7 | FireFlyError, 8 | FireFlyReplaceOptions, 9 | FireFlyUpdateOptions, 10 | FireFlyDeleteOptions, 11 | FireFlyIdempotencyError, 12 | FireFlyGetWithStatus, 13 | } from './interfaces'; 14 | 15 | function isSuccess(status: number) { 16 | return status >= 200 && status < 300; 17 | } 18 | 19 | export function mapConfig( 20 | options: 21 | | FireFlyGetOptions 22 | | FireFlyGetWithStatus 23 | | FireFlyUpdateOptions 24 | | FireFlyReplaceOptions 25 | | FireFlyCreateOptions 26 | | FireFlyDeleteOptions 27 | | undefined, 28 | params?: any, 29 | ): AxiosRequestConfig { 30 | const config: AxiosRequestConfig = { 31 | ...options?.requestConfig, 32 | params, 33 | }; 34 | 35 | if (options !== undefined) { 36 | if ('confirm' in options) { 37 | config.params = { 38 | ...config.params, 39 | confirm: options.confirm, 40 | }; 41 | } 42 | if ('publish' in options) { 43 | config.params = { 44 | ...config.params, 45 | publish: options.publish, 46 | }; 47 | } 48 | if ('fetchstatus' in options) { 49 | config.params = { 50 | ...config.params, 51 | fetchstatus: options.fetchstatus, 52 | }; 53 | } 54 | } 55 | return config; 56 | } 57 | 58 | export default class HttpBase { 59 | protected options: FireFlyOptions; 60 | protected rootHttp: AxiosInstance; 61 | protected http: AxiosInstance; 62 | 63 | private errorHandler?: (err: FireFlyError) => void; 64 | 65 | constructor(options: FireFlyOptionsInput) { 66 | this.options = this.setDefaults(options); 67 | this.rootHttp = axios.create({ 68 | ...options.requestConfig, 69 | baseURL: this.options.baseURL, 70 | }); 71 | this.http = axios.create({ 72 | ...options.requestConfig, 73 | baseURL: this.options.namespaceBaseURL, 74 | }); 75 | } 76 | 77 | private setDefaults(options: FireFlyOptionsInput): FireFlyOptions { 78 | const baseURLSet = (options.baseURL ?? '') !== '' && (options.namespaceBaseURL ?? '' !== ''); 79 | if (!baseURLSet && (options.host ?? '') === '') { 80 | throw new Error('Invalid options. Option host, or baseURL and namespaceBaseURL must be set.'); 81 | } 82 | if ((options.host ?? '') === '' && (options.websocket?.host ?? '') === '') { 83 | throw new Error('Invalid options. Option host, or websocket.host must be set.'); 84 | } 85 | return { 86 | ...options, 87 | baseURL: baseURLSet ? options.baseURL : `${options.host}/api/v1`, 88 | namespaceBaseURL: baseURLSet 89 | ? options.namespaceBaseURL 90 | : `${options.host}/api/v1/namespaces/${options.namespace}`, 91 | namespace: options.namespace ?? 'default', 92 | websocket: { 93 | ...options.websocket, 94 | host: options.websocket?.host ?? options.host.replace('http', 'ws'), 95 | reconnectDelay: options.websocket?.reconnectDelay ?? 5000, 96 | heartbeatInterval: options.websocket?.heartbeatInterval ?? 30000, 97 | }, 98 | }; 99 | } 100 | 101 | protected async wrapError(response: Promise>) { 102 | return response.catch((err) => { 103 | if (axios.isAxiosError(err)) { 104 | const errorMessage = err.response?.data?.error ?? err.message; 105 | const errorClass = 106 | errorMessage?.includes('FF10430') || errorMessage?.includes('FF10431') 107 | ? FireFlyIdempotencyError 108 | : FireFlyError; 109 | const ffError = new errorClass(errorMessage, err, err.request.path); 110 | if (this.errorHandler !== undefined) { 111 | this.errorHandler(ffError); 112 | } 113 | throw ffError; 114 | } 115 | throw err; 116 | }); 117 | } 118 | 119 | protected async getMany(url: string, params?: any, options?: FireFlyGetOptions, root = false) { 120 | const http = root ? this.rootHttp : this.http; 121 | const response = await this.wrapError(http.get(url, mapConfig(options, params))); 122 | return response.data; 123 | } 124 | 125 | protected async getOne(url: string, options?: FireFlyGetOptions, params?: any, root = false) { 126 | const http = root ? this.rootHttp : this.http; 127 | const response = await this.wrapError( 128 | http.get(url, { 129 | ...mapConfig(options, params), 130 | validateStatus: (status) => status === 404 || isSuccess(status), 131 | }), 132 | ); 133 | return response.status === 404 ? undefined : response.data; 134 | } 135 | 136 | protected async createOne(url: string, data: any, options?: FireFlyCreateOptions) { 137 | const response = await this.wrapError(this.http.post(url, data, mapConfig(options))); 138 | return response.data; 139 | } 140 | 141 | protected async updateOne(url: string, data: any, options?: FireFlyUpdateOptions) { 142 | const response = await this.wrapError(this.http.patch(url, data, mapConfig(options))); 143 | return response.data; 144 | } 145 | 146 | protected async replaceOne(url: string, data: any, options?: FireFlyReplaceOptions) { 147 | const response = await this.wrapError(this.http.put(url, data, mapConfig(options))); 148 | return response.data; 149 | } 150 | 151 | protected async deleteOne(url: string, options?: FireFlyDeleteOptions) { 152 | await this.wrapError(this.http.delete(url, mapConfig(options))); 153 | } 154 | 155 | onError(handler: (err: FireFlyError) => void) { 156 | this.errorHandler = handler; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | import FireFly from './firefly'; 2 | export default FireFly; 3 | export * from './interfaces'; 4 | -------------------------------------------------------------------------------- /lib/interfaces.ts: -------------------------------------------------------------------------------- 1 | import * as http from 'http'; 2 | import { AxiosRequestConfig } from 'axios'; 3 | import * as WebSocket from 'ws'; 4 | import { operations } from './schema'; 5 | 6 | /** 7 | * Most types in this file are aliased from request/response body types that 8 | * are generated from the OpenAPI specification for FireFly. 9 | * 10 | * Because the spec doesn't accurately reflect "required" fields, currently 11 | * all request types below mark every field as optional, and response types 12 | * mark every field as being set. This is not completely accurate, but should 13 | * be close enough for most use cases. 14 | */ 15 | 16 | // General 17 | 18 | export class FireFlyError extends Error { 19 | constructor(message?: string, public originalError?: Error, public path?: string) { 20 | super(message); 21 | } 22 | } 23 | 24 | export class FireFlyIdempotencyError extends FireFlyError {} 25 | 26 | interface FireFlyBaseHttpOptions { 27 | requestConfig?: AxiosRequestConfig; 28 | } 29 | 30 | export interface FireFlyGetOptions extends FireFlyBaseHttpOptions {} 31 | export interface FireFlyUpdateOptions extends FireFlyBaseHttpOptions {} 32 | export interface FireFlyReplaceOptions extends FireFlyBaseHttpOptions {} 33 | export interface FireFlyDeleteOptions extends FireFlyBaseHttpOptions {} 34 | 35 | export interface FireFlyCreateOptions extends FireFlyBaseHttpOptions { 36 | confirm?: boolean; 37 | publish?: boolean; 38 | } 39 | 40 | export interface FireFlyGetWithStatus extends FireFlyGetOptions { 41 | fetchstatus?: string; 42 | } 43 | 44 | export interface FireFlyOptionsInput { 45 | host: string; 46 | namespace?: string; 47 | username?: string; 48 | password?: string; 49 | baseURL?: string; 50 | namespaceBaseURL?: string; 51 | websocket?: { 52 | host?: string; 53 | reconnectDelay?: number; 54 | heartbeatInterval?: number; 55 | }; 56 | requestConfig?: AxiosRequestConfig; 57 | } 58 | 59 | export interface FireFlyOptions extends FireFlyOptionsInput { 60 | namespace: string; 61 | websocket: { 62 | host: string; 63 | reconnectDelay: number; 64 | heartbeatInterval: number; 65 | }; 66 | } 67 | 68 | export interface FireFlyWebSocketSender { 69 | send: (json: JSON) => void; 70 | } 71 | 72 | export interface FireFlyWebSocketConnectCallback { 73 | (sender: FireFlyWebSocketSender): void | Promise; 74 | } 75 | 76 | export interface FireFlyWebSocketOptions { 77 | host: string; 78 | namespace: string; 79 | subscriptions: string[]; 80 | username?: string; 81 | password?: string; 82 | ephemeral?: FireFlyEphemeralSubscription; 83 | autoack?: boolean; 84 | noack?: boolean; 85 | reconnectDelay: number; 86 | heartbeatInterval: number; 87 | socketOptions?: WebSocket.ClientOptions | http.ClientRequestArgs; 88 | afterConnect?: FireFlyWebSocketConnectCallback; 89 | } 90 | 91 | // Namespace 92 | export type FireFlyNamespaceResponse = Required< 93 | operations['getNamespace']['responses']['200']['content']['application/json'] 94 | >; 95 | 96 | // Network 97 | 98 | export type FireFlyIdentityFilter = operations['getIdentities']['parameters']['query']; 99 | export type FireFlyOrganizationFilter = operations['getNetworkOrgs']['parameters']['query']; 100 | export type FireFlyNodeFilter = operations['getNetworkNodes']['parameters']['query']; 101 | export type FireFlyVerifierFilter = operations['getVerifiers']['parameters']['query']; 102 | 103 | export type FireFlyIdentityRequest = 104 | operations['postNewIdentity']['requestBody']['content']['application/json']; 105 | export type FireFlyUpdateIdentityRequest = 106 | operations['patchUpdateIdentity']['requestBody']['content']['application/json']; 107 | 108 | export type FireFlyIdentityResponse = Required< 109 | operations['getIdentityByID']['responses']['200']['content']['application/json'] 110 | >; 111 | export type FireFlyIdentitiesResponse = Required< 112 | operations['getIdentities']['responses']['200']['content']['application/json'] 113 | >; 114 | export type FireFlyOrganizationResponse = Required< 115 | operations['getNetworkOrg']['responses']['200']['content']['application/json'] 116 | >; 117 | export type FireFlyNodeResponse = Required< 118 | operations['getNetworkNode']['responses']['200']['content']['application/json'] 119 | >; 120 | export type FireFlyVerifierResponse = Required< 121 | operations['getVerifierByID']['responses']['200']['content']['application/json'] 122 | >; 123 | export type FireFlyStatusResponse = Required< 124 | operations['getStatus']['responses']['200']['content']['application/json'] 125 | >; 126 | 127 | // Subscriptions 128 | 129 | export type FireFlySubscriptionFilter = operations['getSubscriptions']['parameters']['query']; 130 | 131 | export type FireFlySubscriptionRequest = 132 | operations['postNewSubscription']['requestBody']['content']['application/json']; 133 | 134 | export type FireFlySubscriptionResponse = Required< 135 | operations['getSubscriptionByID']['responses']['200']['content']['application/json'] 136 | > & { status?: any }; 137 | export type FireFlyEventResponse = Required< 138 | operations['getEventByID']['responses']['200']['content']['application/json'] 139 | >; 140 | 141 | // Verifier 142 | 143 | export type FireFlyVerifierResolveRequest = Required< 144 | operations['postVerifiersResolveNamespace']['requestBody']['content']['application/json'] 145 | >; 146 | 147 | export type FireFlyVerifierResolveResponse = Required< 148 | operations['postVerifiersResolveNamespace']['responses']['200']['content']['application/json'] 149 | >; 150 | export interface FireFlySubscriptionBase { 151 | filter?: { 152 | events?: string; 153 | }; 154 | options?: { 155 | firstEvent?: string; 156 | readAhead?: number; 157 | withData?: boolean; 158 | }; 159 | } 160 | 161 | export interface FireFlyEphemeralSubscription extends FireFlySubscriptionBase { 162 | namespace: string; 163 | } 164 | 165 | export interface FireFlyEnrichedEvent extends FireFlyEventResponse { 166 | blockchainEvent?: FireFlyBlockchainEventResponse; 167 | contractAPI?: FireFlyContractAPIResponse; 168 | contractInterface?: FireFlyContractInterfaceResponse; 169 | datatype?: FireFlyDatatypeResponse; 170 | identity?: FireFlyIdentityResponse; 171 | message?: FireFlyMessageResponse; 172 | tokenApproval?: FireFlyTokenApprovalResponse; 173 | tokenPool?: FireFlyTokenPoolResponse; 174 | tokenTransfer?: FireFlyTokenTransferResponse; 175 | transaction?: FireFlyTransactionResponse; 176 | operation?: FireFlyOperationResponse; 177 | } 178 | 179 | export interface FireFlyEventDelivery extends Omit { 180 | type: FireFlyEnrichedEvent['type'] | 'protocol_error'; 181 | subscription: { 182 | id: string; 183 | name: string; 184 | namespace: string; 185 | }; 186 | } 187 | 188 | export interface FireFlyEventBatchDelivery { 189 | type: 'event_batch'; 190 | id: string; 191 | subscription: { 192 | id: string; 193 | name: string; 194 | namespace: string; 195 | }; 196 | events: FireFlyEventDelivery[]; 197 | } 198 | 199 | // Datatypes 200 | 201 | export type FireFlyDatatypeFilter = operations['getDatatypes']['parameters']['query']; 202 | 203 | export type FireFlyDatatypeRequest = 204 | operations['postNewDatatype']['requestBody']['content']['application/json']; 205 | 206 | export type FireFlyDatatypeResponse = 207 | operations['getDatatypeByName']['responses']['200']['content']['application/json']; 208 | 209 | // Data 210 | 211 | export type FireFlyDataFilter = operations['getData']['parameters']['query']; 212 | 213 | export type FireFlyDataRequest = 214 | operations['postData']['requestBody']['content']['application/json']; 215 | export type FireFlyDataBlobRequest = 216 | operations['postData']['requestBody']['content']['multipart/form-data']; 217 | 218 | export type FireFlyDataResponse = Required< 219 | operations['getDataByID']['responses']['200']['content']['application/json'] 220 | >; 221 | 222 | export const FireFlyDataBlobRequestDefaults: FireFlyDataBlobRequest = { 223 | autometa: 'true', 224 | }; 225 | 226 | // Messages 227 | 228 | export type FireFlyMessageFilter = operations['getMsgs']['parameters']['query']; 229 | export type FireFlyBatchFilter = operations['getBatches']['parameters']['query']; 230 | 231 | export type FireFlyBroadcastMessageRequest = 232 | operations['postNewMessageBroadcast']['requestBody']['content']['application/json']; 233 | export type FireFlyPrivateMessageRequest = 234 | operations['postNewMessagePrivate']['requestBody']['content']['application/json']; 235 | 236 | export type FireFlyMessageResponse = Required< 237 | operations['getMsgByID']['responses']['200']['content']['application/json'] 238 | >; 239 | export type FireFlyBatchResponse = Required< 240 | operations['getBatchByID']['responses']['200']['content']['application/json'] 241 | >; 242 | export type FireFlyGroupResponse = Required< 243 | operations['getGroupByHash']['responses']['200']['content']['application/json'] 244 | >; 245 | 246 | export interface FireFlyPrivateSendOptions extends FireFlyCreateOptions { 247 | requestReply?: boolean; 248 | } 249 | 250 | // Token Pools 251 | 252 | export type FireFlyTokenPoolFilter = operations['getTokenPools']['parameters']['query']; 253 | 254 | export type FireFlyTokenPoolRequest = 255 | operations['postTokenPool']['requestBody']['content']['application/json']; 256 | 257 | export type FireFlyTokenPoolResponse = Required< 258 | operations['getTokenPoolByNameOrID']['responses']['200']['content']['application/json'] 259 | >; 260 | 261 | // Token Transfers 262 | 263 | export type FireFlyTokenTransferFilter = operations['getTokenTransfers']['parameters']['query']; 264 | 265 | export type FireFlyTokenMintRequest = 266 | operations['postTokenMint']['requestBody']['content']['application/json']; 267 | export type FireFlyTokenBurnRequest = 268 | operations['postTokenBurn']['requestBody']['content']['application/json']; 269 | export type FireFlyTokenTransferRequest = 270 | operations['postTokenTransfer']['requestBody']['content']['application/json']; 271 | 272 | export type FireFlyTokenTransferResponse = Required< 273 | operations['getTokenTransferByID']['responses']['200']['content']['application/json'] 274 | >; 275 | 276 | // Token Balances 277 | 278 | export type FireFlyTokenBalanceFilter = operations['getTokenBalances']['parameters']['query']; 279 | 280 | type BalancesList = Required< 281 | operations['getTokenBalances']['responses']['200']['content']['application/json'] 282 | >; 283 | const balances: BalancesList = []; 284 | export type FireFlyTokenBalanceResponse = typeof balances[0]; 285 | 286 | // Token Approvals 287 | 288 | export type FireFlyTokenApprovalFilter = operations['getTokenApprovals']['parameters']['query']; 289 | 290 | export type FireFlyTokenApprovalRequest = 291 | operations['postTokenApproval']['requestBody']['content']['application/json']; 292 | type ApprovalsList = 293 | operations['getTokenApprovals']['responses']['200']['content']['application/json']; 294 | 295 | const approvals: ApprovalsList = []; 296 | export type FireFlyTokenApprovalResponse = typeof approvals[0]; 297 | 298 | // Operations + Transactions 299 | 300 | export type FireFlyOperationFilter = operations['getOps']['parameters']['query']; 301 | export type FireFlyTransactionFilter = operations['getTxns']['parameters']['query']; 302 | 303 | export type FireFlyOperationResponse = Required< 304 | operations['getOpByID']['responses']['200']['content']['application/json'] 305 | >; 306 | 307 | export type FireFlyTransactionResponse = Required< 308 | operations['getTxnByID']['responses']['200']['content']['application/json'] 309 | >; 310 | 311 | // Contracts 312 | 313 | export type FireFlyContractInterfaceFilter = 314 | operations['getContractInterfaces']['parameters']['query']; 315 | export type FireFlyContractAPIFilter = operations['getContractAPIs']['parameters']['query']; 316 | export type FireFlyContractListenerFilter = 317 | operations['getContractListeners']['parameters']['query']; 318 | 319 | export type FireFlyDeployContractRequest = 320 | operations['postContractDeploy']['requestBody']['content']['application/json']; 321 | export type FireFlyContractGenerateRequest = 322 | operations['postGenerateContractInterface']['requestBody']['content']['application/json']; 323 | export type FireFlyContractInterfaceRequest = 324 | operations['postNewContractInterface']['requestBody']['content']['application/json']; 325 | export type FireFlyContractAPIRequest = 326 | operations['postNewContractAPI']['requestBody']['content']['application/json']; 327 | export type FireFlyContractListenerRequest = 328 | operations['postNewContractListener']['requestBody']['content']['application/json']; 329 | 330 | export type FireFlyDeployContractResponse = Required< 331 | operations['postContractDeploy']['responses']['200']['content']['application/json'] 332 | >; 333 | export type FireFlyContractInterfaceResponse = Required< 334 | operations['getContractInterface']['responses']['200']['content']['application/json'] 335 | >; 336 | export type FireFlyContractAPIResponse = Required< 337 | operations['getContractAPIByName']['responses']['200']['content']['application/json'] 338 | >; 339 | export type FireFlyContractListenerResponse = Required< 340 | operations['getContractListenerByNameOrID']['responses']['200']['content']['application/json'] 341 | >; 342 | 343 | export type FireFlyContractInvokeRequest = 344 | operations['postContractInvoke']['requestBody']['content']['application/json']; 345 | export type FireFlyContractAPIInvokeRequest = 346 | operations['postContractAPIInvoke']['requestBody']['content']['application/json']; 347 | export type FireFlyContractInvokeResponse = Required< 348 | operations['postContractInvoke']['responses']['202']['content']['application/json'] 349 | >; 350 | 351 | export type FireFlyContractQueryRequest = 352 | operations['postContractQuery']['requestBody']['content']['application/json']; 353 | export type FireFlyContractAPIQueryRequest = 354 | operations['postContractAPIQuery']['requestBody']['content']['application/json']; 355 | export type FireFlyContractQueryResponse = Required< 356 | operations['postContractQuery']['responses']['200']['content']['application/json'] 357 | >; 358 | 359 | // Blockchain Events 360 | 361 | export type FireFlyBlockchainEventFilter = operations['getBlockchainEvents']['parameters']['query']; 362 | 363 | export type FireFlyBlockchainEventResponse = Required< 364 | operations['getBlockchainEventByID']['responses']['200']['content']['application/json'] 365 | >; 366 | -------------------------------------------------------------------------------- /lib/logger.ts: -------------------------------------------------------------------------------- 1 | enum logLevels { 2 | LEVEL_NONE, 3 | LEVEL_ERROR, 4 | LEVEL_WARN, 5 | LEVEL_LOG, 6 | LEVEL_INFO, 7 | LEVEL_DEBUG, 8 | LEVEL_TRACE 9 | } 10 | 11 | export default class Logger { 12 | 13 | private logLevel = logLevels.LEVEL_LOG; 14 | 15 | constructor(private prefix: string) { 16 | switch (process.env.FF_SDK_LOG_LEVEL) { 17 | case 'NONE': this.logLevel = logLevels.LEVEL_NONE; break; 18 | case 'ERROR': this.logLevel = logLevels.LEVEL_ERROR; break; 19 | case 'WARN': this.logLevel = logLevels.LEVEL_WARN; break; 20 | case 'LOG': this.logLevel = logLevels.LEVEL_LOG; break; 21 | case 'INFO': this.logLevel = logLevels.LEVEL_INFO; break; 22 | case 'DEBUG': this.logLevel = logLevels.LEVEL_DEBUG; break; 23 | case 'TRACE': this.logLevel = logLevels.LEVEL_TRACE; break; 24 | } 25 | } 26 | 27 | private formatMessage(message: string) { 28 | const now = new Date().toISOString(); 29 | return `${now} [${this.prefix}] ${message}`; 30 | } 31 | 32 | error(message?: any, ...optionalParams: any[]): void { 33 | this.logLevel >= logLevels.LEVEL_ERROR && console.error(this.formatMessage(message), ...optionalParams); 34 | } 35 | 36 | warn(message?: any, ...optionalParams: any[]): void { 37 | this.logLevel >= logLevels.LEVEL_WARN && console.warn(this.formatMessage(message), ...optionalParams); 38 | } 39 | 40 | log(message?: any, ...optionalParams: any[]): void { 41 | this.logLevel >= logLevels.LEVEL_LOG && console.log(this.formatMessage(message), ...optionalParams); 42 | } 43 | 44 | info(message?: any, ...optionalParams: any[]): void { 45 | this.logLevel >= logLevels.LEVEL_INFO && console.info(this.formatMessage(message), ...optionalParams); 46 | } 47 | 48 | debug(message?: any, ...optionalParams: any[]): void { 49 | this.logLevel >= logLevels.LEVEL_DEBUG && console.debug(this.formatMessage(message), ...optionalParams); 50 | } 51 | 52 | trace(message?: any, ...optionalParams: any[]): void { 53 | this.logLevel >= logLevels.LEVEL_TRACE && console.trace(this.formatMessage(message), ...optionalParams); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /lib/websocket.ts: -------------------------------------------------------------------------------- 1 | import { IncomingMessage } from 'http'; 2 | import { Transform } from 'stream'; 3 | import * as WebSocket from 'ws'; 4 | import { 5 | FireFlyEphemeralSubscription, 6 | FireFlyWebSocketOptions, 7 | FireFlyEventDelivery, 8 | FireFlyEventBatchDelivery, 9 | } from './interfaces'; 10 | import Logger from './logger'; 11 | 12 | function buildEphemeralQueryParams(sub: FireFlyEphemeralSubscription) { 13 | const params = new URLSearchParams(); 14 | params.append('ephemeral', 'true'); 15 | params.append('namespace', sub.namespace); 16 | if (sub.filter?.events !== undefined) { 17 | params.append('filter.events', sub.filter.events); 18 | } 19 | return params.toString(); 20 | } 21 | 22 | export interface FireFlyWebSocketCallback { 23 | ( 24 | socket: FireFlyWebSocket, 25 | data: FireFlyEventDelivery | FireFlyEventBatchDelivery, 26 | ): void | Promise; 27 | } 28 | 29 | export class FireFlyWebSocket { 30 | private readonly logger = new Logger(FireFlyWebSocket.name); 31 | 32 | private socket?: WebSocket; 33 | private closed? = () => {}; 34 | private pingTimer?: NodeJS.Timeout; 35 | private disconnectTimer?: NodeJS.Timeout; 36 | private reconnectTimer?: NodeJS.Timeout; 37 | private disconnectDetected = false; 38 | 39 | constructor( 40 | private options: FireFlyWebSocketOptions, 41 | private callback: FireFlyWebSocketCallback, 42 | ) { 43 | this.connect(); 44 | } 45 | 46 | private connect() { 47 | // Ensure we've cleaned up any old socket 48 | this.close(); 49 | if (this.reconnectTimer) { 50 | clearTimeout(this.reconnectTimer); 51 | delete this.reconnectTimer; 52 | } 53 | 54 | let url = `${this.options.host}/ws`; 55 | if (this.options.ephemeral !== undefined) { 56 | url += '?' + buildEphemeralQueryParams(this.options.ephemeral); 57 | } 58 | 59 | const auth = 60 | this.options.username && this.options.password 61 | ? `${this.options.username}:${this.options.password}` 62 | : undefined; 63 | const socket = (this.socket = new WebSocket(url, { 64 | ...this.options.socketOptions, 65 | auth, 66 | handshakeTimeout: this.options.heartbeatInterval, 67 | })); 68 | this.closed = undefined; 69 | 70 | socket 71 | .on('open', () => { 72 | if (this.disconnectDetected) { 73 | this.disconnectDetected = false; 74 | this.logger.log('Connection restored'); 75 | } else { 76 | this.logger.log('Connected'); 77 | } 78 | this.schedulePing(); 79 | for (const name of this.options.subscriptions) { 80 | socket.send( 81 | JSON.stringify({ 82 | type: 'start', 83 | autoack: this.options.autoack, 84 | namespace: this.options.namespace, 85 | name, 86 | }), 87 | ); 88 | this.logger.log(`Started listening on subscription ${this.options.namespace}:${name}`); 89 | } 90 | if (this.options?.afterConnect !== undefined) { 91 | this.options.afterConnect(this); 92 | } 93 | }) 94 | .on('error', (err) => { 95 | this.logger.error('Error', err.stack); 96 | }) 97 | .on('close', () => { 98 | if (this.closed) { 99 | this.logger.log('Closed'); 100 | this.closed(); // do this after all logging 101 | } else { 102 | this.disconnectDetected = true; 103 | this.reconnect('Closed by peer'); 104 | } 105 | }) 106 | .on('pong', () => { 107 | this.logger.debug(`WS received pong`); 108 | this.schedulePing(); 109 | }) 110 | .on('unexpected-response', (req, res: IncomingMessage) => { 111 | let responseData = ''; 112 | res.pipe( 113 | new Transform({ 114 | transform(chunk, encoding, callback) { 115 | responseData += chunk; 116 | callback(); 117 | }, 118 | flush: () => { 119 | this.reconnect(`FireFly connect error [${res.statusCode}]: ${responseData}`); 120 | }, 121 | }), 122 | ); 123 | }) 124 | .on('message', (data: string) => { 125 | const event: FireFlyEventDelivery = JSON.parse(data); 126 | this.callback(this, event); 127 | }); 128 | } 129 | 130 | private clearPingTimers() { 131 | if (this.disconnectTimer) { 132 | clearTimeout(this.disconnectTimer); 133 | delete this.disconnectTimer; 134 | } 135 | if (this.pingTimer) { 136 | clearTimeout(this.pingTimer); 137 | delete this.pingTimer; 138 | } 139 | } 140 | 141 | private schedulePing() { 142 | this.clearPingTimers(); 143 | this.disconnectTimer = setTimeout( 144 | () => this.reconnect('Heartbeat timeout'), 145 | Math.ceil(this.options.heartbeatInterval * 1.5), // 50% grace period 146 | ); 147 | this.pingTimer = setTimeout(() => { 148 | this.logger.debug(`WS sending ping`); 149 | this.socket?.ping('ping', true, (err) => { 150 | if (err) this.reconnect(err.message); 151 | }); 152 | }, this.options.heartbeatInterval); 153 | } 154 | 155 | private reconnect(msg: string) { 156 | if (!this.reconnectTimer) { 157 | this.close(); 158 | this.logger.error(`Websocket closed: ${msg}`); 159 | if (this.options.reconnectDelay === -1) { 160 | // do not attempt to reconnect 161 | } else { 162 | this.reconnectTimer = setTimeout(() => this.connect(), this.options.reconnectDelay); 163 | } 164 | } 165 | } 166 | 167 | send(json: JSON) { 168 | if (this.socket !== undefined) { 169 | this.socket.send(JSON.stringify(json)); 170 | } 171 | } 172 | 173 | ack(event: FireFlyEventDelivery | FireFlyEventBatchDelivery) { 174 | if (this.socket !== undefined && event.id !== undefined) { 175 | this.socket.send( 176 | JSON.stringify({ 177 | type: 'ack', 178 | id: event.id, 179 | subscription: event.subscription, 180 | }), 181 | ); 182 | } 183 | } 184 | 185 | async close(wait?: boolean): Promise { 186 | const closedPromise = new Promise((resolve) => { 187 | this.closed = resolve; 188 | }); 189 | this.clearPingTimers(); 190 | if (this.socket) { 191 | try { 192 | this.socket.close(); 193 | } catch (e: any) { 194 | this.logger.warn(`Failed to clean up websocket: ${e.message}`); 195 | } 196 | if (wait) await closedPromise; 197 | this.socket = undefined; 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@hyperledger/firefly-sdk", 3 | "version": "1.3.3", 4 | "description": "Client SDK for Hyperledger FireFly", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "prebuild": "rimraf dist", 9 | "build": "tsc", 10 | "prepare": "npm run build", 11 | "test": "mocha -r ts-node/register --bail --timeout 30000 'test/**/*.ts'", 12 | "lint": "eslint \"lib/*.ts\"", 13 | "lint:fix": "eslint \"lib/*.ts\" --fix", 14 | "format": "prettier --write \"lib/*.ts\" \"examples/**/*.ts\"", 15 | "schema": "ts-node scripts/parseSchema.ts" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/hyperledger/firefly-sdk-nodejs.git" 20 | }, 21 | "author": "", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/hyperledger/firefly-sdk-nodejs/issues" 25 | }, 26 | "homepage": "https://github.com/hyperledger/firefly-sdk-nodejs#readme", 27 | "devDependencies": { 28 | "@types/mocha": "^9.1.1", 29 | "@types/sinon": "^10.0.13", 30 | "@types/ws": "^8.5.10", 31 | "@typescript-eslint/eslint-plugin": "^5.17.0", 32 | "@typescript-eslint/parser": "^5.19.0", 33 | "eslint": "^8.12.0", 34 | "eslint-plugin-import": "^2.25.4", 35 | "mocha": "^10.0.0", 36 | "openapi-typescript": "^7.6.1", 37 | "prettier": "^2.6.1", 38 | "rimraf": "^3.0.2", 39 | "sinon": "^14.0.0", 40 | "ts-node": "^10.9.2", 41 | "typescript": "^5.8.3" 42 | }, 43 | "dependencies": { 44 | "axios": "^1.6.8", 45 | "form-data": "^4.0.0", 46 | "ws": "^8.17.1" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /scripts/parseSchema.ts: -------------------------------------------------------------------------------- 1 | import { promises as fs } from 'fs'; 2 | import openapiTS, { astToString } from 'openapi-typescript'; 3 | import * as ts from 'typescript'; 4 | import { pathToFileURL } from 'url'; 5 | 6 | const STRING = ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword); 7 | const ANY = ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); 8 | 9 | async function run() { 10 | const localPath = pathToFileURL('../firefly/doc-site/docs/swagger/swagger.yaml'); 11 | console.log(`Generating types from ${localPath}`); 12 | const output = await openapiTS(localPath.toString(), { 13 | transform: (schemaObject, options) => { 14 | if (schemaObject.type === 'object' && schemaObject.additionalProperties) { 15 | // For objects with arbitrary properties, use "any" instead of "unknown" 16 | return ANY; 17 | } 18 | 19 | if (schemaObject.type === undefined) { 20 | // For objects with undefined type, use "any" instead of "unknown" 21 | return ANY; 22 | } 23 | 24 | if (options.path && options.path.indexOf('/responses/') >= 0 && schemaObject.nullable) { 25 | // Override all response fields to be non-nullable (but allow undefined) 26 | schemaObject.nullable = false; 27 | } 28 | }, 29 | }); 30 | await fs.writeFile('lib/schema.ts', astToString(output)); 31 | } 32 | 33 | run().catch((err) => { 34 | console.error('Error running script', err); 35 | }); 36 | -------------------------------------------------------------------------------- /test/logger.ts: -------------------------------------------------------------------------------- 1 | import Logger from '../lib/logger'; 2 | import { spy, assert, SinonSpy } from 'sinon'; 3 | 4 | describe('logger', () => { 5 | 6 | let errorSpy: SinonSpy; 7 | let warnSpy: SinonSpy; 8 | let logSpy: SinonSpy; 9 | let infoSpy: SinonSpy; 10 | let debugSpy: SinonSpy; 11 | let traceSpy: SinonSpy; 12 | 13 | beforeEach(() => { 14 | errorSpy = spy(console, 'error'); 15 | warnSpy = spy(console, 'warn'); 16 | logSpy = spy(console, 'log'); 17 | infoSpy = spy(console, 'info'); 18 | debugSpy = spy(console, 'debug'); 19 | traceSpy = spy(console, 'trace'); 20 | }); 21 | 22 | afterEach(() => { 23 | errorSpy.restore(); 24 | warnSpy.restore(); 25 | logSpy.restore(); 26 | infoSpy.restore(); 27 | debugSpy.restore(); 28 | traceSpy.restore(); 29 | }); 30 | 31 | it('level NONE', () => { 32 | process.env.FF_SDK_LOG_LEVEL = 'NONE'; 33 | const logger = new Logger('test'); 34 | submit(logger); 35 | assert.notCalled(errorSpy); 36 | assert.notCalled(warnSpy); 37 | assert.notCalled(logSpy); 38 | assert.notCalled(infoSpy); 39 | assert.notCalled(debugSpy); 40 | assert.notCalled(traceSpy); 41 | }); 42 | 43 | it('level ERROR', () => { 44 | process.env.FF_SDK_LOG_LEVEL = 'ERROR'; 45 | const logger = new Logger('test'); 46 | submit(logger); 47 | assert.called(errorSpy); 48 | assert.notCalled(warnSpy); 49 | assert.notCalled(logSpy); 50 | assert.notCalled(infoSpy); 51 | assert.notCalled(debugSpy); 52 | assert.notCalled(traceSpy); 53 | }); 54 | 55 | it('level WARN', () => { 56 | process.env.FF_SDK_LOG_LEVEL = 'WARN'; 57 | const logger = new Logger('test'); 58 | submit(logger); 59 | assert.called(errorSpy); 60 | assert.called(warnSpy); 61 | assert.notCalled(logSpy); 62 | assert.notCalled(infoSpy); 63 | assert.notCalled(debugSpy); 64 | assert.notCalled(traceSpy); 65 | }); 66 | 67 | it('level LOG', () => { 68 | process.env.FF_SDK_LOG_LEVEL = 'LOG'; 69 | const logger = new Logger('test'); 70 | submit(logger); 71 | assert.called(errorSpy); 72 | assert.called(warnSpy); 73 | assert.called(logSpy); 74 | assert.notCalled(infoSpy); 75 | assert.notCalled(debugSpy); 76 | assert.notCalled(traceSpy); 77 | }); 78 | 79 | it('level INFO', () => { 80 | process.env.FF_SDK_LOG_LEVEL = 'INFO'; 81 | const logger = new Logger('test'); 82 | submit(logger); 83 | assert.called(errorSpy); 84 | assert.called(warnSpy); 85 | assert.called(logSpy); 86 | assert.called(infoSpy); 87 | assert.notCalled(debugSpy); 88 | assert.notCalled(traceSpy); 89 | }); 90 | 91 | it('level DEBUG', () => { 92 | process.env.FF_SDK_LOG_LEVEL = 'DEBUG'; 93 | const logger = new Logger('test'); 94 | submit(logger); 95 | assert.called(errorSpy); 96 | assert.called(warnSpy); 97 | assert.called(logSpy); 98 | assert.called(infoSpy); 99 | assert.called(debugSpy); 100 | assert.notCalled(traceSpy); 101 | }); 102 | 103 | it('level TRACE', () => { 104 | process.env.FF_SDK_LOG_LEVEL = 'TRACE'; 105 | const logger = new Logger('test'); 106 | submit(logger); 107 | assert.called(errorSpy); 108 | assert.called(warnSpy); 109 | assert.called(logSpy); 110 | assert.called(infoSpy); 111 | assert.called(debugSpy); 112 | assert.called(traceSpy); 113 | }); 114 | 115 | function submit(logger: Logger) { 116 | logger.error('error'); 117 | logger.warn('warn'); 118 | logger.log('log'); 119 | logger.info('info'); 120 | logger.debug('debug'); 121 | logger.trace('trace'); 122 | } 123 | 124 | }); 125 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2016", 4 | "module": "commonjs", 5 | "strict": true, 6 | "skipLibCheck": true, 7 | "declaration": true, 8 | "outDir": "./dist" 9 | }, 10 | "include": ["lib/**/*"] 11 | } 12 | --------------------------------------------------------------------------------