diff --git a/.changeset/busy-loops-move.md b/.changeset/busy-loops-move.md new file mode 100644 index 000000000..f348cf366 --- /dev/null +++ b/.changeset/busy-loops-move.md @@ -0,0 +1,6 @@ +--- +"@hashgraph/asset-tokenization-sdk": major +"@hashgraph/asset-tokenization-dapp": minor +--- + +[ATS-SDK] Add tokenBalance and decimals to getCouponFor and [ATS-WEB] add fullRedeem in forceRedeem view and balance in seeCoupons and seeDividend views diff --git a/.changeset/large-aliens-train.md b/.changeset/large-aliens-train.md new file mode 100644 index 000000000..0e428dac4 --- /dev/null +++ b/.changeset/large-aliens-train.md @@ -0,0 +1,6 @@ +--- +"@hashgraph/asset-tokenization-dapp": minor +"@hashgraph/asset-tokenization-sdk": patch +--- + +Add a checkbox in force redeem view to redeem every tokens if the maturity date has arrived diff --git a/apps/ats/web/src/hooks/queries/useFullRedeemAtMaturity.ts b/apps/ats/web/src/hooks/queries/useFullRedeemAtMaturity.ts new file mode 100644 index 000000000..f0f1e25c0 --- /dev/null +++ b/apps/ats/web/src/hooks/queries/useFullRedeemAtMaturity.ts @@ -0,0 +1,40 @@ +//SPDX-License-Identifier: Apache-2.0 + +import { UseMutationOptions, useMutation } from "@tanstack/react-query"; +import { SDKService } from "../../services/SDKService"; +import { FullRedeemAtMaturityRequest } from "@hashgraph/asset-tokenization-sdk"; +import { useToast } from "io-bricks-ui"; +import { useTranslation } from "react-i18next"; + +export const useFullRedeemAtMaturity = ( + options: UseMutationOptions = {}, +) => { + const toast = useToast(); + const { t } = useTranslation("security", { keyPrefix: "redeem" }); + + return useMutation((request: FullRedeemAtMaturityRequest) => SDKService.fullRedeemAtMaturity(request), { + onSuccess: (data) => { + if (data) { + toast.show({ + duration: 3000, + title: `${t("messages.success")}`, + description: `${t("messages.descriptionSuccess")}`, + variant: "subtle", + status: "success", + }); + } else { + toast.show({ + duration: 3000, + title: t("messages.error"), + description: t("messages.descriptionFailed"), + variant: "subtle", + status: "error", + }); + } + }, + onError: (error) => { + console.log("SDK message --> Full redeem at maturity error: ", error); + }, + ...options, + }); +}; diff --git a/apps/ats/web/src/i18n/en/security/coupons.ts b/apps/ats/web/src/i18n/en/security/coupons.ts index bbe67890d..653d42bc7 100644 --- a/apps/ats/web/src/i18n/en/security/coupons.ts +++ b/apps/ats/web/src/i18n/en/security/coupons.ts @@ -69,10 +69,8 @@ export default { details: { title: "Detail", paymentDay: "Payment day", - period: "Period", + balance: "Balance", amount: "Amount", - numerator: "Numerator", - denominator: "Denominator", recordDateReached: "Record Date Reached", }, }, diff --git a/apps/ats/web/src/i18n/en/security/dividends.ts b/apps/ats/web/src/i18n/en/security/dividends.ts index c10b6e049..ba4487705 100644 --- a/apps/ats/web/src/i18n/en/security/dividends.ts +++ b/apps/ats/web/src/i18n/en/security/dividends.ts @@ -55,9 +55,8 @@ export default { details: { title: "Detail", paymentDay: "Payment day", + balance: "Balance", amount: "Amount", - numerator: "Numerator", - denominator: "Denominator", recordDateReached: "Record date reached", }, }, diff --git a/apps/ats/web/src/i18n/en/security/forceRedeem.ts b/apps/ats/web/src/i18n/en/security/forceRedeem.ts index 9f52ba66d..d0b8d6c03 100644 --- a/apps/ats/web/src/i18n/en/security/forceRedeem.ts +++ b/apps/ats/web/src/i18n/en/security/forceRedeem.ts @@ -1,236 +1,36 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ +//SPDX-License-Identifier: Apache-2.0 export default { header: { - title: 'Force redeem digital security', + title: "Force redeem digital security", }, - title: 'Force redeem securities', - subtitle: 'Choose the amount you want to redeem', + title: "Force redeem securities", + subtitle: "Choose the amount you want to redeem", input: { amount: { - label: 'Amount to redeem', - placeholder: 'Enter the amount to redeem', + label: "Amount to redeem", + placeholder: "Enter the amount to redeem", }, source: { - label: 'Add source Account', - placeholder: 'Enter the account', + label: "Add source Account", + placeholder: "Enter the account", }, }, list: { details: { - label: 'Details', + label: "Details", }, }, button: { - accept: 'Redeem', + accept: "Redeem", }, messages: { - success: 'Success: ', - descriptionSuccess: 'The redeem operation has been executed successfully', - error: 'Error: ', - descriptionFailed: 'The redeem operation has failed', + success: "Success: ", + descriptionSuccess: "The redeem operation has been executed successfully", + error: "Error: ", + descriptionFailed: "The redeem operation has failed", + }, + checkbox: { + label: "Select to redeem the full amount after maturity date", }, }; diff --git a/apps/ats/web/src/services/SDKService.ts b/apps/ats/web/src/services/SDKService.ts index e2a5bf65c..cba935964 100644 --- a/apps/ats/web/src/services/SDKService.ts +++ b/apps/ats/web/src/services/SDKService.ts @@ -1,207 +1,4 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ +//SPDX-License-Identifier: Apache-2.0 import { ApplyRolesRequest, @@ -383,15 +180,16 @@ import { IsProceedRecipientRequest, GetProceedRecipientDataRequest, DividendAmountForViewModel, -} from '@hashgraph/asset-tokenization-sdk'; + FullRedeemAtMaturityRequest, +} from "@hashgraph/asset-tokenization-sdk"; export class SDKService { static initData?: InitializationData = undefined; - static testnetNetwork = 'testnet'; + static testnetNetwork = "testnet"; static testnetMirrorNode = { - baseUrl: process.env.REACT_APP_MIRROR_NODE ?? '', - apiKey: '', - headerName: '', + baseUrl: process.env.REACT_APP_MIRROR_NODE ?? "", + apiKey: "", + headerName: "", }; static testnetMirrorNodes = { nodes: [ @@ -402,10 +200,10 @@ export class SDKService { ], }; static testnetRPCNode = { - baseUrl: process.env.REACT_APP_RPC_NODE ?? '', + baseUrl: process.env.REACT_APP_RPC_NODE ?? "", //baseUrl: "http://127.0.0.1:7546", - apiKey: '', - headerName: '', + apiKey: "", + headerName: "", }; static testnetRPCNodes = { nodes: [ @@ -415,8 +213,8 @@ export class SDKService { }, ], }; - static testnetResolverAddress = process.env.REACT_APP_RPC_RESOLVER ?? '0.0.0'; - static testnetFactoryAddress = process.env.REACT_APP_RPC_FACTORY ?? '0.0.0'; + static testnetResolverAddress = process.env.REACT_APP_RPC_RESOLVER ?? "0.0.0"; + static testnetFactoryAddress = process.env.REACT_APP_RPC_FACTORY ?? "0.0.0"; static testnetConfiguration = { factoryAddress: this.testnetFactoryAddress, @@ -446,11 +244,11 @@ export class SDKService { public static async connectWallet(wallet: SupportedWallets) { let hwcSettings; if (wallet === SupportedWallets.HWALLETCONNECT) { - const projectId = process.env.REACT_APP_PROJECT_ID ?? ''; - const dappName = process.env.REACT_APP_DAPP_NAME ?? ''; - const dappDescription = process.env.REACT_APP_DAPP_DESCRIPTION ?? ''; - const dappURL = process.env.REACT_APP_DAPP_URL ?? ''; - const dappIcons = process.env.REACT_APP_DAPP_ICONS?.split(',') ?? []; + const projectId = process.env.REACT_APP_PROJECT_ID ?? ""; + const dappName = process.env.REACT_APP_DAPP_NAME ?? ""; + const dappDescription = process.env.REACT_APP_DAPP_DESCRIPTION ?? ""; + const dappURL = process.env.REACT_APP_DAPP_URL ?? ""; + const dappIcons = process.env.REACT_APP_DAPP_ICONS?.split(",") ?? []; if (projectId) { hwcSettings = { @@ -493,9 +291,9 @@ export class SDKService { return init; } catch (e) { - console.error('Error initializing the Network : ' + e); + console.error("Error initializing the Network : " + e); console.error( - 'There was an error initializing the network, please check your .env file and make sure the configuration is correct', + "There was an error initializing the network, please check your .env file and make sure the configuration is correct", ); } } @@ -504,16 +302,12 @@ export class SDKService { return await Network.disconnect(); } // FACTORY //////////////////////////////////////////// - public static async getRegulationDetails( - req: GetRegulationDetailsRequest, - ): Promise { + public static async getRegulationDetails(req: GetRegulationDetailsRequest): Promise { return await Factory.getRegulationDetails(req); } // SECURITY //////////////////////////////////////////// - public static async getSecurityDetails( - req: GetSecurityDetailsRequest, - ): Promise { + public static async getSecurityDetails(req: GetSecurityDetailsRequest): Promise { return await Security.getInfo(req); } @@ -525,29 +319,21 @@ export class SDKService { return response; } - public static async getEquityDetails( - req: GetEquityDetailsRequest, - ): Promise { + public static async getEquityDetails(req: GetEquityDetailsRequest): Promise { return await Equity.getEquityDetails(req); } // BOND //////////////////////////////////////////// - public static async createBond( - createRequest: CreateBondRequest, - ): Promise<{ security: SecurityViewModel } | null> { + public static async createBond(createRequest: CreateBondRequest): Promise<{ security: SecurityViewModel } | null> { const response = await Bond.create(createRequest); return response; } - public static async getBondDetails( - req: GetBondDetailsRequest, - ): Promise { + public static async getBondDetails(req: GetBondDetailsRequest): Promise { return await Bond.getBondDetails(req); } - public static async updateBondMaturityDate( - req: UpdateMaturityDateRequest, - ): Promise { + public static async updateBondMaturityDate(req: UpdateMaturityDateRequest): Promise { const response = await Bond.updateMaturityDate(req); return response.payload; } @@ -562,66 +348,48 @@ export class SDKService { return await Security.setCompliance(req); } - public static async getIdentityRegistry( - req: IdentityRegistryRequest, - ): Promise { + public static async getIdentityRegistry(req: IdentityRegistryRequest): Promise { return await Security.identityRegistry(req); } - public static async updateIdentityRegistry( - req: SetIdentityRegistryRequest, - ): Promise<{ + public static async updateIdentityRegistry(req: SetIdentityRegistryRequest): Promise<{ payload: boolean; }> { return await Security.setIdentityRegistry(req); } // Proceed Recipients - public static async getProceedRecipientsCount( - req: GetProceedRecipientsCountRequest, - ): Promise { + public static async getProceedRecipientsCount(req: GetProceedRecipientsCountRequest): Promise { const request = await Bond.getProceedRecipientsCount(req); return request.payload; } - public static async getProceedRecipients( - req: GetProceedRecipientsRequest, - ): Promise { + public static async getProceedRecipients(req: GetProceedRecipientsRequest): Promise { const request = await Bond.getProceedRecipients(req); return request.payload; } - public static async getProceedRecipientData( - req: GetProceedRecipientDataRequest, - ): Promise { + public static async getProceedRecipientData(req: GetProceedRecipientDataRequest): Promise { const request = await Bond.getProceedRecipientData(req); return request.payload; } - public static async isProceedRecipient( - req: IsProceedRecipientRequest, - ): Promise { + public static async isProceedRecipient(req: IsProceedRecipientRequest): Promise { const request = await Bond.isProceedRecipient(req); return request.payload; } - public static async addProceedRecipient( - req: AddProceedRecipientRequest, - ): Promise { + public static async addProceedRecipient(req: AddProceedRecipientRequest): Promise { const response = await Bond.addProceedRecipient(req); return response.payload; } - public static async removeProceedRecipient( - req: RemoveProceedRecipientRequest, - ): Promise { + public static async removeProceedRecipient(req: RemoveProceedRecipientRequest): Promise { const response = await Bond.removeProceedRecipient(req); return response.payload; } - public static async updateProceedRecipientData( - req: UpdateProceedRecipientDataRequest, - ): Promise { + public static async updateProceedRecipientData(req: UpdateProceedRecipientDataRequest): Promise { const response = await Bond.updateProceedRecipientData(req); return response.payload; } @@ -632,45 +400,31 @@ export class SDKService { return response.payload; } - public static async getCouponFor( - req: GetCouponForRequest, - ): Promise { + public static async getCouponFor(req: GetCouponForRequest): Promise { return await Bond.getCouponFor(req); } - public static async getCouponAmountFor( - req: GetCouponForRequest, - ): Promise { + public static async getCouponAmountFor(req: GetCouponForRequest): Promise { return await Bond.getCouponAmountFor(req); } - public static async getPrincipalFor( - req: GetPrincipalForRequest, - ): Promise { + public static async getPrincipalFor(req: GetPrincipalForRequest): Promise { return await Bond.getPrincipalFor(req); } - public static async getCoupon( - req: GetCouponRequest, - ): Promise { + public static async getCoupon(req: GetCouponRequest): Promise { return await Bond.getCoupon(req); } - public static async getAllCoupons( - req: GetAllCouponsRequest, - ): Promise { + public static async getAllCoupons(req: GetAllCouponsRequest): Promise { return await Bond.getAllCoupons(req); } - public static async getCouponHolders( - req: GetCouponHoldersRequest, - ): Promise { + public static async getCouponHolders(req: GetCouponHoldersRequest): Promise { return await Bond.getCouponHolders(req); } - public static async getTotalCouponHolders( - req: GetTotalCouponHoldersRequest, - ): Promise { + public static async getTotalCouponHolders(req: GetTotalCouponHoldersRequest): Promise { return await Bond.getTotalCouponHolders(req); } @@ -685,21 +439,15 @@ export class SDKService { return response.payload; } - public static async getRoleMemberCount( - req: GetRoleMemberCountRequest, - ): Promise { + public static async getRoleMemberCount(req: GetRoleMemberCountRequest): Promise { return await Role.getRoleMemberCount(req); } - public static async getRoleMembers( - req: GetRoleMembersRequest, - ): Promise { + public static async getRoleMembers(req: GetRoleMembersRequest): Promise { return await Role.getRoleMembers(req); } - public static async getRoleCountFor( - req: GetRoleCountForRequest, - ): Promise { + public static async getRoleCountFor(req: GetRoleCountForRequest): Promise { return await Role.getRoleCountFor(req); } @@ -713,41 +461,29 @@ export class SDKService { } // CONTROL LIST //////////////////////////////////////////// - public static async addToControlList( - req: ControlListRequest, - ): Promise { + public static async addToControlList(req: ControlListRequest): Promise { const response = await Security.addToControlList(req); return response.payload; } - public static async removeFromControlList( - req: ControlListRequest, - ): Promise { + public static async removeFromControlList(req: ControlListRequest): Promise { const response = await Security.removeFromControlList(req); return response.payload; } - public static async isAccountInControlList( - req: ControlListRequest, - ): Promise { + public static async isAccountInControlList(req: ControlListRequest): Promise { return await Security.isAccountInControlList(req); } - public static async getControlListCount( - req: GetControlListCountRequest, - ): Promise { + public static async getControlListCount(req: GetControlListCountRequest): Promise { return await Security.getControlListCount(req); } - public static async getControlListMembers( - req: GetControlListMembersRequest, - ): Promise { + public static async getControlListMembers(req: GetControlListMembersRequest): Promise { return await Security.getControlListMembers(req); } - public static async getControlListType( - req: GetControlListTypeRequest, - ): Promise { + public static async getControlListType(req: GetControlListTypeRequest): Promise { return await Security.getControlListType(req); } @@ -758,23 +494,17 @@ export class SDKService { } // FREEZE & UNFREEZE //////////////////////////////////////////// - public static async freezePartialTokens( - req: FreezePartialTokensRequest, - ): Promise { + public static async freezePartialTokens(req: FreezePartialTokensRequest): Promise { const response = await Security.freezePartialTokens(req); return response.payload; } - public static async unfreezePartialTokens( - req: UnfreezePartialTokensRequest, - ): Promise { + public static async unfreezePartialTokens(req: UnfreezePartialTokensRequest): Promise { const response = await Security.unfreezePartialTokens(req); return response.payload; } - public static async getFrozenTokens( - req: GetFrozenPartialTokensRequest, - ): Promise { + public static async getFrozenTokens(req: GetFrozenPartialTokensRequest): Promise { const response = await Security.getFrozenPartialTokens(req); return response; } @@ -790,9 +520,7 @@ export class SDKService { return response.payload; } - public static async getBalanceOf( - req: GetAccountBalanceRequest, - ): Promise { + public static async getBalanceOf(req: GetAccountBalanceRequest): Promise { return await Security.getBalanceOf(req); } @@ -802,46 +530,32 @@ export class SDKService { return response.payload; } - public static async getDividendsFor( - req: GetDividendsForRequest, - ): Promise { + public static async getDividendsFor(req: GetDividendsForRequest): Promise { return await Equity.getDividendsFor(req); } - public static async getDividendAmountFor( - req: GetDividendsForRequest, - ): Promise { + public static async getDividendAmountFor(req: GetDividendsForRequest): Promise { return await Equity.getDividendAmountFor(req); } - public static async getDividends( - req: GetDividendsRequest, - ): Promise { + public static async getDividends(req: GetDividendsRequest): Promise { return await Equity.getDividends(req); } - public static async getAllDividends( - req: GetAllDividendsRequest, - ): Promise { + public static async getAllDividends(req: GetAllDividendsRequest): Promise { return await Equity.getAllDividends(req); } - public static async getDividendHolders( - req: GetDividendHoldersRequest, - ): Promise { + public static async getDividendHolders(req: GetDividendHoldersRequest): Promise { return await Equity.getDividendHolders(req); } - public static async getTotalDividendHolders( - req: GetTotalDividendHoldersRequest, - ): Promise { + public static async getTotalDividendHolders(req: GetTotalDividendHoldersRequest): Promise { return await Equity.getTotalDividendHolders(req); } // SPLIT & REVERSE SPLIT //////////////////////////////////////////// - public static async setScheduledBalanceAdjustmentRequest( - req: SetScheduledBalanceAdjustmentRequest, - ): Promise { + public static async setScheduledBalanceAdjustmentRequest(req: SetScheduledBalanceAdjustmentRequest): Promise { const response = await Equity.setScheduledBalanceAdjustment(req); return response.payload; } @@ -859,16 +573,12 @@ export class SDKService { } // CONTROLLER //////////////////////////////////////////// - public static async controllerTransfer( - req: ForceTransferRequest, - ): Promise { + public static async controllerTransfer(req: ForceTransferRequest): Promise { const response = await Security.controllerTransfer(req); return response.payload; } - public static async controllerRedeem( - req: ForceRedeemRequest, - ): Promise { + public static async controllerRedeem(req: ForceRedeemRequest): Promise { const response = await Security.controllerRedeem(req); return response.payload; } @@ -894,47 +604,33 @@ export class SDKService { return response.payload; } - public static async getMaxSupply( - req: GetMaxSupplyRequest, - ): Promise { + public static async getMaxSupply(req: GetMaxSupplyRequest): Promise { return await Security.getMaxSupply(req); } // VOTING RIGHTS //////////////////////////////////////////// - public static async setVotingRights( - req: SetVotingRightsRequest, - ): Promise { + public static async setVotingRights(req: SetVotingRightsRequest): Promise { const response = await Equity.setVotingRights(req); return response.payload; } - public static async getAllVotingRights( - req: GetAllVotingRightsRequest, - ): Promise { + public static async getAllVotingRights(req: GetAllVotingRightsRequest): Promise { return await Equity.getAllVotingRights(req); } - public static async getVotingRightsFor( - req: GetVotingRightsForRequest, - ): Promise { + public static async getVotingRightsFor(req: GetVotingRightsForRequest): Promise { return await Equity.getVotingRightsFor(req); } - public static async getVotingRights( - req: GetVotingRightsRequest, - ): Promise { + public static async getVotingRights(req: GetVotingRightsRequest): Promise { return await Equity.getVotingRights(req); } - public static async getVotingHolders( - req: GetVotingHoldersRequest, - ): Promise { + public static async getVotingHolders(req: GetVotingHoldersRequest): Promise { return await Equity.getVotingHolders(req); } - public static async getTotalVotingHolders( - req: GetTotalVotingHoldersRequest, - ): Promise { + public static async getTotalVotingHolders(req: GetTotalVotingHoldersRequest): Promise { return await Equity.getTotalVotingHolders(req); } @@ -949,9 +645,7 @@ export class SDKService { return response.payload; } - public static async getLockedBalanceOf( - req: GetLockedBalanceRequest, - ): Promise { + public static async getLockedBalanceOf(req: GetLockedBalanceRequest): Promise { return await Security.getLockedBalanceOf(req); } @@ -963,118 +657,84 @@ export class SDKService { return await Security.getLock(req); } - public static async getHoldsId( - req: GetHoldsIdForByPartitionRequest, - ): Promise { + public static async getHoldsId(req: GetHoldsIdForByPartitionRequest): Promise { return await Security.getHoldsIdForByPartition(req); } - public static async getHoldDetails( - req: GetHoldForByPartitionRequest, - ): Promise { + public static async getHoldDetails(req: GetHoldForByPartitionRequest): Promise { return await Security.getHoldForByPartition(req); } - public static async createHoldFromByPartition( - req: CreateHoldFromByPartitionRequest, - ): Promise { + public static async createHoldFromByPartition(req: CreateHoldFromByPartitionRequest): Promise { const response = await Security.createHoldFromByPartition(req); return response.payload; } - public static async controllerCreateHoldByPartition( - req: CreateHoldFromByPartitionRequest, - ): Promise { + public static async controllerCreateHoldByPartition(req: CreateHoldFromByPartitionRequest): Promise { const response = await Security.controllerCreateHoldByPartition(req); return response.payload; } - public static async createHoldByPartition( - req: CreateHoldByPartitionRequest, - ): Promise { + public static async createHoldByPartition(req: CreateHoldByPartitionRequest): Promise { const response = await Security.createHoldByPartition(req); return response.payload; } - public static async reclaimHoldByPartition( - req: ReclaimHoldByPartitionRequest, - ): Promise { + public static async reclaimHoldByPartition(req: ReclaimHoldByPartitionRequest): Promise { const response = await Security.reclaimHoldByPartition(req); return response.payload; } - public static async releaseHoldByPartition( - req: ReleaseHoldByPartitionRequest, - ): Promise { + public static async releaseHoldByPartition(req: ReleaseHoldByPartitionRequest): Promise { const response = await Security.releaseHoldByPartition(req); return response.payload; } - public static async executeHoldByPartition( - req: ExecuteHoldByPartitionRequest, - ): Promise { + public static async executeHoldByPartition(req: ExecuteHoldByPartitionRequest): Promise { const response = await Security.executeHoldByPartition(req); return response.payload; } - public static async getHeldAmountFor( - req: GetHeldAmountForRequest, - ): Promise { + public static async getHeldAmountFor(req: GetHeldAmountForRequest): Promise { const response = await Security.getHeldAmountFor(req); return response; } // MANAGEMENT //////////////////////////////////////////// - public static async getConfigInfo( - req: GetConfigInfoRequest, - ): Promise { + public static async getConfigInfo(req: GetConfigInfoRequest): Promise { return await Management.getConfigInfo(req); } - public static async updateSecurityConfigVersion( - req: UpdateConfigVersionRequest, - ): Promise { + public static async updateSecurityConfigVersion(req: UpdateConfigVersionRequest): Promise { const response = await Management.updateConfigVersion(req); return response.payload; } - public static async updateSecurityConfig( - req: UpdateConfigRequest, - ): Promise { + public static async updateSecurityConfig(req: UpdateConfigRequest): Promise { const response = await Management.updateConfig(req); return response.payload; } - public static async updateSecurityResolver( - req: UpdateResolverRequest, - ): Promise { + public static async updateSecurityResolver(req: UpdateResolverRequest): Promise { const response = await Management.updateResolver(req); return response.payload; } // DID MANAGEMENT //////////////////////////////////////////// - public static async getRevocationRegistryAddress( - req: GetRevocationRegistryAddressRequest, - ): Promise { + public static async getRevocationRegistryAddress(req: GetRevocationRegistryAddressRequest): Promise { return await SsiManagement.getRevocationRegistryAddress(req); } - public static async setRevocationRegistryAddress( - req: SetRevocationRegistryAddressRequest, - ): Promise { + public static async setRevocationRegistryAddress(req: SetRevocationRegistryAddressRequest): Promise { const response = await SsiManagement.setRevocationRegistryAddress(req); return response.payload; } - public static async getIssuerListCount( - req: GetIssuerListCountRequest, - ): Promise { + public static async getIssuerListCount(req: GetIssuerListCountRequest): Promise { return await SsiManagement.getIssuerListCount(req); } - public static async getIssuerListMembers( - req: GetIssuerListMembersRequest, - ): Promise { + public static async getIssuerListMembers(req: GetIssuerListMembersRequest): Promise { return await SsiManagement.getIssuerListMembers(req); } @@ -1097,9 +757,7 @@ export class SDKService { return await Kyc.getKycFor(req); } - public static async getKYCAccountsData( - req: GetKycAccountsDataRequest, - ): Promise { + public static async getKYCAccountsData(req: GetKycAccountsDataRequest): Promise { return await Kyc.getKycAccountsData(req); } @@ -1113,31 +771,23 @@ export class SDKService { return response.payload; } - public static async isInternalKycActivated( - req: IsInternalKycActivatedRequest, - ): Promise { + public static async isInternalKycActivated(req: IsInternalKycActivatedRequest): Promise { const response = await Kyc.isInternalKycActivated(req); return response; } - public static async activateInternalKyc( - req: ActivateInternalKycRequest, - ): Promise { + public static async activateInternalKyc(req: ActivateInternalKycRequest): Promise { const response = await Kyc.activateInternalKyc(req); return response.payload; } - public static async deactivateInternalKyc( - req: DeactivateInternalKycRequest, - ): Promise { + public static async deactivateInternalKyc(req: DeactivateInternalKycRequest): Promise { const response = await Kyc.deactivateInternalKyc(req); return response.payload; } // CLEARING OPERATIONS //////////////////////////////////////////// - public static async getClearingsIdForByPartition( - request: GetClearingsIdForByPartitionRequest, - ): Promise { + public static async getClearingsIdForByPartition(request: GetClearingsIdForByPartitionRequest): Promise { const response = await Security.getClearingsIdForByPartition(request); return response; } @@ -1158,28 +808,21 @@ export class SDKService { public static async getClearingCreateHoldForByPartition( request: GetClearingCreateHoldForByPartitionRequest, ): Promise { - const response = - await Security.getClearingCreateHoldForByPartition(request); + const response = await Security.getClearingCreateHoldForByPartition(request); return response; } - public static async clearingTransferByPartition( - request: ClearingTransferByPartitionRequest, - ): Promise { + public static async clearingTransferByPartition(request: ClearingTransferByPartitionRequest): Promise { const response = await Security.clearingTransferByPartition(request); return response.payload; } - public static async clearingRedeemByPartition( - request: ClearingRedeemByPartitionRequest, - ): Promise { + public static async clearingRedeemByPartition(request: ClearingRedeemByPartitionRequest): Promise { const response = await Security.clearingRedeemByPartition(request); return response.payload; } - public static async clearingCreateHoldByPartition( - request: ClearingCreateHoldByPartitionRequest, - ): Promise { + public static async clearingCreateHoldByPartition(request: ClearingCreateHoldByPartitionRequest): Promise { const response = await Security.clearingCreateHoldByPartition(request); return response.payload; } @@ -1187,8 +830,7 @@ export class SDKService { public static async approveClearingOperationByPartition( request: ApproveClearingOperationByPartitionRequest, ): Promise { - const response = - await Security.approveClearingOperationByPartition(request); + const response = await Security.approveClearingOperationByPartition(request); return response.payload; } @@ -1202,80 +844,58 @@ export class SDKService { public static async reclaimClearingOperationByPartition( request: ReclaimClearingOperationByPartitionRequest, ): Promise { - const response = - await Security.reclaimClearingOperationByPartition(request); + const response = await Security.reclaimClearingOperationByPartition(request); return response.payload; } - public static async activateClearing( - request: ActivateClearingRequest, - ): Promise { + public static async activateClearing(request: ActivateClearingRequest): Promise { const response = await Security.activateClearing(request); return response.payload; } - public static async deactivateClearing( - request: DeactivateClearingRequest, - ): Promise { + public static async deactivateClearing(request: DeactivateClearingRequest): Promise { const response = await Security.deactivateClearing(request); return response.payload; } - public static async isClearingActivated( - request: IsClearingActivatedRequest, - ): Promise { + public static async isClearingActivated(request: IsClearingActivatedRequest): Promise { const response = await Security.isClearingActivated(request); return response; } - public static async getClearedAmountFor( - req: GetClearedAmountForRequest, - ): Promise { + public static async getClearedAmountFor(req: GetClearedAmountForRequest): Promise { const response = await Security.getClearedAmountFor(req); return response; } // EXTERNAL PAUSES ////////////////////////////////////// - public static async addExternalPause( - req: AddExternalPauseRequest, - ): Promise { + public static async addExternalPause(req: AddExternalPauseRequest): Promise { const response = await ExternalPausesManagement.addExternalPause(req); return response.payload; } - public static async removeExternalPause( - req: RemoveExternalPauseRequest, - ): Promise { + public static async removeExternalPause(req: RemoveExternalPauseRequest): Promise { const response = await ExternalPausesManagement.removeExternalPause(req); return response.payload; } - public static async updateExternalPauses( - req: UpdateExternalPausesRequest, - ): Promise { + public static async updateExternalPauses(req: UpdateExternalPausesRequest): Promise { const response = await ExternalPausesManagement.updateExternalPauses(req); return response.payload; } - public static async isExternalPause( - req: IsExternalPauseRequest, - ): Promise { + public static async isExternalPause(req: IsExternalPauseRequest): Promise { const response = await ExternalPausesManagement.isExternalPause(req); return response; } - public static async getExternalPausesCount( - req: GetExternalPausesCountRequest, - ): Promise { + public static async getExternalPausesCount(req: GetExternalPausesCountRequest): Promise { const response = await ExternalPausesManagement.getExternalPausesCount(req); return response; } - public static async getExternalPausesMembers( - req: GetExternalPausesMembersRequest, - ): Promise { - const response = - await ExternalPausesManagement.getExternalPausesMembers(req); + public static async getExternalPausesMembers(req: GetExternalPausesMembersRequest): Promise { + const response = await ExternalPausesManagement.getExternalPausesMembers(req); return response; } @@ -1284,9 +904,7 @@ export class SDKService { return response; } - public static async setPausedMock( - req: SetPausedMockRequest, - ): Promise { + public static async setPausedMock(req: SetPausedMockRequest): Promise { const response = await ExternalPausesManagement.setPausedMock(req); return response.payload; } @@ -1298,110 +916,72 @@ export class SDKService { // External Control public static async createExternalBlackListMock(): Promise { - const response = - await ExternalControlListsManagement.createExternalBlackListMock(); + const response = await ExternalControlListsManagement.createExternalBlackListMock(); return response; } public static async createExternalWhiteListMock(): Promise { - const response = - await ExternalControlListsManagement.createExternalWhiteListMock(); + const response = await ExternalControlListsManagement.createExternalWhiteListMock(); return response; } - public static async addExternalControlList( - req: AddExternalControlListRequest, - ): Promise { - const response = - await ExternalControlListsManagement.addExternalControlList(req); + public static async addExternalControlList(req: AddExternalControlListRequest): Promise { + const response = await ExternalControlListsManagement.addExternalControlList(req); return response.payload; } - public static async addToBlackListMock( - req: AddToBlackListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.addToBlackListMock(req); + public static async addToBlackListMock(req: AddToBlackListMockRequest): Promise { + const response = await ExternalControlListsManagement.addToBlackListMock(req); return response.payload; } - public static async addToWhiteListMock( - req: AddToWhiteListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.addToWhiteListMock(req); + public static async addToWhiteListMock(req: AddToWhiteListMockRequest): Promise { + const response = await ExternalControlListsManagement.addToWhiteListMock(req); return response.payload; } - public static async removeExternalControlList( - req: RemoveExternalControlListRequest, - ): Promise { - const response = - await ExternalControlListsManagement.removeExternalControlList(req); + public static async removeExternalControlList(req: RemoveExternalControlListRequest): Promise { + const response = await ExternalControlListsManagement.removeExternalControlList(req); return response.payload; } - public static async removeFromBlackListMock( - req: RemoveFromBlackListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.removeFromBlackListMock(req); + public static async removeFromBlackListMock(req: RemoveFromBlackListMockRequest): Promise { + const response = await ExternalControlListsManagement.removeFromBlackListMock(req); return response.payload; } - public static async removeFromWhiteListMock( - req: RemoveFromWhiteListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.removeFromWhiteListMock(req); + public static async removeFromWhiteListMock(req: RemoveFromWhiteListMockRequest): Promise { + const response = await ExternalControlListsManagement.removeFromWhiteListMock(req); return response.payload; } - public static async updateExternalControlLists( - req: UpdateExternalControlListsRequest, - ): Promise { - const response = - await ExternalControlListsManagement.updateExternalControlLists(req); + public static async updateExternalControlLists(req: UpdateExternalControlListsRequest): Promise { + const response = await ExternalControlListsManagement.updateExternalControlLists(req); return response.payload; } - public static async getExternalControlListsCount( - req: GetExternalControlListsCountRequest, - ): Promise { - const response = - await ExternalControlListsManagement.getExternalControlListsCount(req); + public static async getExternalControlListsCount(req: GetExternalControlListsCountRequest): Promise { + const response = await ExternalControlListsManagement.getExternalControlListsCount(req); return response; } - public static async getExternalControlListsMembers( - req: GetExternalControlListsMembersRequest, - ): Promise { - const response = - await ExternalControlListsManagement.getExternalControlListsMembers(req); + public static async getExternalControlListsMembers(req: GetExternalControlListsMembersRequest): Promise { + const response = await ExternalControlListsManagement.getExternalControlListsMembers(req); return response; } - public static async isExternalControlList( - req: IsExternalControlListRequest, - ): Promise { - const response = - await ExternalControlListsManagement.isExternalControlList(req); + public static async isExternalControlList(req: IsExternalControlListRequest): Promise { + const response = await ExternalControlListsManagement.isExternalControlList(req); return response; } - public static async isAuthorizedBlackListMock( - req: IsAuthorizedBlackListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.isAuthorizedBlackListMock(req); + public static async isAuthorizedBlackListMock(req: IsAuthorizedBlackListMockRequest): Promise { + const response = await ExternalControlListsManagement.isAuthorizedBlackListMock(req); return response; } - public static async isAuthorizedWhiteListMock( - req: IsAuthorizedWhiteListMockRequest, - ): Promise { - const response = - await ExternalControlListsManagement.isAuthorizedWhiteListMock(req); + public static async isAuthorizedWhiteListMock(req: IsAuthorizedWhiteListMockRequest): Promise { + const response = await ExternalControlListsManagement.isAuthorizedWhiteListMock(req); return response; } @@ -1411,9 +991,7 @@ export class SDKService { return response; } - public static async addExternalKycList( - req: AddExternalKycListRequest, - ): Promise { + public static async addExternalKycList(req: AddExternalKycListRequest): Promise { const response = await ExternalKycListsManagement.addExternalKycList(req); return response.payload; } @@ -1423,65 +1001,50 @@ export class SDKService { return response.payload; } - public static async revokeKycMock( - req: RevokeKycMockRequest, - ): Promise { + public static async revokeKycMock(req: RevokeKycMockRequest): Promise { const response = await ExternalKycListsManagement.revokeKycMock(req); return response.payload; } - public static async removeExternalKycList( - req: RemoveExternalKycListRequest, - ): Promise { - const response = - await ExternalKycListsManagement.removeExternalKycList(req); + public static async removeExternalKycList(req: RemoveExternalKycListRequest): Promise { + const response = await ExternalKycListsManagement.removeExternalKycList(req); return response.payload; } - public static async updateExternalKycLists( - req: UpdateExternalKycListsRequest, - ): Promise { - const response = - await ExternalKycListsManagement.updateExternalKycLists(req); + public static async updateExternalKycLists(req: UpdateExternalKycListsRequest): Promise { + const response = await ExternalKycListsManagement.updateExternalKycLists(req); return response.payload; } - public static async getExternalKycListsCount( - req: GetExternalKycListsCountRequest, - ): Promise { - const response = - await ExternalKycListsManagement.getExternalKycListsCount(req); + public static async getExternalKycListsCount(req: GetExternalKycListsCountRequest): Promise { + const response = await ExternalKycListsManagement.getExternalKycListsCount(req); return response; } - public static async getExternalKycListsMembers( - req: GetExternalKycListsMembersRequest, - ): Promise { - const response = - await ExternalKycListsManagement.getExternalKycListsMembers(req); + public static async getExternalKycListsMembers(req: GetExternalKycListsMembersRequest): Promise { + const response = await ExternalKycListsManagement.getExternalKycListsMembers(req); return response; } - public static async getKycStatusMock( - req: GetKycStatusMockRequest, - ): Promise { + public static async getKycStatusMock(req: GetKycStatusMockRequest): Promise { const response = await ExternalKycListsManagement.getKycStatusMock(req); return response; } - public static async isExternalKycList( - req: IsExternalKycListRequest, - ): Promise { + public static async isExternalKycList(req: IsExternalKycListRequest): Promise { const response = await ExternalKycListsManagement.isExternalKycList(req); return response; } - public static async isExternallyKycGranted( - req: IsExternallyGrantedRequest, - ): Promise { + public static async isExternallyKycGranted(req: IsExternallyGrantedRequest): Promise { const response = await ExternalKycListsManagement.isExternallyGranted(req); return response; } + + public static async fullRedeemAtMaturity(req: FullRedeemAtMaturityRequest): Promise { + const response = await Bond.fullRedeemAtMaturity(req); + return response.payload; + } } export default SDKService; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/SeeCoupon.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/SeeCoupon.tsx index 35e7f168e..eb55bc2c5 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/SeeCoupon.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/SeeCoupon.tsx @@ -18,7 +18,7 @@ import { GetCouponForRequest, GetCouponRequest } from "@hashgraph/asset-tokeniza import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { useGetCoupons, useGetCouponsFor, useGetCouponsAmountFor } from "../../../../hooks/queries/useCoupons"; -import { formatDate, formatCouponPeriod } from "../../../../utils/format"; +import { formatDate, formatNumberLocale } from "../../../../utils/format"; import { DATE_TIME_FORMAT } from "../../../../utils/constants"; interface SeeCouponFormValues { @@ -165,6 +165,15 @@ export const SeeCoupon = () => { setCouponAmountForRequest(couponsAmountForReq); }; + const calculateAmount = () => { + const numerator = Number(couponsAmountFor?.numerator) || 0; + const denominator = Number(couponsAmountFor?.denominator) || 0; + if (numerator === 0 || denominator === 0) { + return "0"; + } + return `${formatNumberLocale(numerator / denominator, 3)} $`; + }; + return (
@@ -218,34 +227,22 @@ export const SeeCoupon = () => { valueToCopy: coupons.executionDate.toDateString(), }, { - title: tDetail("period"), - description: formatCouponPeriod(coupons.period), + title: tDetail("balance"), + description: formatNumberLocale(couponsFor.tokenBalance, parseFloat(couponsFor.decimals)), canCopy: true, - valueToCopy: coupons.period.toString(), + valueToCopy: formatNumberLocale(couponsFor.tokenBalance, parseFloat(couponsFor.decimals)), }, { title: tDetail("amount"), - description: couponsFor.value, - canCopy: true, - valueToCopy: couponsFor.value, - }, - { - title: tDetail("numerator"), - description: couponsAmountFor?.numerator || "0", - canCopy: true, - valueToCopy: couponsAmountFor?.numerator || "0", - }, - { - title: tDetail("denominator"), - description: couponsAmountFor?.denominator || "0", + description: calculateAmount(), canCopy: true, - valueToCopy: couponsAmountFor?.denominator || "0", + valueToCopy: calculateAmount(), }, { title: tDetail("recordDateReached"), - description: couponsAmountFor?.recordDateReached?.toString() || "false", + description: couponsAmountFor?.recordDateReached ? "Yes" : "No", canCopy: true, - valueToCopy: couponsAmountFor?.recordDateReached?.toString() || "false", + valueToCopy: couponsAmountFor?.recordDateReached ? "Yes" : "No", }, ]} title={tDetail("title")} diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/__tests__/SeeCoupon.test.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/__tests__/SeeCoupon.test.tsx index c800aac95..1fd522159 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/__tests__/SeeCoupon.test.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Coupons/__tests__/SeeCoupon.test.tsx @@ -27,17 +27,17 @@ const defaultHookResponse = { }; const mockCouponsForData = { - value: "100.50", + tokenBalance: "10050", + decimals: "2", }; const mockCouponsData = { executionDate: new Date("2024-06-15T10:00:00Z"), - period: 30, }; const mockCouponsAmountForData = { numerator: "150", - denominator: "1000", + denominator: "100", recordDateReached: true, }; @@ -146,17 +146,79 @@ describe(`${SeeCoupon.name}`, () => { render(); await waitFor(() => { - // Verify amount from couponsFor + // Verify balance from couponsFor.value expect(screen.getByText("100.50")).toBeInTheDocument(); - // Verify numerator from couponsAmountFor - expect(screen.getByText("150")).toBeInTheDocument(); - - // Verify denominator from couponsAmountFor - expect(screen.getByText("1000")).toBeInTheDocument(); + // Verify amount calculated as numerator/denominator (150/100 = 1.500 $) + expect(screen.getByText("1.500 $")).toBeInTheDocument(); // Verify recordDateReached from couponsAmountFor - expect(screen.getByText("true")).toBeInTheDocument(); + expect(screen.getByText("Yes")).toBeInTheDocument(); + }); + }); + + test("should display 0 for amount when numerator is 0", async () => { + mockUseGetCouponsFor.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsForData, + refetch: mockRefetchCouponsFor, + }); + + mockUseGetCoupons.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsData, + refetch: mockRefetchCoupons, + }); + + mockUseGetCouponsAmountFor.mockReturnValue({ + ...defaultHookResponse, + data: { + numerator: "0", + denominator: "100", + recordDateReached: true, + }, + refetch: mockRefetchCouponsAmountFor, + }); + + render(); + + await waitFor(() => { + // Amount should be "0" when numerator is 0 + const zeroElements = screen.getAllByText("0"); + expect(zeroElements.length).toBeGreaterThanOrEqual(1); + }); + }); + + test("should display 0 for amount when denominator is 0", async () => { + mockUseGetCouponsFor.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsForData, + refetch: mockRefetchCouponsFor, + }); + + mockUseGetCoupons.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsData, + refetch: mockRefetchCoupons, + }); + + mockUseGetCouponsAmountFor.mockReturnValue({ + ...defaultHookResponse, + data: { + numerator: "100", + denominator: "0", + recordDateReached: false, + }, + refetch: mockRefetchCouponsAmountFor, + }); + + render(); + + await waitFor(() => { + // Amount should be "0" when denominator is 0 + const zeroElements = screen.getAllByText("0"); + expect(zeroElements.length).toBeGreaterThanOrEqual(1); + expect(screen.getByText("No")).toBeInTheDocument(); }); }); @@ -186,15 +248,15 @@ describe(`${SeeCoupon.name}`, () => { render(); await waitFor(() => { - // Verify default values are displayed + // Amount should be "0" when numerator/denominator are undefined const zeroElements = screen.getAllByText("0"); - expect(zeroElements.length).toBeGreaterThanOrEqual(2); + expect(zeroElements.length).toBeGreaterThanOrEqual(1); - expect(screen.getByText("false")).toBeInTheDocument(); + expect(screen.getByText("No")).toBeInTheDocument(); }); }); - test("should display recordDateReached as false when it is false", async () => { + test("should display recordDateReached as No when it is false", async () => { mockUseGetCouponsFor.mockReturnValue({ ...defaultHookResponse, data: mockCouponsForData, @@ -210,8 +272,8 @@ describe(`${SeeCoupon.name}`, () => { mockUseGetCouponsAmountFor.mockReturnValue({ ...defaultHookResponse, data: { - numerator: "50", - denominator: "500", + numerator: "500", + denominator: "100", recordDateReached: false, }, refetch: mockRefetchCouponsAmountFor, @@ -220,17 +282,17 @@ describe(`${SeeCoupon.name}`, () => { render(); await waitFor(() => { - expect(screen.getByText("50")).toBeInTheDocument(); - expect(screen.getByText("500")).toBeInTheDocument(); - expect(screen.getByText("false")).toBeInTheDocument(); + // Verify amount calculated as 500/100 = 5.000 + expect(screen.getByText("5.000 $")).toBeInTheDocument(); + expect(screen.getByText("No")).toBeInTheDocument(); }); }); test("should not display details when data is not loaded", () => { render(); - expect(screen.queryByText(/numerator/i)).not.toBeInTheDocument(); - expect(screen.queryByText(/denominator/i)).not.toBeInTheDocument(); + expect(screen.queryByText(/balance/i)).not.toBeInTheDocument(); + expect(screen.queryByText(/amount/i)).not.toBeInTheDocument(); expect(screen.queryByText(/recordDateReached/i)).not.toBeInTheDocument(); }); @@ -261,4 +323,35 @@ describe(`${SeeCoupon.name}`, () => { expect(submitButton).toBeDisabled(); }); }); + + test("should calculate amount with 3 decimal places", async () => { + mockUseGetCouponsFor.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsForData, + refetch: mockRefetchCouponsFor, + }); + + mockUseGetCoupons.mockReturnValue({ + ...defaultHookResponse, + data: mockCouponsData, + refetch: mockRefetchCoupons, + }); + + mockUseGetCouponsAmountFor.mockReturnValue({ + ...defaultHookResponse, + data: { + numerator: "1", + denominator: "3", + recordDateReached: true, + }, + refetch: mockRefetchCouponsAmountFor, + }); + + render(); + + await waitFor(() => { + // 1/3 = 0.333... should be formatted to 0.333 $ + expect(screen.getByText("0.333 $")).toBeInTheDocument(); + }); + }); }); diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/SeeDividend.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/SeeDividend.tsx index 51c6cb6f5..f90f3525c 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/SeeDividend.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/SeeDividend.tsx @@ -169,15 +169,16 @@ export const SeeDividend = () => { setDividendsAmountForRequest(dividendsAmountForReq); }; - let dividendsPaymentDay = ""; - let dividendsAmount = "0"; + let dividendsPaymentDay = dividends?.executionDate?.toDateString() || ""; - if (dividends && dividendsFor) { - dividendsPaymentDay = dividends.executionDate.toDateString(); - const amount = (parseFloat(dividends.amountPerUnitOfSecurity) * parseFloat(dividendsFor.tokenBalance)).toString(); - - dividendsAmount = `${formatNumberLocale(amount, parseFloat(dividendsFor.decimals))} $`; - } + const calculateAmount = () => { + const numerator = Number(dividendsAmountFor?.numerator) || 0; + const denominator = Number(dividendsAmountFor?.denominator) || 0; + if (numerator === 0 || denominator === 0) { + return "0"; + } + return `${formatNumberLocale(numerator / denominator, 3)} $`; + }; return (
@@ -232,22 +233,16 @@ export const SeeDividend = () => { valueToCopy: dividendsPaymentDay, }, { - title: tDetail("amount"), - description: dividendsAmount, - canCopy: true, - valueToCopy: dividendsAmount, - }, - { - title: tDetail("numerator"), - description: dividendsAmountFor?.numerator, + title: tDetail("balance"), + description: formatNumberLocale(dividendsFor.tokenBalance, parseFloat(dividendsFor.decimals)), canCopy: true, - valueToCopy: dividendsAmountFor?.numerator, + valueToCopy: formatNumberLocale(dividendsFor.tokenBalance, parseFloat(dividendsFor.decimals)), }, { - title: tDetail("denominator"), - description: dividendsAmountFor?.denominator, + title: tDetail("amount"), + description: calculateAmount(), canCopy: true, - valueToCopy: dividendsAmountFor?.denominator, + valueToCopy: calculateAmount(), }, { title: tDetail("recordDateReached"), diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/__tests__/SeeDividend.test.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/__tests__/SeeDividend.test.tsx index 767da69da..3ac7f669c 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/__tests__/SeeDividend.test.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Dividends/__tests__/SeeDividend.test.tsx @@ -31,7 +31,7 @@ const defaultHookResponse = { }; const mockDividendsForData = { - tokenBalance: "100", + tokenBalance: "10000", decimals: "2", }; @@ -42,7 +42,7 @@ const mockDividendsData = { const mockDividendsAmountForData = { numerator: "150", - denominator: "1000", + denominator: "100", recordDateReached: true, }; @@ -151,11 +151,11 @@ describe(`${SeeDividend.name}`, () => { render(); await waitFor(() => { - // Verify numerator from dividendsAmountFor - expect(screen.getByText("150")).toBeInTheDocument(); + // Verify balance from dividendsFor (tokenBalance: "10000", decimals: "2" -> 100.00) + expect(screen.getByText("100.00")).toBeInTheDocument(); - // Verify denominator from dividendsAmountFor - expect(screen.getByText("1000")).toBeInTheDocument(); + // Verify amount calculated as numerator/denominator (150/100 = 1.500 $) + expect(screen.getByText("1.500 $")).toBeInTheDocument(); // Verify recordDateReached from dividendsAmountFor (displays "Yes") expect(screen.getByText("Yes")).toBeInTheDocument(); @@ -178,8 +178,8 @@ describe(`${SeeDividend.name}`, () => { mockUseGetDividendsAmountFor.mockReturnValue({ ...defaultHookResponse, data: { - numerator: "50", - denominator: "500", + numerator: "500", + denominator: "100", recordDateReached: false, }, refetch: mockRefetchDividendsAmountFor, @@ -188,8 +188,73 @@ describe(`${SeeDividend.name}`, () => { render(); await waitFor(() => { - expect(screen.getByText("50")).toBeInTheDocument(); - expect(screen.getByText("500")).toBeInTheDocument(); + // Verify amount calculated as 500/100 = 5.000 $ + expect(screen.getByText("5.000 $")).toBeInTheDocument(); + expect(screen.getByText("No")).toBeInTheDocument(); + }); + }); + + test("should display 0 for amount when numerator is 0", async () => { + mockUseGetDividendsFor.mockReturnValue({ + ...defaultHookResponse, + data: mockDividendsForData, + refetch: mockRefetchDividendsFor, + }); + + mockUseGetDividends.mockReturnValue({ + ...defaultHookResponse, + data: mockDividendsData, + refetch: mockRefetchDividends, + }); + + mockUseGetDividendsAmountFor.mockReturnValue({ + ...defaultHookResponse, + data: { + numerator: "0", + denominator: "100", + recordDateReached: true, + }, + refetch: mockRefetchDividendsAmountFor, + }); + + render(); + + await waitFor(() => { + // Amount should be "0" when numerator is 0 + const zeroElements = screen.getAllByText("0"); + expect(zeroElements.length).toBeGreaterThanOrEqual(1); + }); + }); + + test("should display 0 for amount when denominator is 0", async () => { + mockUseGetDividendsFor.mockReturnValue({ + ...defaultHookResponse, + data: mockDividendsForData, + refetch: mockRefetchDividendsFor, + }); + + mockUseGetDividends.mockReturnValue({ + ...defaultHookResponse, + data: mockDividendsData, + refetch: mockRefetchDividends, + }); + + mockUseGetDividendsAmountFor.mockReturnValue({ + ...defaultHookResponse, + data: { + numerator: "100", + denominator: "0", + recordDateReached: false, + }, + refetch: mockRefetchDividendsAmountFor, + }); + + render(); + + await waitFor(() => { + // Amount should be "0" when denominator is 0 + const zeroElements = screen.getAllByText("0"); + expect(zeroElements.length).toBeGreaterThanOrEqual(1); expect(screen.getByText("No")).toBeInTheDocument(); }); }); @@ -197,8 +262,8 @@ describe(`${SeeDividend.name}`, () => { test("should not display details when data is not loaded", () => { render(); - expect(screen.queryByText(/numerator/i)).not.toBeInTheDocument(); - expect(screen.queryByText(/denominator/i)).not.toBeInTheDocument(); + expect(screen.queryByText(/balance/i)).not.toBeInTheDocument(); + expect(screen.queryByText(/amount/i)).not.toBeInTheDocument(); expect(screen.queryByText(/recordDateReached/i)).not.toBeInTheDocument(); }); @@ -218,7 +283,7 @@ describe(`${SeeDividend.name}`, () => { render(); // Details should not be visible without dividendsFor - expect(screen.queryByText("150")).not.toBeInTheDocument(); + expect(screen.queryByText("1.500 $")).not.toBeInTheDocument(); }); test("should not display details when dividends is missing", () => { @@ -237,7 +302,7 @@ describe(`${SeeDividend.name}`, () => { render(); // Details should not be visible without dividends - expect(screen.queryByText("150")).not.toBeInTheDocument(); + expect(screen.queryByText("1.500 $")).not.toBeInTheDocument(); }); test("should not display details when dividendsAmountFor is missing", () => { @@ -256,7 +321,7 @@ describe(`${SeeDividend.name}`, () => { render(); // Details should not be visible without dividendsAmountFor - expect(screen.queryByText("150")).not.toBeInTheDocument(); + expect(screen.queryByText("1.500 $")).not.toBeInTheDocument(); }); test("should validate dividendId with min value of 0", async () => { @@ -309,36 +374,34 @@ describe(`${SeeDividend.name}`, () => { }); }); - test("should calculate and display correct dividend amount", async () => { + test("should calculate amount with 3 decimal places", async () => { mockUseGetDividendsFor.mockReturnValue({ ...defaultHookResponse, - data: { - tokenBalance: "100", - decimals: "2", - }, + data: mockDividendsForData, refetch: mockRefetchDividendsFor, }); mockUseGetDividends.mockReturnValue({ ...defaultHookResponse, - data: { - executionDate: new Date("2024-06-15T10:00:00Z"), - amountPerUnitOfSecurity: "1.5", - }, + data: mockDividendsData, refetch: mockRefetchDividends, }); mockUseGetDividendsAmountFor.mockReturnValue({ ...defaultHookResponse, - data: mockDividendsAmountForData, + data: { + numerator: "1", + denominator: "3", + recordDateReached: true, + }, refetch: mockRefetchDividendsAmountFor, }); render(); await waitFor(() => { - // Amount = tokenBalance * amountPerUnitOfSecurity = 100 * 1.5 = 150 - expect(screen.getByText(/150/)).toBeInTheDocument(); + // 1/3 = 0.333... should be formatted to 0.333 $ + expect(screen.getByText("0.333 $")).toBeInTheDocument(); }); }); }); diff --git a/apps/ats/web/src/views/DigitalSecurityForceRedeem/DigitalSecurityForceRedeem.tsx b/apps/ats/web/src/views/DigitalSecurityForceRedeem/DigitalSecurityForceRedeem.tsx index d1d3de31f..46a66c601 100644 --- a/apps/ats/web/src/views/DigitalSecurityForceRedeem/DigitalSecurityForceRedeem.tsx +++ b/apps/ats/web/src/views/DigitalSecurityForceRedeem/DigitalSecurityForceRedeem.tsx @@ -1,250 +1,49 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { HStack, Stack, VStack } from '@chakra-ui/react'; -import { History } from '../../components/History'; -import { useTranslation } from 'react-i18next'; -import { - Text, - InputController, - InputNumberController, - Button, -} from 'io-bricks-ui'; -import { SubmitHandler, useForm } from 'react-hook-form'; -import { required, min } from '../../utils/rules'; -import { CancelButton } from '../../components/CancelButton'; -import { useParams } from 'react-router'; -import { ForceRedeemRequest } from '@hashgraph/asset-tokenization-sdk'; -import { useForceRedeemSecurity } from '../../hooks/queries/useForceRedeemSecurity'; -import { DetailsBalancePanel } from '../../components/DetailsBalancePanel'; -import { useWalletStore } from '../../store/walletStore'; -import { useDetailsBalancePanel } from '../../hooks/useDetailsBalancePanel'; -import { useSecurityStore } from '../../store/securityStore'; +//SPDX-License-Identifier: Apache-2.0 + +import { HStack, Stack, VStack } from "@chakra-ui/react"; +import { History } from "../../components/History"; +import { useTranslation } from "react-i18next"; +import { Text, InputController, InputNumberController, Button, Checkbox } from "io-bricks-ui"; +import { SubmitHandler, useForm } from "react-hook-form"; +import { required, min } from "../../utils/rules"; +import { CancelButton } from "../../components/CancelButton"; +import { useParams } from "react-router"; +import { ForceRedeemRequest, FullRedeemAtMaturityRequest } from "@hashgraph/asset-tokenization-sdk"; +import { useForceRedeemSecurity } from "../../hooks/queries/useForceRedeemSecurity"; +import { useFullRedeemAtMaturity } from "../../hooks/queries/useFullRedeemAtMaturity"; +import { DetailsBalancePanel } from "../../components/DetailsBalancePanel"; +import { useWalletStore } from "../../store/walletStore"; +import { useDetailsBalancePanel } from "../../hooks/useDetailsBalancePanel"; +import { useSecurityStore } from "../../store/securityStore"; interface ForceRedeemFormValues { source: string; amount: number; + fullRedeem: boolean; } export const DigitalSecurityForceRedeem = () => { - const { t: tHeader } = useTranslation('security', { - keyPrefix: 'forceRedeem.header', + const { t: tHeader } = useTranslation("security", { + keyPrefix: "forceRedeem.header", + }); + const { t: tForm } = useTranslation("security", { + keyPrefix: "forceRedeem.input", }); - const { t: tForm } = useTranslation('security', { - keyPrefix: 'forceRedeem.input', + const { t } = useTranslation("security", { keyPrefix: "forceRedeem" }); + const { t: tGlobal } = useTranslation("globals"); + const { control, handleSubmit, reset, watch } = useForm({ + mode: "all", + defaultValues: { + fullRedeem: false, + }, + }); + const { t: TButton } = useTranslation("security", { + keyPrefix: "forceRedeem.button", }); - const { t } = useTranslation('security', { keyPrefix: 'forceRedeem' }); - const { t: tGlobal } = useTranslation('globals'); - const { control, formState, handleSubmit, reset } = - useForm({ - mode: 'all', - }); - const { t: TButton } = useTranslation('security', { - keyPrefix: 'forceRedeem.button', + const { t: TCheckbox } = useTranslation("security", { + keyPrefix: "forceRedeem.checkbox", }); - const { id = '' } = useParams(); + const { id = "" } = useParams(); const { details } = useSecurityStore(); const { address: walletAddress } = useWalletStore(); @@ -261,27 +60,40 @@ export const DigitalSecurityForceRedeem = () => { }, }); - const submit: SubmitHandler = (params) => { - const request = new ForceRedeemRequest({ - securityId: id, - sourceId: params.source, - amount: params.amount.toString(), - }); + const { mutate: fullRedeemAtMaturity, isLoading: isLoadingFullRedeem } = useFullRedeemAtMaturity({ + onSettled: () => update(), + onSuccess: () => { + reset(); + }, + }); + + const isFullRedeem = watch("fullRedeem"); + const sourceValue = watch("source"); + const amountValue = watch("amount"); - forceRedeemSecurity(request); + const submit: SubmitHandler = (params) => { + if (params.fullRedeem) { + const request = new FullRedeemAtMaturityRequest({ + securityId: id, + sourceId: params.source, + }); + fullRedeemAtMaturity(request); + } else { + const request = new ForceRedeemRequest({ + securityId: id, + sourceId: params.source, + amount: params.amount.toString(), + }); + forceRedeemSecurity(request); + } }; + const isFormValid = !!sourceValue && (isFullRedeem || !!amountValue); + return ( <> - - + + { as="form" onSubmit={handleSubmit(submit)} > - {t('title')} + {t("title")} - {t('subtitle')} + {t("subtitle")} - {tGlobal('mandatoryFields')} + {tGlobal("mandatoryFields")} { control={control} id="source" rules={{ required }} - label={tForm('source.label')} - placeholder={tForm('source.placeholder')} + label={tForm("source.label")} + placeholder={tForm("source.placeholder")} size="md" /> - + + { + const checked = e.target.checked; + reset({ ...watch(), fullRedeem: checked, amount: checked ? 0 : watch("amount") }); + }} + > + {TCheckbox("label")} + + + - + ); diff --git a/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/DigitalSecurityForceRedeem.test.tsx b/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/DigitalSecurityForceRedeem.test.tsx index 8a50bd9ba..b1c5f81d7 100644 --- a/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/DigitalSecurityForceRedeem.test.tsx +++ b/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/DigitalSecurityForceRedeem.test.tsx @@ -1,240 +1,175 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { DigitalSecurityForceRedeem } from '../DigitalSecurityForceRedeem'; -import { render } from '../../../test-utils'; +//SPDX-License-Identifier: Apache-2.0 + +import { DigitalSecurityForceRedeem } from "../DigitalSecurityForceRedeem"; +import { render } from "../../../test-utils"; +import { screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; + +const SOURCE_PLACEHOLDER = "Enter the account"; +const AMOUNT_PLACEHOLDER = "Enter the amount to redeem"; describe(`${DigitalSecurityForceRedeem.name}`, () => { const factoryComponent = () => { return render(); }; - test('render correctly', () => { + test("render correctly", () => { const component = factoryComponent(); expect(component.asFragment()).toMatchSnapshot(); }); - test('should show Goback button', () => { + test("should show Goback button", () => { const component = factoryComponent(); - const breadcrumbs = component.getByTestId('go-back-button'); + const breadcrumbs = component.getByTestId("go-back-button"); expect(breadcrumbs).toBeInTheDocument(); }); - test('should show breadcrumbs', () => { + test("should show breadcrumbs", () => { const component = factoryComponent(); - const breadcrumbs = component.getByTestId('breadcrumb-desktop'); + const breadcrumbs = component.getByTestId("breadcrumb-desktop"); expect(breadcrumbs).toBeInTheDocument(); }); - test('should form be rendered properly', () => { + test("should form be rendered properly", () => { const component = factoryComponent(); - const form = component.getByTestId('force-redeem-form'); + const form = component.getByTestId("force-redeem-form"); expect(form).toBeInTheDocument(); }); + + test("should render fullRedeem checkbox", () => { + factoryComponent(); + + const checkbox = screen.getByRole("checkbox"); + expect(checkbox).toBeInTheDocument(); + expect(checkbox).not.toBeChecked(); + }); + + test("should redeem button be disabled when form is empty", () => { + factoryComponent(); + + const redeemButton = screen.getByTestId("redeem-security-button"); + expect(redeemButton).toBeDisabled(); + }); + + test("should redeem button be disabled when only source is filled", async () => { + factoryComponent(); + + const sourceInput = screen.getByPlaceholderText(SOURCE_PLACEHOLDER); + await userEvent.type(sourceInput, "0x1234567890abcdef"); + + const redeemButton = screen.getByTestId("redeem-security-button"); + expect(redeemButton).toBeDisabled(); + }); + + test("should redeem button be enabled when source and amount are filled", async () => { + factoryComponent(); + + const sourceInput = screen.getByPlaceholderText(SOURCE_PLACEHOLDER); + await userEvent.type(sourceInput, "0x1234567890abcdef"); + + const amountInput = screen.getByPlaceholderText(AMOUNT_PLACEHOLDER); + await userEvent.type(amountInput, "100"); + + await waitFor(() => { + const redeemButton = screen.getByTestId("redeem-security-button"); + expect(redeemButton).toBeEnabled(); + }); + }); + + test("should redeem button be enabled when source is filled and fullRedeem is checked", async () => { + factoryComponent(); + + const sourceInput = screen.getByPlaceholderText(SOURCE_PLACEHOLDER); + await userEvent.type(sourceInput, "0x1234567890abcdef"); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + + await waitFor(() => { + const redeemButton = screen.getByTestId("redeem-security-button"); + expect(redeemButton).toBeEnabled(); + }); + }); + + test("should disable amount input when fullRedeem is checked", async () => { + factoryComponent(); + + const amountInput = screen.getByPlaceholderText(AMOUNT_PLACEHOLDER); + expect(amountInput).toBeEnabled(); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + + await waitFor(() => { + expect(amountInput).toBeDisabled(); + }); + }); + + test("should enable amount input when fullRedeem is unchecked", async () => { + factoryComponent(); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + + const amountInput = screen.getByPlaceholderText(AMOUNT_PLACEHOLDER); + await waitFor(() => { + expect(amountInput).toBeDisabled(); + }); + + await userEvent.click(checkbox); + await waitFor(() => { + expect(amountInput).toBeEnabled(); + }); + }); + + test("should redeem button be disabled when fullRedeem is checked but source is empty", async () => { + factoryComponent(); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + + const redeemButton = screen.getByTestId("redeem-security-button"); + expect(redeemButton).toBeDisabled(); + }); + + test("should clear amount when fullRedeem is checked and unchecked", async () => { + factoryComponent(); + + const amountInput = screen.getByPlaceholderText(AMOUNT_PLACEHOLDER); + await userEvent.type(amountInput, "100"); + + expect(amountInput).toHaveValue("100"); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + await userEvent.click(checkbox); + + await waitFor(() => { + expect(amountInput).toHaveValue(""); + }); + }); + + test("should keep source value when toggling fullRedeem checkbox", async () => { + factoryComponent(); + + const sourceInput = screen.getByPlaceholderText(SOURCE_PLACEHOLDER); + await userEvent.type(sourceInput, "0x1234567890abcdef"); + + const checkbox = screen.getByRole("checkbox"); + await userEvent.click(checkbox); + + await waitFor(() => { + expect(sourceInput).toHaveValue("0x1234567890abcdef"); + }); + + await userEvent.click(checkbox); + + await waitFor(() => { + expect(sourceInput).toHaveValue("0x1234567890abcdef"); + }); + }); }); diff --git a/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/__snapshots__/DigitalSecurityForceRedeem.test.tsx.snap b/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/__snapshots__/DigitalSecurityForceRedeem.test.tsx.snap index 1ae30c3ac..9d1969286 100644 --- a/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/__snapshots__/DigitalSecurityForceRedeem.test.tsx.snap +++ b/apps/ats/web/src/views/DigitalSecurityForceRedeem/__tests__/__snapshots__/DigitalSecurityForceRedeem.test.tsx.snap @@ -152,6 +152,34 @@ exports[`DigitalSecurityForceRedeem render correctly 1`] = ` +
+ +
diff --git a/apps/ats/web/src/views/DigitalSecurityRedeem/DigitalSecurityRedeem.tsx b/apps/ats/web/src/views/DigitalSecurityRedeem/DigitalSecurityRedeem.tsx index 46fbefac1..15767be34 100644 --- a/apps/ats/web/src/views/DigitalSecurityRedeem/DigitalSecurityRedeem.tsx +++ b/apps/ats/web/src/views/DigitalSecurityRedeem/DigitalSecurityRedeem.tsx @@ -1,250 +1,47 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { HStack, Stack, VStack } from '@chakra-ui/react'; -import { History } from '../../components/History'; -import { useTranslation } from 'react-i18next'; -import { Text, InputNumberController, Button } from 'io-bricks-ui'; -import { SubmitHandler, useForm } from 'react-hook-form'; -import { required, min } from '../../utils/rules'; -import { CancelButton } from '../../components/CancelButton'; -import { useParams } from 'react-router'; -import { useRedeemSecurity } from '../../hooks/queries/useRedeemSecurity'; -import { RedeemRequest } from '@hashgraph/asset-tokenization-sdk'; -import { DetailsBalancePanel } from '../../components/DetailsBalancePanel'; -import { useDetailsBalancePanel } from '../../hooks/useDetailsBalancePanel'; -import { useWalletStore } from '../../store/walletStore'; -import { useSecurityStore } from '../../store/securityStore'; +//SPDX-License-Identifier: Apache-2.0 + +import { HStack, Stack, VStack } from "@chakra-ui/react"; +import { History } from "../../components/History"; +import { useTranslation } from "react-i18next"; +import { Text, InputNumberController, Button } from "io-bricks-ui"; +import { SubmitHandler, useForm } from "react-hook-form"; +import { required, min } from "../../utils/rules"; +import { CancelButton } from "../../components/CancelButton"; +import { useParams } from "react-router"; +import { useRedeemSecurity } from "../../hooks/queries/useRedeemSecurity"; +import { RedeemRequest } from "@hashgraph/asset-tokenization-sdk"; +import { DetailsBalancePanel } from "../../components/DetailsBalancePanel"; +import { useDetailsBalancePanel } from "../../hooks/useDetailsBalancePanel"; +import { useWalletStore } from "../../store/walletStore"; +import { useSecurityStore } from "../../store/securityStore"; interface RedeemFormValues { amount: number; } export const DigitalSecurityRedeem = () => { - const { t: tHeader } = useTranslation('security', { - keyPrefix: 'redeem.header', + const { t: tHeader } = useTranslation("security", { + keyPrefix: "redeem.header", }); - const { t: tForm } = useTranslation('security', { - keyPrefix: 'redeem.input', + const { t: tForm } = useTranslation("security", { + keyPrefix: "redeem.input", }); - const { t } = useTranslation('security', { keyPrefix: 'redeem' }); - const { t: tGlobal } = useTranslation('globals'); - const { control, formState, handleSubmit, reset } = useForm( - { - mode: 'all', - }, - ); - const { t: TButton } = useTranslation('security', { - keyPrefix: 'redeem.button', + const { t } = useTranslation("security", { keyPrefix: "redeem" }); + const { t: tGlobal } = useTranslation("globals"); + const { control, formState, handleSubmit, reset } = useForm({ + mode: "all", }); - const { id = '' } = useParams(); + const { t: TButton } = useTranslation("security", { + keyPrefix: "redeem.button", + }); + const { id = "" } = useParams(); const { details } = useSecurityStore(); const { address: walletAddress } = useWalletStore(); - const { currentAvailableBalance, isCurrentAvailableBalanceLoading, update } = - useDetailsBalancePanel(id, walletAddress); + const { currentAvailableBalance, isCurrentAvailableBalanceLoading, update } = useDetailsBalancePanel( + id, + walletAddress, + ); const { mutate: redeemSecurity, isLoading } = useRedeemSecurity({ onSettled: () => update(), @@ -264,15 +61,8 @@ export const DigitalSecurityRedeem = () => { return ( <> - - + + { as="form" onSubmit={handleSubmit(submit)} > - {t('title')} + {t("title")} - {t('subtitle')} + {t("subtitle")} - {tGlobal('mandatoryFields')} + {tGlobal("mandatoryFields")} { }} size="md" allowNegative={false} - label={tForm('amount.label')} - placeholder={tForm('amount.placeholder')} + label={tForm("amount.label")} + placeholder={tForm("amount.placeholder")} decimalScale={details?.decimals} fixedDecimalScale={true} thousandSeparator="," decimalSeparator="." /> - + - + ); diff --git a/packages/ats/sdk/__tests__/port/in/Bond.test.ts b/packages/ats/sdk/__tests__/port/in/Bond.test.ts index bb542ef25..ceeddd450 100644 --- a/packages/ats/sdk/__tests__/port/in/Bond.test.ts +++ b/packages/ats/sdk/__tests__/port/in/Bond.test.ts @@ -1,209 +1,6 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import '../environmentMock'; +//SPDX-License-Identifier: Apache-2.0 + +import "../environmentMock"; import { SDK, LoggerTransports, @@ -219,65 +16,60 @@ import { RoleRequest, SetCouponRequest, UpdateMaturityDateRequest, -} from '@port/in'; -import { - CLIENT_ACCOUNT_ECDSA, - FACTORY_ADDRESS, - RESOLVER_ADDRESS, -} from '@test/config'; -import { TIME_PERIODS_S } from '@core/Constants'; -import ConnectRequest from '@port/in/request/network/ConnectRequest'; -import { MirrorNode } from '@domain/context/network/MirrorNode'; -import { JsonRpcRelay } from '@domain/context/network/JsonRpcRelay'; -import NetworkService from '@service/network/NetworkService'; -import SecurityViewModel from '@port/in/response/SecurityViewModel'; -import Injectable from '@core/injectable/Injectable'; -import { SecurityRole } from '@domain/context/security/SecurityRole'; +} from "@port/in"; +import { CLIENT_ACCOUNT_ECDSA, FACTORY_ADDRESS, RESOLVER_ADDRESS } from "@test/config"; +import { TIME_PERIODS_S } from "@core/Constants"; +import ConnectRequest from "@port/in/request/network/ConnectRequest"; +import { MirrorNode } from "@domain/context/network/MirrorNode"; +import { JsonRpcRelay } from "@domain/context/network/JsonRpcRelay"; +import NetworkService from "@service/network/NetworkService"; +import SecurityViewModel from "@port/in/response/SecurityViewModel"; +import Injectable from "@core/injectable/Injectable"; +import { SecurityRole } from "@domain/context/security/SecurityRole"; import { CastRegulationSubType, CastRegulationType, RegulationSubType, RegulationType, -} from '@domain/context/factory/RegulationType'; -import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; -import { MirrorNodeAdapter } from '@port/out/mirror/MirrorNodeAdapter'; -import { RPCTransactionAdapter } from '@port/out/rpc/RPCTransactionAdapter'; -import { Wallet, ethers } from 'ethers'; -import BaseError from '@core/error/BaseError'; +} from "@domain/context/factory/RegulationType"; +import { RPCQueryAdapter } from "@port/out/rpc/RPCQueryAdapter"; +import { MirrorNodeAdapter } from "@port/out/mirror/MirrorNodeAdapter"; +import { RPCTransactionAdapter } from "@port/out/rpc/RPCTransactionAdapter"; +import { Wallet, ethers } from "ethers"; +import BaseError from "@core/error/BaseError"; -SDK.log = { level: 'ERROR', transports: new LoggerTransports.Console() }; +SDK.log = { level: "ERROR", transports: new LoggerTransports.Console() }; const decimals = 0; -const name = 'TEST_SECURITY_TOKEN'; -const symbol = 'TEST'; -const isin = 'ABCDE123456Z'; -const currency = '0x455552'; +const name = "TEST_SECURITY_TOKEN"; +const symbol = "TEST"; +const isin = "ABCDE123456Z"; +const currency = "0x455552"; const TIME = 30; -const numberOfUnits = '1000'; -const nominalValue = '100'; +const numberOfUnits = "1000"; +const nominalValue = "100"; const nominalValueDecimals = 3; const currentTimeInSeconds = Math.floor(new Date().getTime() / 1000) + 1000; const startingDate = currentTimeInSeconds + TIME; const maturityDate = startingDate + 365; // 1 year maturity const regulationType = RegulationType.REG_S; const regulationSubType = RegulationSubType.NONE; -const countries = 'AF,HG,BN'; -const info = 'Anything'; -const configId = - '0x0000000000000000000000000000000000000000000000000000000000000000'; +const countries = "AF,HG,BN"; +const info = "Anything"; +const configId = "0x0000000000000000000000000000000000000000000000000000000000000000"; const configVersion = 0; const mirrorNode: MirrorNode = { - name: 'testmirrorNode', - baseUrl: 'https://testnet.mirrornode.hedera.com/api/v1/', + name: "testmirrorNode", + baseUrl: "https://testnet.mirrornode.hedera.com/api/v1/", }; const rpcNode: JsonRpcRelay = { - name: 'testrpcNode', - baseUrl: 'http://127.0.0.1:7546/api', + name: "testrpcNode", + baseUrl: "http://127.0.0.1:7546/api", }; -describe('🧪 Bond test', () => { +describe("🧪 Bond test", () => { let th: RPCTransactionAdapter; let ns: NetworkService; let mirrorNodeAdapter: MirrorNodeAdapter; @@ -293,7 +85,7 @@ describe('🧪 Bond test', () => { rpcQueryAdapter = Injectable.resolve(RPCQueryAdapter); rpcQueryAdapter.init(); - ns.environment = 'testnet'; + ns.environment = "testnet"; ns.configuration = { factoryAddress: FACTORY_ADDRESS, resolverAddress: RESOLVER_ADDRESS, @@ -304,15 +96,10 @@ describe('🧪 Bond test', () => { await th.init(true); //await th.register(undefined, true); - const url = 'http://127.0.0.1:7546'; + const url = "http://127.0.0.1:7546"; const customHttpProvider = new ethers.providers.JsonRpcProvider(url); - th.setSignerOrProvider( - new Wallet( - CLIENT_ACCOUNT_ECDSA.privateKey?.key ?? '', - customHttpProvider, - ), - ); + th.setSignerOrProvider(new Wallet(CLIENT_ACCOUNT_ECDSA.privateKey?.key ?? "", customHttpProvider)); await Network.connect( new ConnectRequest({ @@ -320,7 +107,7 @@ describe('🧪 Bond test', () => { accountId: CLIENT_ACCOUNT_ECDSA.id.toString(), privateKey: CLIENT_ACCOUNT_ECDSA.privateKey, }, - network: 'testnet', + network: "testnet", wallet: SupportedWallets.METAMASK, mirrorNode: mirrorNode, rpcNode: rpcNode, @@ -360,10 +147,10 @@ describe('🧪 Bond test', () => { bond = (await Bond.create(requestST)).security; - console.log('bond: ' + JSON.stringify(bond)); + console.log("bond: " + JSON.stringify(bond)); }, 600_000); - it('Check Bond Details', async () => { + it("Check Bond Details", async () => { const bondDetails = await Bond.getBondDetails( new GetBondDetailsRequest({ bondId: bond.evmDiamondAddress!.toString(), @@ -377,9 +164,9 @@ describe('🧪 Bond test', () => { expect(bondDetails.maturityDate.getTime() / 1000).toEqual(maturityDate); }, 60_000); - it('Coupons Fixed', async () => { + it("Coupons Fixed", async () => { // Manually create a coupon since automatic creation was removed - const couponRate = '3'; + const couponRate = "3"; const couponRecordDate = startingDate + 30; const couponExecutionDate = startingDate + 35; @@ -427,14 +214,15 @@ describe('🧪 Bond test', () => { expect(coupon.couponId).toEqual(1); expect(coupon.recordDate.getTime() / 1000).toEqual(couponRecordDate); expect(coupon.executionDate.getTime() / 1000).toEqual(couponExecutionDate); - expect(couponFor.value).toEqual('0'); + expect(couponFor.tokenBalance).toEqual("0"); + expect(couponFor.decimals).toEqual("0"); expect(allCoupon.length).toEqual(1); // Now only 1 manually created coupon - expect(couponAmountFor.numerator).toEqual('5'); - expect(couponAmountFor.denominator).toEqual('3'); + expect(couponAmountFor.numerator).toEqual("5"); + expect(couponAmountFor.denominator).toEqual("3"); expect(couponAmountFor.recordDateReached).toEqual(true); }, 600_000); - it('Coupons Custom', async () => { + it("Coupons Custom", async () => { await Role.grantRole( new RoleRequest({ securityId: bond.evmDiamondAddress!.toString(), @@ -443,7 +231,7 @@ describe('🧪 Bond test', () => { }), ); - const rate = '1'; + const rate = "1"; const recordTimestamp = Math.ceil(new Date().getTime() / 1000) + 1000; const executionTimestamp = recordTimestamp + 1000; @@ -469,7 +257,7 @@ describe('🧪 Bond test', () => { expect(coupon.executionDate.getTime() / 1000).toEqual(executionTimestamp); }, 600_000); - it('Update bond maturity date correctly', async () => { + it("Update bond maturity date correctly", async () => { const newMaturityDate = maturityDate + 10; const request = new UpdateMaturityDateRequest({ securityId: bond.evmDiamondAddress!.toString(), @@ -487,7 +275,7 @@ describe('🧪 Bond test', () => { expect(res.payload).toBe(true); }, 600_000); - it('Should return error if bond maturity date is earlier than current one', async () => { + it("Should return error if bond maturity date is earlier than current one", async () => { const newMaturityDate = maturityDate - 10; const request = new UpdateMaturityDateRequest({ securityId: bond.evmDiamondAddress!.toString(), diff --git a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQuery.ts b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQuery.ts index 67c14b1e6..6985fe195 100644 --- a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQuery.ts +++ b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQuery.ts @@ -203,12 +203,15 @@ */ -import { Query } from '@core/query/Query'; -import { QueryResponse } from '@core/query/QueryResponse'; -import BigDecimal from '@domain/context/shared/BigDecimal'; +import { Query } from "@core/query/Query"; +import { QueryResponse } from "@core/query/QueryResponse"; +import BigDecimal from "@domain/context/shared/BigDecimal"; export class GetCouponForQueryResponse implements QueryResponse { - constructor(public readonly payload: BigDecimal) {} + constructor( + public readonly tokenBalance: BigDecimal, + public readonly decimals: number, + ) {} } export class GetCouponForQuery extends Query { diff --git a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.ts b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.ts index 05b8efba3..ffb7c2bd4 100644 --- a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.ts +++ b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.ts @@ -1,226 +1,17 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { IQueryHandler } from '@core/query/QueryHandler'; -import { QueryHandler } from '@core/decorator/QueryHandlerDecorator'; -import { lazyInject } from '@core/decorator/LazyInjectDecorator'; -import { - GetCouponForQuery, - GetCouponForQueryResponse, -} from './GetCouponForQuery'; -import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; -import BigDecimal from '@domain/context/shared/BigDecimal'; -import ContractService from '@service/contract/ContractService'; -import EvmAddress from '@domain/context/contract/EvmAddress'; -import AccountService from '@service/account/AccountService'; -import { GetCouponForQueryError } from './error/GetCouponForQueryError'; +//SPDX-License-Identifier: Apache-2.0 + +import { IQueryHandler } from "@core/query/QueryHandler"; +import { QueryHandler } from "@core/decorator/QueryHandlerDecorator"; +import { lazyInject } from "@core/decorator/LazyInjectDecorator"; +import { GetCouponForQuery, GetCouponForQueryResponse } from "./GetCouponForQuery"; +import { RPCQueryAdapter } from "@port/out/rpc/RPCQueryAdapter"; +import ContractService from "@service/contract/ContractService"; +import EvmAddress from "@domain/context/contract/EvmAddress"; +import AccountService from "@service/account/AccountService"; +import { GetCouponForQueryError } from "./error/GetCouponForQueryError"; @QueryHandler(GetCouponForQuery) -export class GetCouponForQueryHandler - implements IQueryHandler -{ +export class GetCouponForQueryHandler implements IQueryHandler { constructor( @lazyInject(RPCQueryAdapter) private readonly queryAdapter: RPCQueryAdapter, @@ -234,18 +25,12 @@ export class GetCouponForQueryHandler try { const { targetId, securityId, couponId } = query; - const securityEvmAddress: EvmAddress = - await this.contractService.getContractEvmAddress(securityId); - const targetEvmAddress: EvmAddress = - await this.accountService.getAccountEvmAddress(targetId); + const securityEvmAddress: EvmAddress = await this.contractService.getContractEvmAddress(securityId); + const targetEvmAddress: EvmAddress = await this.accountService.getAccountEvmAddress(targetId); - const res = await this.queryAdapter.getCouponFor( - securityEvmAddress, - targetEvmAddress, - couponId, - ); + const res = await this.queryAdapter.getCouponFor(securityEvmAddress, targetEvmAddress, couponId); - return new GetCouponForQueryResponse(new BigDecimal(res)); + return new GetCouponForQueryResponse(res.tokenBalance || "0", res.decimals); } catch (error) { throw new GetCouponForQueryError(error as Error); } diff --git a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.unit.test.ts index 25c4bd13e..0a2c948cb 100644 --- a/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.unit.test.ts +++ b/packages/ats/sdk/src/app/usecase/query/bond/coupons/getCouponFor/GetCouponForQueryHandler.unit.test.ts @@ -1,229 +1,19 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { createMock } from '@golevelup/ts-jest'; -import { - ErrorMsgFixture, - EvmAddressPropsFixture, -} from '@test/fixtures/shared/DataFixture'; -import { ErrorCode } from '@core/error/BaseError'; -import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; -import ContractService from '@service/contract/ContractService'; -import EvmAddress from '@domain/context/contract/EvmAddress'; -import { GetCouponForQueryFixture } from '@test/fixtures/bond/BondFixture'; -import { GetCouponForQueryError } from './error/GetCouponForQueryError'; -import { GetCouponForQueryHandler } from './GetCouponForQueryHandler'; -import AccountService from '@service/account/AccountService'; -import { BigNumber } from 'ethers'; -import BigDecimal from '@domain/context/shared/BigDecimal'; -import { - GetCouponForQuery, - GetCouponForQueryResponse, -} from './GetCouponForQuery'; - -describe('GetCouponForQueryHandler', () => { +//SPDX-License-Identifier: Apache-2.0 + +import { createMock } from "@golevelup/ts-jest"; +import { ErrorMsgFixture, EvmAddressPropsFixture } from "@test/fixtures/shared/DataFixture"; +import { ErrorCode } from "@core/error/BaseError"; +import { RPCQueryAdapter } from "@port/out/rpc/RPCQueryAdapter"; +import ContractService from "@service/contract/ContractService"; +import EvmAddress from "@domain/context/contract/EvmAddress"; +import { GetCouponForQueryFixture } from "@test/fixtures/bond/BondFixture"; +import { GetCouponForQueryError } from "./error/GetCouponForQueryError"; +import { GetCouponForQueryHandler } from "./GetCouponForQueryHandler"; +import AccountService from "@service/account/AccountService"; +import BigDecimal from "@domain/context/shared/BigDecimal"; +import { GetCouponForQuery, GetCouponForQueryResponse } from "./GetCouponForQuery"; + +describe("GetCouponForQueryHandler", () => { let handler: GetCouponForQueryHandler; let query: GetCouponForQuery; @@ -232,19 +22,14 @@ describe('GetCouponForQueryHandler', () => { const accountServiceMock = createMock(); const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); - const targetEvmAddress = new EvmAddress( - EvmAddressPropsFixture.create().value, - ); + const targetEvmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); const errorMsg = ErrorMsgFixture.create().msg; - const amount = BigNumber.from(1); + const amount = new BigDecimal("1000000"); + const decimals = 6; beforeEach(() => { - handler = new GetCouponForQueryHandler( - queryAdapterServiceMock, - accountServiceMock, - contractServiceMock, - ); + handler = new GetCouponForQueryHandler(queryAdapterServiceMock, accountServiceMock, contractServiceMock); query = GetCouponForQueryFixture.create(); }); @@ -252,53 +37,36 @@ describe('GetCouponForQueryHandler', () => { jest.resetAllMocks(); }); - describe('execute', () => { - it('throws GetCouponForQueryError when query fails with uncaught error', async () => { + describe("execute", () => { + it("throws GetCouponForQueryError when query fails with uncaught error", async () => { const fakeError = new Error(errorMsg); contractServiceMock.getContractEvmAddress.mockRejectedValue(fakeError); const resultPromise = handler.execute(query); - await expect(resultPromise).rejects.toBeInstanceOf( - GetCouponForQueryError, - ); + await expect(resultPromise).rejects.toBeInstanceOf(GetCouponForQueryError); await expect(resultPromise).rejects.toMatchObject({ - message: expect.stringContaining( - `An error occurred while querying account's coupon: ${errorMsg}`, - ), + message: expect.stringContaining(`An error occurred while querying account's coupon: ${errorMsg}`), errorCode: ErrorCode.UncaughtQueryError, }); }); - it('should successfully get coupon for', async () => { - contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( - evmAddress, - ); - accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( - targetEvmAddress, - ); - queryAdapterServiceMock.getCouponFor.mockResolvedValue(amount); + it("should successfully get coupon for", async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce(evmAddress); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce(targetEvmAddress); + queryAdapterServiceMock.getCouponFor.mockResolvedValue({ tokenBalance: amount, decimals: decimals }); const result = await handler.execute(query); expect(result).toBeInstanceOf(GetCouponForQueryResponse); - expect(result.payload).toStrictEqual(new BigDecimal(amount)); - expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( - 1, - ); + expect(result.tokenBalance).toStrictEqual(amount); + expect(result.decimals).toStrictEqual(decimals); + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes(1); expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); - expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith( - query.securityId, - ); - expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledWith( - query.targetId, - ); - expect(queryAdapterServiceMock.getCouponFor).toHaveBeenCalledWith( - evmAddress, - targetEvmAddress, - query.couponId, - ); + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith(query.securityId); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledWith(query.targetId); + expect(queryAdapterServiceMock.getCouponFor).toHaveBeenCalledWith(evmAddress, targetEvmAddress, query.couponId); }); }); }); diff --git a/packages/ats/sdk/src/core/injectable/bond/InjectableBond.ts b/packages/ats/sdk/src/core/injectable/bond/InjectableBond.ts index ddcce2f03..a5368b472 100644 --- a/packages/ats/sdk/src/core/injectable/bond/InjectableBond.ts +++ b/packages/ats/sdk/src/core/injectable/bond/InjectableBond.ts @@ -1,221 +1,19 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { TOKENS } from '../Tokens'; -import { GetCouponForQueryHandler } from '@query/bond/coupons/getCouponFor/GetCouponForQueryHandler'; -import { GetCouponAmountForQueryHandler } from '@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQueryHandler'; -import { GetPrincipalForQueryHandler } from '@query/bond/get/getPrincipalFor/GetPrincipalForQueryHandler'; -import { GetCouponQueryHandler } from '@query/bond/coupons/getCoupon/GetCouponQueryHandler'; -import { GetCouponCountQueryHandler } from '@query/bond/coupons/getCouponCount/GetCouponCountQueryHandler'; -import { UpdateMaturityDateCommandHandler } from '@command/bond/updateMaturityDate/UpdateMaturityDateCommandHandler'; -import { SetCouponCommandHandler } from '@command/bond/coupon/set/SetCouponCommandHandler'; -import { CreateBondCommandHandler } from '@command/bond/create/CreateBondCommandHandler'; -import { GetBondDetailsQueryHandler } from '@query/bond/get/getBondDetails/GetBondDetailsQueryHandler'; -import { RedeemAtMaturityByPartitionCommandHandler } from '@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommandHandler'; -import { GetTotalCouponHoldersQueryHandler } from '@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQueryHandler'; -import { GetCouponHoldersQueryHandler } from '@query/bond/coupons/getCouponHolders/GetCouponHoldersQueryHandler'; +//SPDX-License-Identifier: Apache-2.0 + +import { TOKENS } from "../Tokens"; +import { GetCouponForQueryHandler } from "@query/bond/coupons/getCouponFor/GetCouponForQueryHandler"; +import { GetCouponAmountForQueryHandler } from "@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQueryHandler"; +import { GetPrincipalForQueryHandler } from "@query/bond/get/getPrincipalFor/GetPrincipalForQueryHandler"; +import { GetCouponQueryHandler } from "@query/bond/coupons/getCoupon/GetCouponQueryHandler"; +import { GetCouponCountQueryHandler } from "@query/bond/coupons/getCouponCount/GetCouponCountQueryHandler"; +import { UpdateMaturityDateCommandHandler } from "@command/bond/updateMaturityDate/UpdateMaturityDateCommandHandler"; +import { SetCouponCommandHandler } from "@command/bond/coupon/set/SetCouponCommandHandler"; +import { CreateBondCommandHandler } from "@command/bond/create/CreateBondCommandHandler"; +import { GetBondDetailsQueryHandler } from "@query/bond/get/getBondDetails/GetBondDetailsQueryHandler"; +import { RedeemAtMaturityByPartitionCommandHandler } from "@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommandHandler"; +import { GetTotalCouponHoldersQueryHandler } from "@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQueryHandler"; +import { GetCouponHoldersQueryHandler } from "@query/bond/coupons/getCouponHolders/GetCouponHoldersQueryHandler"; +import { FullRedeemAtMaturityCommandHandler } from "@command/bond/fullRedeemAtMaturity/FullRedeemAtMaturityCommandHandler"; export const COMMAND_HANDLERS_BOND = [ { @@ -234,6 +32,10 @@ export const COMMAND_HANDLERS_BOND = [ token: TOKENS.COMMAND_HANDLER, useClass: RedeemAtMaturityByPartitionCommandHandler, }, + { + token: TOKENS.COMMAND_HANDLER, + useClass: FullRedeemAtMaturityCommandHandler, + }, ]; export const QUERY_HANDLERS_BOND = [ diff --git a/packages/ats/sdk/src/domain/context/bond/CouponFor.ts b/packages/ats/sdk/src/domain/context/bond/CouponFor.ts new file mode 100644 index 000000000..a144f36dc --- /dev/null +++ b/packages/ats/sdk/src/domain/context/bond/CouponFor.ts @@ -0,0 +1,12 @@ +//SPDX-License-Identifier: Apache-2.0 + +import BigDecimal from "../shared/BigDecimal"; + +export class CouponFor { + tokenBalance: BigDecimal; + decimals: number; + constructor(tokenBalance: BigDecimal, decimals: number) { + this.tokenBalance = tokenBalance; + this.decimals = decimals; + } +} diff --git a/packages/ats/sdk/src/port/in/bond/Bond.ts b/packages/ats/sdk/src/port/in/bond/Bond.ts index b00a12271..8cce5c0f8 100644 --- a/packages/ats/sdk/src/port/in/bond/Bond.ts +++ b/packages/ats/sdk/src/port/in/bond/Bond.ts @@ -1,146 +1,108 @@ // SPDX-License-Identifier: Apache-2.0 -import { GetBondDetailsQuery } from '@query/bond/get/getBondDetails/GetBondDetailsQuery'; -import Injectable from '@core/injectable/Injectable'; -import { LogError } from '@core/decorator/LogErrorDecorator'; -import { QueryBus } from '@core/query/QueryBus'; -import ValidatedRequest from '@core/validation/ValidatedArgs'; - -import GetBondDetailsRequest from '../request/bond/GetBondDetailsRequest'; -import BondDetailsViewModel from '../response/BondDetailsViewModel'; -import CouponViewModel from '../response/CouponViewModel'; -import CouponForViewModel from '../response/CouponForViewModel'; -import CouponAmountForViewModel from '../response/CouponAmountForViewModel'; -import PrincipalForViewModel from '../response/PrincipalForViewModel'; -import GetAllCouponsRequest from '../request/bond/GetAllCouponsRequest'; -import GetCouponForRequest from '../request/bond/GetCouponForRequest'; -import GetPrincipalForRequest from '../request/bond/GetPrincipalForRequest'; -import GetCouponRequest from '../request/bond/GetCouponRequest'; -import { GetCouponForQuery } from '@query/bond/coupons/getCouponFor/GetCouponForQuery'; -import { GetCouponAmountForQuery } from '@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQuery'; -import { GetPrincipalForQuery } from '@query/bond/get/getPrincipalFor/GetPrincipalForQuery'; -import { GetCouponQuery } from '@query/bond/coupons/getCoupon/GetCouponQuery'; -import { GetCouponCountQuery } from '@query/bond/coupons/getCouponCount/GetCouponCountQuery'; -import { ONE_THOUSAND } from '@domain/context/shared/SecurityDate'; -import CreateBondRequest from '../request/bond/CreateBondRequest'; -import { SecurityViewModel } from '../security/Security'; -import { CommandBus } from '@core/command/CommandBus'; -import NetworkService from '@service/network/NetworkService'; -import { SecurityProps } from '@domain/context/security/Security'; -import { CreateBondCommand } from '@command/bond/create/CreateBondCommand'; -import ContractId from '@domain/context/contract/ContractId'; -import { GetSecurityQuery } from '@query/security/get/GetSecurityQuery'; -import BigDecimal from '@domain/context/shared/BigDecimal'; -import SetCouponRequest from '../request/bond/SetCouponRequest'; -import { SetCouponCommand } from '@command/bond/coupon/set/SetCouponCommand'; -import { - CastRegulationSubType, - CastRegulationType, -} from '@domain/context/factory/RegulationType'; -import UpdateMaturityDateRequest from '../request/bond/UpdateMaturityDateRequest'; -import { UpdateMaturityDateCommand } from '@command/bond/updateMaturityDate/UpdateMaturityDateCommand'; -import { RedeemAtMaturityByPartitionCommand } from '@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommand'; -import { FullRedeemAtMaturityCommand } from '@command/bond/fullRedeemAtMaturity/FullRedeemAtMaturityCommand'; -import RedeemAtMaturityByPartitionRequest from '../request/bond/RedeemAtMaturityByPartitionRequest'; -import FullRedeemAtMaturityRequest from '../request/bond/FullRedeemAtMaturityRequest'; -import { GetCouponHoldersQuery } from '@query/bond/coupons/getCouponHolders/GetCouponHoldersQuery'; -import { GetTotalCouponHoldersQuery } from '@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQuery'; -import CreateTrexSuiteBondRequest from '../request/bond/CreateTrexSuiteBondRequest'; -import { CreateTrexSuiteBondCommand } from '@command/bond/createTrexSuite/CreateTrexSuiteBondCommand'; -import AddProceedRecipientRequest from '../request/bond/AddProceedRecipientRequest'; -import RemoveProceedRecipientRequest from '../request/bond/RemoveProceedRecipientRequest'; -import UpdateProceedRecipientDataRequest from '../request/bond/UpdateProceedRecipientDataRequest'; -import { UpdateProceedRecipientDataCommand } from '@command/security/proceedRecipients/updateProceedRecipientData/UpdateProceedRecipientDataCommand'; -import { RemoveProceedRecipientCommand } from '@command/security/proceedRecipients/removeProceedRecipient/RemoveProceedRecipientCommand'; -import { AddProceedRecipientCommand } from '@command/security/proceedRecipients/addProceedRecipient/AddProceedRecipientCommand'; -import IsProceedRecipientRequest from '../request/bond/IsProceedRecipientRequest'; -import { GetProceedRecipientsQuery } from '@query/security/proceedRecipient/getProceedRecipients/GetProceedRecipientsQuery'; -import { GetProceedRecipientsCountQuery } from '@query/security/proceedRecipient/getProceedRecipientsCount/GetProceedRecipientsCountQuery'; -import { GetProceedRecipientDataQuery } from '@query/security/proceedRecipient/getProceedRecipientData/GetProceedRecipientDataQuery'; -import { IsProceedRecipientQuery } from '@query/security/proceedRecipient/isProceedRecipient/IsProceedRecipientQuery'; +import { GetBondDetailsQuery } from "@query/bond/get/getBondDetails/GetBondDetailsQuery"; +import Injectable from "@core/injectable/Injectable"; +import { LogError } from "@core/decorator/LogErrorDecorator"; +import { QueryBus } from "@core/query/QueryBus"; +import ValidatedRequest from "@core/validation/ValidatedArgs"; + +import GetBondDetailsRequest from "../request/bond/GetBondDetailsRequest"; +import BondDetailsViewModel from "../response/BondDetailsViewModel"; +import CouponViewModel from "../response/CouponViewModel"; +import CouponForViewModel from "../response/CouponForViewModel"; +import CouponAmountForViewModel from "../response/CouponAmountForViewModel"; +import PrincipalForViewModel from "../response/PrincipalForViewModel"; +import GetAllCouponsRequest from "../request/bond/GetAllCouponsRequest"; +import GetCouponForRequest from "../request/bond/GetCouponForRequest"; +import GetPrincipalForRequest from "../request/bond/GetPrincipalForRequest"; +import GetCouponRequest from "../request/bond/GetCouponRequest"; +import { GetCouponForQuery } from "@query/bond/coupons/getCouponFor/GetCouponForQuery"; +import { GetCouponAmountForQuery } from "@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQuery"; +import { GetPrincipalForQuery } from "@query/bond/get/getPrincipalFor/GetPrincipalForQuery"; +import { GetCouponQuery } from "@query/bond/coupons/getCoupon/GetCouponQuery"; +import { GetCouponCountQuery } from "@query/bond/coupons/getCouponCount/GetCouponCountQuery"; +import { ONE_THOUSAND } from "@domain/context/shared/SecurityDate"; +import CreateBondRequest from "../request/bond/CreateBondRequest"; +import { SecurityViewModel } from "../security/Security"; +import { CommandBus } from "@core/command/CommandBus"; +import NetworkService from "@service/network/NetworkService"; +import { SecurityProps } from "@domain/context/security/Security"; +import { CreateBondCommand } from "@command/bond/create/CreateBondCommand"; +import ContractId from "@domain/context/contract/ContractId"; +import { GetSecurityQuery } from "@query/security/get/GetSecurityQuery"; +import BigDecimal from "@domain/context/shared/BigDecimal"; +import SetCouponRequest from "../request/bond/SetCouponRequest"; +import { SetCouponCommand } from "@command/bond/coupon/set/SetCouponCommand"; +import { CastRegulationSubType, CastRegulationType } from "@domain/context/factory/RegulationType"; +import UpdateMaturityDateRequest from "../request/bond/UpdateMaturityDateRequest"; +import { UpdateMaturityDateCommand } from "@command/bond/updateMaturityDate/UpdateMaturityDateCommand"; +import { RedeemAtMaturityByPartitionCommand } from "@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommand"; +import { FullRedeemAtMaturityCommand } from "@command/bond/fullRedeemAtMaturity/FullRedeemAtMaturityCommand"; +import RedeemAtMaturityByPartitionRequest from "../request/bond/RedeemAtMaturityByPartitionRequest"; +import FullRedeemAtMaturityRequest from "../request/bond/FullRedeemAtMaturityRequest"; +import { GetCouponHoldersQuery } from "@query/bond/coupons/getCouponHolders/GetCouponHoldersQuery"; +import { GetTotalCouponHoldersQuery } from "@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQuery"; +import CreateTrexSuiteBondRequest from "../request/bond/CreateTrexSuiteBondRequest"; +import { CreateTrexSuiteBondCommand } from "@command/bond/createTrexSuite/CreateTrexSuiteBondCommand"; +import AddProceedRecipientRequest from "../request/bond/AddProceedRecipientRequest"; +import RemoveProceedRecipientRequest from "../request/bond/RemoveProceedRecipientRequest"; +import UpdateProceedRecipientDataRequest from "../request/bond/UpdateProceedRecipientDataRequest"; +import { UpdateProceedRecipientDataCommand } from "@command/security/proceedRecipients/updateProceedRecipientData/UpdateProceedRecipientDataCommand"; +import { RemoveProceedRecipientCommand } from "@command/security/proceedRecipients/removeProceedRecipient/RemoveProceedRecipientCommand"; +import { AddProceedRecipientCommand } from "@command/security/proceedRecipients/addProceedRecipient/AddProceedRecipientCommand"; +import IsProceedRecipientRequest from "../request/bond/IsProceedRecipientRequest"; +import { GetProceedRecipientsQuery } from "@query/security/proceedRecipient/getProceedRecipients/GetProceedRecipientsQuery"; +import { GetProceedRecipientsCountQuery } from "@query/security/proceedRecipient/getProceedRecipientsCount/GetProceedRecipientsCountQuery"; +import { GetProceedRecipientDataQuery } from "@query/security/proceedRecipient/getProceedRecipientData/GetProceedRecipientDataQuery"; +import { IsProceedRecipientQuery } from "@query/security/proceedRecipient/isProceedRecipient/IsProceedRecipientQuery"; import { GetCouponHoldersRequest, GetTotalCouponHoldersRequest, GetProceedRecipientDataRequest, GetProceedRecipientsCountRequest, GetProceedRecipientsRequest, -} from '../request'; +} from "../request"; interface IBondInPort { - create( - request: CreateBondRequest, - ): Promise<{ security: SecurityViewModel; transactionId: string }>; + create(request: CreateBondRequest): Promise<{ security: SecurityViewModel; transactionId: string }>; getBondDetails(request: GetBondDetailsRequest): Promise; - setCoupon( - request: SetCouponRequest, - ): Promise<{ payload: number; transactionId: string }>; + setCoupon(request: SetCouponRequest): Promise<{ payload: number; transactionId: string }>; getCouponFor(request: GetCouponForRequest): Promise; - getCouponAmountFor( - request: GetCouponForRequest, - ): Promise; - getPrincipalFor( - request: GetPrincipalForRequest, - ): Promise; + getCouponAmountFor(request: GetCouponForRequest): Promise; + getPrincipalFor(request: GetPrincipalForRequest): Promise; getCoupon(request: GetCouponRequest): Promise; getAllCoupons(request: GetAllCouponsRequest): Promise; - updateMaturityDate( - request: UpdateMaturityDateRequest, - ): Promise<{ payload: boolean; transactionId: string }>; + updateMaturityDate(request: UpdateMaturityDateRequest): Promise<{ payload: boolean; transactionId: string }>; redeemAtMaturityByPartition( request: RedeemAtMaturityByPartitionRequest, ): Promise<{ payload: boolean; transactionId: string }>; - fullRedeemAtMaturity( - request: FullRedeemAtMaturityRequest, - ): Promise<{ payload: boolean; transactionId: string }>; + fullRedeemAtMaturity(request: FullRedeemAtMaturityRequest): Promise<{ payload: boolean; transactionId: string }>; getCouponHolders(request: GetCouponHoldersRequest): Promise; getTotalCouponHolders(request: GetTotalCouponHoldersRequest): Promise; - createTrexSuite( - request: CreateTrexSuiteBondRequest, - ): Promise<{ security: SecurityViewModel; transactionId: string }>; + createTrexSuite(request: CreateTrexSuiteBondRequest): Promise<{ security: SecurityViewModel; transactionId: string }>; - addProceedRecipient( - request: AddProceedRecipientRequest, - ): Promise<{ payload: boolean; transactionId: string }>; - removeProceedRecipient( - request: RemoveProceedRecipientRequest, - ): Promise<{ payload: boolean; transactionId: string }>; + addProceedRecipient(request: AddProceedRecipientRequest): Promise<{ payload: boolean; transactionId: string }>; + removeProceedRecipient(request: RemoveProceedRecipientRequest): Promise<{ payload: boolean; transactionId: string }>; updateProceedRecipientData( request: UpdateProceedRecipientDataRequest, ): Promise<{ payload: boolean; transactionId: string }>; - isProceedRecipient( - request: IsProceedRecipientRequest, - ): Promise<{ payload: boolean }>; - getProceedRecipientData( - request: GetProceedRecipientDataRequest, - ): Promise<{ payload: string }>; - getProceedRecipientsCount( - request: GetProceedRecipientsCountRequest, - ): Promise<{ payload: number }>; - getProceedRecipients( - request: GetProceedRecipientsRequest, - ): Promise<{ payload: string[] }>; + isProceedRecipient(request: IsProceedRecipientRequest): Promise<{ payload: boolean }>; + getProceedRecipientData(request: GetProceedRecipientDataRequest): Promise<{ payload: string }>; + getProceedRecipientsCount(request: GetProceedRecipientsCountRequest): Promise<{ payload: number }>; + getProceedRecipients(request: GetProceedRecipientsRequest): Promise<{ payload: string[] }>; } class BondInPort implements IBondInPort { constructor( private readonly queryBus: QueryBus = Injectable.resolve(QueryBus), private readonly commandBus: CommandBus = Injectable.resolve(CommandBus), - private readonly networkService: NetworkService = Injectable.resolve( - NetworkService, - ), + private readonly networkService: NetworkService = Injectable.resolve(NetworkService), ) {} @LogError - async create( - req: CreateBondRequest, - ): Promise<{ security: SecurityViewModel; transactionId: string }> { - ValidatedRequest.handleValidation('CreateBondRequest', req); - const { - diamondOwnerAccount, - externalPausesIds, - externalControlListsIds, - externalKycListsIds, - } = req; + async create(req: CreateBondRequest): Promise<{ security: SecurityViewModel; transactionId: string }> { + ValidatedRequest.handleValidation("CreateBondRequest", req); + const { diamondOwnerAccount, externalPausesIds, externalControlListsIds, externalKycListsIds } = req; const securityFactory = this.networkService.configuration.factoryAddress; const resolver = this.networkService.configuration.resolverAddress; @@ -159,9 +121,7 @@ class BondInPort implements IBondInPort { isMultiPartition: req.isMultiPartition, maxSupply: BigDecimal.fromString(req.numberOfUnits), regulationType: CastRegulationType.fromNumber(req.regulationType), - regulationsubType: CastRegulationSubType.fromNumber( - req.regulationSubType, - ), + regulationsubType: CastRegulationSubType.fromNumber(req.regulationSubType), isCountryControlListWhiteList: req.isCountryControlListWhiteList, countries: req.countries, info: req.info, @@ -190,15 +150,10 @@ class BondInPort implements IBondInPort { ), ); - const securityCreated = - createResponse.securityId.toString() !== ContractId.NULL.toString(); + const securityCreated = createResponse.securityId.toString() !== ContractId.NULL.toString(); const res = securityCreated - ? ( - await this.queryBus.execute( - new GetSecurityQuery(createResponse.securityId.toString()), - ) - ).security + ? (await this.queryBus.execute(new GetSecurityQuery(createResponse.securityId.toString()))).security : {}; return { @@ -212,14 +167,10 @@ class BondInPort implements IBondInPort { } @LogError - async getBondDetails( - request: GetBondDetailsRequest, - ): Promise { - ValidatedRequest.handleValidation('GetBondDetailsRequest', request); + async getBondDetails(request: GetBondDetailsRequest): Promise { + ValidatedRequest.handleValidation("GetBondDetailsRequest", request); - const res = await this.queryBus.execute( - new GetBondDetailsQuery(request.bondId), - ); + const res = await this.queryBus.execute(new GetBondDetailsQuery(request.bondId)); const bondDetails: BondDetailsViewModel = { currency: res.bond.currency, @@ -233,57 +184,37 @@ class BondInPort implements IBondInPort { } @LogError - async setCoupon( - request: SetCouponRequest, - ): Promise<{ payload: number; transactionId: string }> { - const { rate, recordTimestamp, executionTimestamp, securityId, period } = - request; - ValidatedRequest.handleValidation('SetCouponRequest', request); + async setCoupon(request: SetCouponRequest): Promise<{ payload: number; transactionId: string }> { + const { rate, recordTimestamp, executionTimestamp, securityId, period } = request; + ValidatedRequest.handleValidation("SetCouponRequest", request); return await this.commandBus.execute( - new SetCouponCommand( - securityId, - recordTimestamp, - executionTimestamp, - rate, - period, - ), + new SetCouponCommand(securityId, recordTimestamp, executionTimestamp, rate, period), ); } @LogError - async getCouponFor( - request: GetCouponForRequest, - ): Promise { - ValidatedRequest.handleValidation('GetCouponForRequest', request); + async getCouponFor(request: GetCouponForRequest): Promise { + ValidatedRequest.handleValidation("GetCouponForRequest", request); const res = await this.queryBus.execute( - new GetCouponForQuery( - request.targetId, - request.securityId, - request.couponId, - ), + new GetCouponForQuery(request.targetId, request.securityId, request.couponId), ); const couponFor: CouponForViewModel = { - value: res.payload.toString(), + tokenBalance: res.tokenBalance.toString(), + decimals: res.decimals.toString(), }; return couponFor; } @LogError - async getCouponAmountFor( - request: GetCouponForRequest, - ): Promise { - ValidatedRequest.handleValidation('GetCouponForRequest', request); + async getCouponAmountFor(request: GetCouponForRequest): Promise { + ValidatedRequest.handleValidation("GetCouponForRequest", request); const res = await this.queryBus.execute( - new GetCouponAmountForQuery( - request.targetId, - request.securityId, - request.couponId, - ), + new GetCouponAmountForQuery(request.targetId, request.securityId, request.couponId), ); const couponAmountFor: CouponAmountForViewModel = { @@ -296,14 +227,10 @@ class BondInPort implements IBondInPort { } @LogError - async getPrincipalFor( - request: GetPrincipalForRequest, - ): Promise { - ValidatedRequest.handleValidation('GetPrincipalForRequest', request); + async getPrincipalFor(request: GetPrincipalForRequest): Promise { + ValidatedRequest.handleValidation("GetPrincipalForRequest", request); - const res = await this.queryBus.execute( - new GetPrincipalForQuery(request.targetId, request.securityId), - ); + const res = await this.queryBus.execute(new GetPrincipalForQuery(request.targetId, request.securityId)); const principalFor: PrincipalForViewModel = { numerator: res.numerator, @@ -315,11 +242,9 @@ class BondInPort implements IBondInPort { @LogError async getCoupon(request: GetCouponRequest): Promise { - ValidatedRequest.handleValidation('GetCouponRequest', request); + ValidatedRequest.handleValidation("GetCouponRequest", request); - const res = await this.queryBus.execute( - new GetCouponQuery(request.securityId, request.couponId), - ); + const res = await this.queryBus.execute(new GetCouponQuery(request.securityId, request.couponId)); const coupon: CouponViewModel = { couponId: request.couponId, @@ -334,14 +259,10 @@ class BondInPort implements IBondInPort { } @LogError - async getAllCoupons( - request: GetAllCouponsRequest, - ): Promise { - ValidatedRequest.handleValidation('GetAllCouponsRequest', request); + async getAllCoupons(request: GetAllCouponsRequest): Promise { + ValidatedRequest.handleValidation("GetAllCouponsRequest", request); - const count = await this.queryBus.execute( - new GetCouponCountQuery(request.securityId), - ); + const count = await this.queryBus.execute(new GetCouponCountQuery(request.securityId)); if (count.payload == 0) return []; @@ -362,15 +283,11 @@ class BondInPort implements IBondInPort { } @LogError - async updateMaturityDate( - request: UpdateMaturityDateRequest, - ): Promise<{ payload: boolean; transactionId: string }> { + async updateMaturityDate(request: UpdateMaturityDateRequest): Promise<{ payload: boolean; transactionId: string }> { const { maturityDate, securityId } = request; - ValidatedRequest.handleValidation('UpdateMaturityDateRequest', request); + ValidatedRequest.handleValidation("UpdateMaturityDateRequest", request); - return await this.commandBus.execute( - new UpdateMaturityDateCommand(maturityDate, securityId), - ); + return await this.commandBus.execute(new UpdateMaturityDateCommand(maturityDate, securityId)); } @LogError @@ -378,18 +295,10 @@ class BondInPort implements IBondInPort { request: RedeemAtMaturityByPartitionRequest, ): Promise<{ payload: boolean; transactionId: string }> { const { securityId, partitionId, sourceId, amount } = request; - ValidatedRequest.handleValidation( - RedeemAtMaturityByPartitionRequest.name, - request, - ); + ValidatedRequest.handleValidation(RedeemAtMaturityByPartitionRequest.name, request); return await this.commandBus.execute( - new RedeemAtMaturityByPartitionCommand( - securityId, - partitionId, - sourceId, - amount, - ), + new RedeemAtMaturityByPartitionCommand(securityId, partitionId, sourceId, amount), ); } @@ -398,17 +307,9 @@ class BondInPort implements IBondInPort { request: FullRedeemAtMaturityRequest, ): Promise<{ payload: boolean; transactionId: string }> { const { securityId, sourceId } = request; - ValidatedRequest.handleValidation( - FullRedeemAtMaturityRequest.name, - request, - ); + ValidatedRequest.handleValidation(FullRedeemAtMaturityRequest.name, request); - return await this.commandBus.execute( - new FullRedeemAtMaturityCommand( - securityId, - sourceId, - ), - ); + return await this.commandBus.execute(new FullRedeemAtMaturityCommand(securityId, sourceId)); } @LogError @@ -416,42 +317,24 @@ class BondInPort implements IBondInPort { const { securityId, couponId, start, end } = request; ValidatedRequest.handleValidation(GetCouponHoldersRequest.name, request); - return ( - await this.queryBus.execute( - new GetCouponHoldersQuery(securityId, couponId, start, end), - ) - ).payload; + return (await this.queryBus.execute(new GetCouponHoldersQuery(securityId, couponId, start, end))).payload; } @LogError - async getTotalCouponHolders( - request: GetTotalCouponHoldersRequest, - ): Promise { + async getTotalCouponHolders(request: GetTotalCouponHoldersRequest): Promise { const { securityId, couponId } = request; - ValidatedRequest.handleValidation( - GetTotalCouponHoldersRequest.name, - request, - ); + ValidatedRequest.handleValidation(GetTotalCouponHoldersRequest.name, request); - return ( - await this.queryBus.execute( - new GetTotalCouponHoldersQuery(securityId, couponId), - ) - ).payload; + return (await this.queryBus.execute(new GetTotalCouponHoldersQuery(securityId, couponId))).payload; } @LogError async createTrexSuite( req: CreateTrexSuiteBondRequest, ): Promise<{ security: SecurityViewModel; transactionId: string }> { - ValidatedRequest.handleValidation('CreateTrexSuiteBondRequest', req); + ValidatedRequest.handleValidation("CreateTrexSuiteBondRequest", req); - const { - diamondOwnerAccount, - externalPauses, - externalControlLists, - externalKycLists, - } = req; + const { diamondOwnerAccount, externalPauses, externalControlLists, externalKycLists } = req; const securityFactory = this.networkService.configuration.factoryAddress; const resolver = this.networkService.configuration.resolverAddress; @@ -469,9 +352,7 @@ class BondInPort implements IBondInPort { isMultiPartition: req.isMultiPartition, maxSupply: BigDecimal.fromString(req.numberOfUnits), regulationType: CastRegulationType.fromNumber(req.regulationType), - regulationsubType: CastRegulationSubType.fromNumber( - req.regulationSubType, - ), + regulationsubType: CastRegulationSubType.fromNumber(req.regulationSubType), isCountryControlListWhiteList: req.isCountryControlListWhiteList, countries: req.countries, info: req.info, @@ -511,15 +392,10 @@ class BondInPort implements IBondInPort { req.identityRegistryId, ), ); - const securityCreated = - createResponse.securityId.toString() !== ContractId.NULL.toString(); + const securityCreated = createResponse.securityId.toString() !== ContractId.NULL.toString(); const res = securityCreated - ? ( - await this.queryBus.execute( - new GetSecurityQuery(createResponse.securityId.toString()), - ) - ).security + ? (await this.queryBus.execute(new GetSecurityQuery(createResponse.securityId.toString()))).security : {}; return { @@ -536,16 +412,9 @@ class BondInPort implements IBondInPort { async updateProceedRecipientData( request: UpdateProceedRecipientDataRequest, ): Promise<{ payload: boolean; transactionId: string }> { - ValidatedRequest.handleValidation( - UpdateProceedRecipientDataRequest.name, - request, - ); + ValidatedRequest.handleValidation(UpdateProceedRecipientDataRequest.name, request); return await this.commandBus.execute( - new UpdateProceedRecipientDataCommand( - request.securityId, - request.proceedRecipientId, - request.data, - ), + new UpdateProceedRecipientDataCommand(request.securityId, request.proceedRecipientId, request.data), ); } @@ -553,86 +422,43 @@ class BondInPort implements IBondInPort { async removeProceedRecipient( request: RemoveProceedRecipientRequest, ): Promise<{ payload: boolean; transactionId: string }> { - ValidatedRequest.handleValidation( - RemoveProceedRecipientRequest.name, - request, - ); + ValidatedRequest.handleValidation(RemoveProceedRecipientRequest.name, request); return await this.commandBus.execute( - new RemoveProceedRecipientCommand( - request.securityId, - request.proceedRecipientId, - ), + new RemoveProceedRecipientCommand(request.securityId, request.proceedRecipientId), ); } @LogError - async addProceedRecipient( - request: AddProceedRecipientRequest, - ): Promise<{ payload: boolean; transactionId: string }> { + async addProceedRecipient(request: AddProceedRecipientRequest): Promise<{ payload: boolean; transactionId: string }> { ValidatedRequest.handleValidation(AddProceedRecipientRequest.name, request); return await this.commandBus.execute( - new AddProceedRecipientCommand( - request.securityId, - request.proceedRecipientId, - request.data, - ), + new AddProceedRecipientCommand(request.securityId, request.proceedRecipientId, request.data), ); } @LogError - async getProceedRecipients( - request: GetProceedRecipientsRequest, - ): Promise<{ payload: string[] }> { - ValidatedRequest.handleValidation( - GetProceedRecipientsRequest.name, - request, - ); + async getProceedRecipients(request: GetProceedRecipientsRequest): Promise<{ payload: string[] }> { + ValidatedRequest.handleValidation(GetProceedRecipientsRequest.name, request); return await this.queryBus.execute( - new GetProceedRecipientsQuery( - request.securityId, - request.pageIndex, - request.pageSize, - ), + new GetProceedRecipientsQuery(request.securityId, request.pageIndex, request.pageSize), ); } @LogError - async getProceedRecipientsCount( - request: GetProceedRecipientsCountRequest, - ): Promise<{ payload: number }> { - ValidatedRequest.handleValidation( - GetProceedRecipientsCountRequest.name, - request, - ); - return await this.queryBus.execute( - new GetProceedRecipientsCountQuery(request.securityId), - ); + async getProceedRecipientsCount(request: GetProceedRecipientsCountRequest): Promise<{ payload: number }> { + ValidatedRequest.handleValidation(GetProceedRecipientsCountRequest.name, request); + return await this.queryBus.execute(new GetProceedRecipientsCountQuery(request.securityId)); } @LogError - async getProceedRecipientData( - request: GetProceedRecipientDataRequest, - ): Promise<{ payload: string }> { - ValidatedRequest.handleValidation( - GetProceedRecipientDataRequest.name, - request, - ); + async getProceedRecipientData(request: GetProceedRecipientDataRequest): Promise<{ payload: string }> { + ValidatedRequest.handleValidation(GetProceedRecipientDataRequest.name, request); return await this.queryBus.execute( - new GetProceedRecipientDataQuery( - request.securityId, - request.proceedRecipientId, - ), + new GetProceedRecipientDataQuery(request.securityId, request.proceedRecipientId), ); } @LogError - async isProceedRecipient( - request: IsProceedRecipientRequest, - ): Promise<{ payload: boolean }> { + async isProceedRecipient(request: IsProceedRecipientRequest): Promise<{ payload: boolean }> { ValidatedRequest.handleValidation(IsProceedRecipientRequest.name, request); - return await this.queryBus.execute( - new IsProceedRecipientQuery( - request.securityId, - request.proceedRecipientId, - ), - ); + return await this.queryBus.execute(new IsProceedRecipientQuery(request.securityId, request.proceedRecipientId)); } } diff --git a/packages/ats/sdk/src/port/in/bond/Bond.unit.test.ts b/packages/ats/sdk/src/port/in/bond/Bond.unit.test.ts index eddea3f7e..b42208825 100644 --- a/packages/ats/sdk/src/port/in/bond/Bond.unit.test.ts +++ b/packages/ats/sdk/src/port/in/bond/Bond.unit.test.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -import { createMock } from '@golevelup/ts-jest'; -import { CommandBus } from '@core/command/CommandBus'; +import { createMock } from "@golevelup/ts-jest"; +import { CommandBus } from "@core/command/CommandBus"; import { CreateBondRequest, GetBondDetailsRequest, @@ -22,17 +22,14 @@ import { GetProceedRecipientDataRequest, GetProceedRecipientsRequest, GetPrincipalForRequest, -} from '../request'; -import { - HederaIdPropsFixture, - TransactionIdFixture, -} from '@test/fixtures/shared/DataFixture'; -import LogService from '@service/log/LogService'; -import { QueryBus } from '@core/query/QueryBus'; -import ValidatedRequest from '@core/validation/ValidatedArgs'; -import { ValidationError } from '@core/validation/ValidationError'; -import NetworkService from '@service/network/NetworkService'; -import BondToken from './Bond'; +} from "../request"; +import { HederaIdPropsFixture, TransactionIdFixture } from "@test/fixtures/shared/DataFixture"; +import LogService from "@service/log/LogService"; +import { QueryBus } from "@core/query/QueryBus"; +import ValidatedRequest from "@core/validation/ValidatedArgs"; +import { ValidationError } from "@core/validation/ValidationError"; +import NetworkService from "@service/network/NetworkService"; +import BondToken from "./Bond"; import { BondDetailsFixture, CouponFixture, @@ -56,42 +53,39 @@ import { GetProceedRecipientDataRequestFixture, GetProceedRecipientsRequestFixture, GetPrincipalForRequestFixture, -} from '@test/fixtures/bond/BondFixture'; -import { SecurityPropsFixture } from '@test/fixtures/shared/SecurityFixture'; -import { Security } from '@domain/context/security/Security'; -import { CreateBondCommand } from '@command/bond/create/CreateBondCommand'; -import ContractId from '@domain/context/contract/ContractId'; -import { - CastRegulationSubType, - CastRegulationType, -} from '@domain/context/factory/RegulationType'; -import BigDecimal from '@domain/context/shared/BigDecimal'; -import { faker } from '@faker-js/faker/.'; -import { GetBondDetailsQuery } from '@query/bond/get/getBondDetails/GetBondDetailsQuery'; -import { ONE_THOUSAND } from '@domain/context/shared/SecurityDate'; -import { SetCouponCommand } from '@command/bond/coupon/set/SetCouponCommand'; -import { BigNumber } from 'ethers'; -import { GetCouponForQuery } from '@query/bond/coupons/getCouponFor/GetCouponForQuery'; -import { GetPrincipalForQuery } from '@query/bond/get/getPrincipalFor/GetPrincipalForQuery'; -import { GetCouponAmountForQuery } from '@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQuery'; -import { GetCouponQuery } from '@query/bond/coupons/getCoupon/GetCouponQuery'; -import { GetCouponCountQuery } from '@query/bond/coupons/getCouponCount/GetCouponCountQuery'; -import { UpdateMaturityDateCommand } from '@command/bond/updateMaturityDate/UpdateMaturityDateCommand'; -import { RedeemAtMaturityByPartitionCommand } from '@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommand'; -import { FullRedeemAtMaturityCommand } from '@command/bond/fullRedeemAtMaturity/FullRedeemAtMaturityCommand'; -import { GetCouponHoldersQuery } from '@query/bond/coupons/getCouponHolders/GetCouponHoldersQuery'; -import { GetTotalCouponHoldersQuery } from '@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQuery'; -import { CreateTrexSuiteBondCommand } from '@command/bond/createTrexSuite/CreateTrexSuiteBondCommand'; -import AddProceedRecipientRequest from '../request/bond/AddProceedRecipientRequest'; -import { AddProceedRecipientCommand } from '@command/security/proceedRecipients/addProceedRecipient/AddProceedRecipientCommand'; -import { RemoveProceedRecipientCommand } from '@command/security/proceedRecipients/removeProceedRecipient/RemoveProceedRecipientCommand'; -import { UpdateProceedRecipientDataCommand } from '@command/security/proceedRecipients/updateProceedRecipientData/UpdateProceedRecipientDataCommand'; -import { IsProceedRecipientQuery } from '@query/security/proceedRecipient/isProceedRecipient/IsProceedRecipientQuery'; -import { GetProceedRecipientsCountQuery } from '@query/security/proceedRecipient/getProceedRecipientsCount/GetProceedRecipientsCountQuery'; -import { GetProceedRecipientDataQuery } from '@query/security/proceedRecipient/getProceedRecipientData/GetProceedRecipientDataQuery'; -import { GetProceedRecipientsQuery } from '@query/security/proceedRecipient/getProceedRecipients/GetProceedRecipientsQuery'; - -describe('Bond', () => { +} from "@test/fixtures/bond/BondFixture"; +import { SecurityPropsFixture } from "@test/fixtures/shared/SecurityFixture"; +import { Security } from "@domain/context/security/Security"; +import { CreateBondCommand } from "@command/bond/create/CreateBondCommand"; +import ContractId from "@domain/context/contract/ContractId"; +import { CastRegulationSubType, CastRegulationType } from "@domain/context/factory/RegulationType"; +import BigDecimal from "@domain/context/shared/BigDecimal"; +import { faker } from "@faker-js/faker/."; +import { GetBondDetailsQuery } from "@query/bond/get/getBondDetails/GetBondDetailsQuery"; +import { ONE_THOUSAND } from "@domain/context/shared/SecurityDate"; +import { SetCouponCommand } from "@command/bond/coupon/set/SetCouponCommand"; +import { BigNumber } from "ethers"; +import { GetCouponForQuery } from "@query/bond/coupons/getCouponFor/GetCouponForQuery"; +import { GetPrincipalForQuery } from "@query/bond/get/getPrincipalFor/GetPrincipalForQuery"; +import { GetCouponAmountForQuery } from "@query/bond/coupons/getCouponAmountFor/GetCouponAmountForQuery"; +import { GetCouponQuery } from "@query/bond/coupons/getCoupon/GetCouponQuery"; +import { GetCouponCountQuery } from "@query/bond/coupons/getCouponCount/GetCouponCountQuery"; +import { UpdateMaturityDateCommand } from "@command/bond/updateMaturityDate/UpdateMaturityDateCommand"; +import { RedeemAtMaturityByPartitionCommand } from "@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommand"; +import { FullRedeemAtMaturityCommand } from "@command/bond/fullRedeemAtMaturity/FullRedeemAtMaturityCommand"; +import { GetCouponHoldersQuery } from "@query/bond/coupons/getCouponHolders/GetCouponHoldersQuery"; +import { GetTotalCouponHoldersQuery } from "@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQuery"; +import { CreateTrexSuiteBondCommand } from "@command/bond/createTrexSuite/CreateTrexSuiteBondCommand"; +import AddProceedRecipientRequest from "../request/bond/AddProceedRecipientRequest"; +import { AddProceedRecipientCommand } from "@command/security/proceedRecipients/addProceedRecipient/AddProceedRecipientCommand"; +import { RemoveProceedRecipientCommand } from "@command/security/proceedRecipients/removeProceedRecipient/RemoveProceedRecipientCommand"; +import { UpdateProceedRecipientDataCommand } from "@command/security/proceedRecipients/updateProceedRecipientData/UpdateProceedRecipientDataCommand"; +import { IsProceedRecipientQuery } from "@query/security/proceedRecipient/isProceedRecipient/IsProceedRecipientQuery"; +import { GetProceedRecipientsCountQuery } from "@query/security/proceedRecipient/getProceedRecipientsCount/GetProceedRecipientsCountQuery"; +import { GetProceedRecipientDataQuery } from "@query/security/proceedRecipient/getProceedRecipientData/GetProceedRecipientDataQuery"; +import { GetProceedRecipientsQuery } from "@query/security/proceedRecipient/getProceedRecipients/GetProceedRecipientsQuery"; + +describe("Bond", () => { let commandBusMock: jest.Mocked; let queryBusMock: jest.Mocked; let networkServiceMock: jest.Mocked; @@ -120,14 +114,14 @@ describe('Bond', () => { beforeEach(() => { commandBusMock = createMock(); queryBusMock = createMock(); - handleValidationSpy = jest.spyOn(ValidatedRequest, 'handleValidation'); + handleValidationSpy = jest.spyOn(ValidatedRequest, "handleValidation"); networkServiceMock = createMock({ configuration: { factoryAddress: factoryAddress, resolverAddress: resolverAddress, }, }); - jest.spyOn(LogService, 'logError').mockImplementation(() => {}); + jest.spyOn(LogService, "logError").mockImplementation(() => {}); (BondToken as any).commandBus = commandBusMock; (BondToken as any).queryBus = queryBusMock; (BondToken as any).networkService = networkServiceMock; @@ -138,11 +132,9 @@ describe('Bond', () => { jest.restoreAllMocks(); }); - describe('create', () => { - createBondRequest = new CreateBondRequest( - CreateBondRequestFixture.create(), - ); - it('should create successfully', async () => { + describe("create", () => { + createBondRequest = new CreateBondRequest(CreateBondRequestFixture.create()); + it("should create successfully", async () => { const expectedResponse = { securityId: new ContractId(HederaIdPropsFixture.create().value), transactionId: transactionId, @@ -155,10 +147,7 @@ describe('Bond', () => { const result = await BondToken.create(createBondRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'CreateBondRequest', - createBondRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("CreateBondRequest", createBondRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -177,14 +166,9 @@ describe('Bond', () => { internalKycActivated: createBondRequest.internalKycActivated, isMultiPartition: createBondRequest.isMultiPartition, maxSupply: BigDecimal.fromString(createBondRequest.numberOfUnits), - regulationType: CastRegulationType.fromNumber( - createBondRequest.regulationType, - ), - regulationsubType: CastRegulationSubType.fromNumber( - createBondRequest.regulationSubType, - ), - isCountryControlListWhiteList: - createBondRequest.isCountryControlListWhiteList, + regulationType: CastRegulationType.fromNumber(createBondRequest.regulationType), + regulationsubType: CastRegulationSubType.fromNumber(createBondRequest.regulationSubType), + isCountryControlListWhiteList: createBondRequest.isCountryControlListWhiteList, countries: createBondRequest.countries, info: createBondRequest.info, }), @@ -216,18 +200,13 @@ describe('Bond', () => { ); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - 'Command execution failed', - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow("Command execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'CreateBondRequest', - createBondRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("CreateBondRequest", createBondRequest); expect(commandBusMock.execute).toHaveBeenCalledWith( new CreateBondCommand( @@ -243,14 +222,9 @@ describe('Bond', () => { internalKycActivated: createBondRequest.internalKycActivated, isMultiPartition: createBondRequest.isMultiPartition, maxSupply: BigDecimal.fromString(createBondRequest.numberOfUnits), - regulationType: CastRegulationType.fromNumber( - createBondRequest.regulationType, - ), - regulationsubType: CastRegulationSubType.fromNumber( - createBondRequest.regulationSubType, - ), - isCountryControlListWhiteList: - createBondRequest.isCountryControlListWhiteList, + regulationType: CastRegulationType.fromNumber(createBondRequest.regulationType), + regulationsubType: CastRegulationSubType.fromNumber(createBondRequest.regulationSubType), + isCountryControlListWhiteList: createBondRequest.isCountryControlListWhiteList, countries: createBondRequest.countries, info: createBondRequest.info, }), @@ -275,112 +249,94 @@ describe('Bond', () => { ); }); - it('should not throw error if proceedRecipientsData not has bytes', async () => { + it("should not throw error if proceedRecipientsData not has bytes", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - proceedRecipientsData: ['', '0x1234'], - proceedRecipientsIds: ['0.0.1234', '0.0.5678'], + proceedRecipientsData: ["", "0x1234"], + proceedRecipientsIds: ["0.0.1234", "0.0.5678"], }), ); await expect(BondToken.create(createBondRequest)).resolves.not.toThrow(); }); - it('should throw error if name is invalid', async () => { - createBondRequest = new CreateBondRequest( - CreateBondRequestFixture.create({ name: '' }), - ); + it("should throw error if name is invalid", async () => { + createBondRequest = new CreateBondRequest(CreateBondRequestFixture.create({ name: "" })); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if symbol is invalid', async () => { + it("should throw error if symbol is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - symbol: '', + symbol: "", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if isin is invalid', async () => { + it("should throw error if isin is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - isin: '', + isin: "", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if decimals is invalid', async () => { + it("should throw error if decimals is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ decimals: 2.85, }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if diamondOwnerAccount is invalid', async () => { + it("should throw error if diamondOwnerAccount is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - diamondOwnerAccount: 'invalid', + diamondOwnerAccount: "invalid", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if currency is invalid', async () => { + it("should throw error if currency is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - currency: 'invalid', + currency: "invalid", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if numberOfUnits is invalid', async () => { + it("should throw error if numberOfUnits is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - numberOfUnits: 'invalid', + numberOfUnits: "invalid", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if nominalValue is invalid', async () => { + it("should throw error if nominalValue is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - nominalValue: 'invalid', + nominalValue: "invalid", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if startingDate is invalid', async () => { + it("should throw error if startingDate is invalid", async () => { const time = Math.floor(faker.date.past().getTime() / 1000); createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ @@ -389,89 +345,73 @@ describe('Bond', () => { }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if maturityDate is invalid', async () => { + it("should throw error if maturityDate is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ maturityDate: faker.date.past().getTime().toString(), }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if regulationSubType is invalid', async () => { + it("should throw error if regulationSubType is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ regulationSubType: 5, }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if configId is invalid', async () => { + it("should throw error if configId is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - configId: 'invalid', + configId: "invalid", }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalPausesIds is invalid', async () => { + it("should throw error if externalPausesIds is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - externalPausesIds: ['invalid'], + externalPausesIds: ["invalid"], }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalControlListsIds is invalid', async () => { + it("should throw error if externalControlListsIds is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - externalControlListsIds: ['invalid'], + externalControlListsIds: ["invalid"], }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalKycListsIds is invalid', async () => { + it("should throw error if externalKycListsIds is invalid", async () => { createBondRequest = new CreateBondRequest( CreateBondRequestFixture.create({ - externalKycListsIds: ['invalid'], + externalKycListsIds: ["invalid"], }), ); - await expect(BondToken.create(createBondRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.create(createBondRequest)).rejects.toThrow(ValidationError); }); }); - describe('getBondDetails', () => { - getBondDetailsRequest = new GetBondDetailsRequest( - GetBondDetailsRequestFixture.create(), - ); - it('should get bond details successfully', async () => { + describe("getBondDetails", () => { + getBondDetailsRequest = new GetBondDetailsRequest(GetBondDetailsRequestFixture.create()); + it("should get bond details successfully", async () => { const expectedResponse = { bond: BondDetailsFixture.create(), }; @@ -480,65 +420,47 @@ describe('Bond', () => { const result = await BondToken.getBondDetails(getBondDetailsRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetBondDetailsRequest', - getBondDetailsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetBondDetailsRequest", getBondDetailsRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); - expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetBondDetailsQuery(getBondDetailsRequest.bondId), - ); + expect(queryBusMock.execute).toHaveBeenCalledWith(new GetBondDetailsQuery(getBondDetailsRequest.bondId)); expect(result).toEqual( expect.objectContaining({ currency: expectedResponse.bond.currency, nominalValue: expectedResponse.bond.nominalValue.toString(), nominalValueDecimals: expectedResponse.bond.nominalValueDecimals, - startingDate: new Date( - expectedResponse.bond.startingDate * ONE_THOUSAND, - ), - maturityDate: new Date( - expectedResponse.bond.maturityDate * ONE_THOUSAND, - ), + startingDate: new Date(expectedResponse.bond.startingDate * ONE_THOUSAND), + maturityDate: new Date(expectedResponse.bond.maturityDate * ONE_THOUSAND), }), ); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getBondDetails(getBondDetailsRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getBondDetails(getBondDetailsRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetBondDetailsRequest', - getBondDetailsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetBondDetailsRequest", getBondDetailsRequest); - expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetBondDetailsQuery(getBondDetailsRequest.bondId), - ); + expect(queryBusMock.execute).toHaveBeenCalledWith(new GetBondDetailsQuery(getBondDetailsRequest.bondId)); }); - it('should throw error if bondId is invalid', async () => { + it("should throw error if bondId is invalid", async () => { getBondDetailsRequest = new GetBondDetailsRequest({ ...GetBondDetailsRequestFixture.create(), - bondId: 'invalid', + bondId: "invalid", }); - await expect( - BondToken.getBondDetails(getBondDetailsRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getBondDetails(getBondDetailsRequest)).rejects.toThrow(ValidationError); }); }); - describe('setCoupon', () => { + describe("setCoupon", () => { setCouponRequest = new SetCouponRequest(SetCouponRequestFixture.create()); - it('should set coupon successfully', async () => { + it("should set coupon successfully", async () => { const expectedResponse = { payload: 1, transactionId: transactionId, @@ -548,10 +470,7 @@ describe('Bond', () => { const result = await BondToken.setCoupon(setCouponRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'SetCouponRequest', - setCouponRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("SetCouponRequest", setCouponRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); @@ -568,18 +487,13 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow( - 'Command execution failed', - ); + await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow("Command execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'SetCouponRequest', - setCouponRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("SetCouponRequest", setCouponRequest); expect(commandBusMock.execute).toHaveBeenCalledWith( new SetCouponCommand( @@ -592,20 +506,16 @@ describe('Bond', () => { ); }); - it('should throw error if recordTimestamp is invalid', async () => { + it("should throw error if recordTimestamp is invalid", async () => { setCouponRequest = new SetCouponRequest({ ...SetCouponRequestFixture.create(), - recordTimestamp: ( - Math.ceil(new Date().getTime() / 1000) - 100 - ).toString(), + recordTimestamp: (Math.ceil(new Date().getTime() / 1000) - 100).toString(), }); - await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if executionTimestamp is invalid', async () => { + it("should throw error if executionTimestamp is invalid", async () => { const time = faker.date.past().getTime(); setCouponRequest = new SetCouponRequest({ ...SetCouponRequestFixture.create(), @@ -613,52 +523,42 @@ describe('Bond', () => { executionTimestamp: (time - 10).toString(), }); - await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { setCouponRequest = new SetCouponRequest({ ...SetCouponRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if rate is invalid', async () => { + it("should throw error if rate is invalid", async () => { setCouponRequest = new SetCouponRequest({ ...SetCouponRequestFixture.create(), - rate: 'invalid', + rate: "invalid", }); - await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.setCoupon(setCouponRequest)).rejects.toThrow(ValidationError); }); }); - describe('getCouponFor', () => { + describe("getCouponFor", () => { beforeEach(() => { - getCouponForRequest = new GetCouponForRequest( - GetCouponForRequestFixture.create(), - ); + getCouponForRequest = new GetCouponForRequest(GetCouponForRequestFixture.create()); }); - it('should get coupon for successfully', async () => { + it("should get coupon for successfully", async () => { const expectedResponse = { - payload: new BigDecimal(BigNumber.from(10)), + tokenBalance: new BigDecimal(BigNumber.from(1000)), + decimals: 2, }; queryBusMock.execute.mockResolvedValue(expectedResponse); const result = await BondToken.getCouponFor(getCouponForRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponForRequest', - getCouponForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponForRequest", getCouponForRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -672,23 +572,19 @@ describe('Bond', () => { expect(result).toEqual( expect.objectContaining({ - value: expectedResponse.payload.toString(), + tokenBalance: expectedResponse.tokenBalance.toString(), + decimals: expectedResponse.decimals.toString(), }), ); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow( - 'Query execution failed', - ); + await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponForRequest', - getCouponForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponForRequest", getCouponForRequest); expect(queryBusMock.execute).toHaveBeenCalledWith( new GetCouponForQuery( @@ -699,50 +595,42 @@ describe('Bond', () => { ); }); - it('should throw error if targetId is invalid', async () => { + it("should throw error if targetId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), - targetId: 'invalid', + targetId: "invalid", }); - await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if couponId is invalid', async () => { + it("should throw error if couponId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), couponId: 0, }); - await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.getCouponFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); }); - describe('getCouponAmountFor', () => { + describe("getCouponAmountFor", () => { beforeEach(() => { - getCouponForRequest = new GetCouponForRequest( - GetCouponForRequestFixture.create(), - ); + getCouponForRequest = new GetCouponForRequest(GetCouponForRequestFixture.create()); }); - it('should get coupon for successfully', async () => { + it("should get coupon for successfully", async () => { const expectedResponse = { - numerator: '10', - denominator: '4', + numerator: "10", + denominator: "4", recordDateReached: true, }; @@ -750,10 +638,7 @@ describe('Bond', () => { const result = await BondToken.getCouponAmountFor(getCouponForRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponForRequest', - getCouponForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponForRequest", getCouponForRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -774,18 +659,13 @@ describe('Bond', () => { ); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getCouponAmountFor(getCouponForRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getCouponAmountFor(getCouponForRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponForRequest', - getCouponForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponForRequest", getCouponForRequest); expect(queryBusMock.execute).toHaveBeenCalledWith( new GetCouponAmountForQuery( @@ -796,68 +676,54 @@ describe('Bond', () => { ); }); - it('should throw error if targetId is invalid', async () => { + it("should throw error if targetId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), - targetId: 'invalid', + targetId: "invalid", }); - await expect( - BondToken.getCouponAmountFor(getCouponForRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponAmountFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.getCouponAmountFor(getCouponForRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponAmountFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if couponId is invalid', async () => { + it("should throw error if couponId is invalid", async () => { getCouponForRequest = new GetCouponForRequest({ ...GetCouponForRequestFixture.create(), couponId: 0, }); - await expect( - BondToken.getCouponAmountFor(getCouponForRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponAmountFor(getCouponForRequest)).rejects.toThrow(ValidationError); }); }); - describe('getPrincipalFor', () => { + describe("getPrincipalFor", () => { beforeEach(() => { - getPrincipalForRequest = new GetPrincipalForRequest( - GetPrincipalForRequestFixture.create(), - ); + getPrincipalForRequest = new GetPrincipalForRequest(GetPrincipalForRequestFixture.create()); }); - it('should get principal for successfully', async () => { + it("should get principal for successfully", async () => { const expectedResponse = { - numerator: '10', - denominator: '4', + numerator: "10", + denominator: "4", }; queryBusMock.execute.mockResolvedValue(expectedResponse); const result = await BondToken.getPrincipalFor(getPrincipalForRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetPrincipalForRequest', - getPrincipalForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetPrincipalForRequest", getPrincipalForRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetPrincipalForQuery( - getPrincipalForRequest.targetId, - getPrincipalForRequest.securityId, - ), + new GetPrincipalForQuery(getPrincipalForRequest.targetId, getPrincipalForRequest.securityId), ); expect(result).toEqual( @@ -868,53 +734,41 @@ describe('Bond', () => { ); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getPrincipalFor(getPrincipalForRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getPrincipalFor(getPrincipalForRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetPrincipalForRequest', - getPrincipalForRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetPrincipalForRequest", getPrincipalForRequest); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetPrincipalForQuery( - getPrincipalForRequest.targetId, - getPrincipalForRequest.securityId, - ), + new GetPrincipalForQuery(getPrincipalForRequest.targetId, getPrincipalForRequest.securityId), ); }); - it('should throw error if targetId is invalid', async () => { + it("should throw error if targetId is invalid", async () => { getPrincipalForRequest = new GetPrincipalForRequest({ ...GetPrincipalForRequestFixture.create(), - targetId: 'invalid', + targetId: "invalid", }); - await expect( - BondToken.getPrincipalFor(getPrincipalForRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getPrincipalFor(getPrincipalForRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getPrincipalForRequest = new GetPrincipalForRequest({ ...GetPrincipalForRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.getPrincipalFor(getPrincipalForRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getPrincipalFor(getPrincipalForRequest)).rejects.toThrow(ValidationError); }); }); - describe('getCoupon', () => { + describe("getCoupon", () => { getCouponRequest = new GetCouponRequest(GetCouponRequestFixture.create()); - it('should get coupon successfully', async () => { + it("should get coupon successfully", async () => { const expectedResponse = { coupon: CouponFixture.create(), }; @@ -923,83 +777,59 @@ describe('Bond', () => { const result = await BondToken.getCoupon(getCouponRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponRequest', - getCouponRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponRequest", getCouponRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetCouponQuery( - getCouponRequest.securityId, - getCouponRequest.couponId, - ), + new GetCouponQuery(getCouponRequest.securityId, getCouponRequest.couponId), ); expect(result).toEqual( expect.objectContaining({ couponId: getCouponRequest.couponId, - recordDate: new Date( - expectedResponse.coupon.recordTimeStamp * ONE_THOUSAND, - ), - executionDate: new Date( - expectedResponse.coupon.executionTimeStamp * ONE_THOUSAND, - ), + recordDate: new Date(expectedResponse.coupon.recordTimeStamp * ONE_THOUSAND), + executionDate: new Date(expectedResponse.coupon.executionTimeStamp * ONE_THOUSAND), rate: expectedResponse.coupon.rate.toString(), }), ); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow( - 'Query execution failed', - ); + await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetCouponRequest', - getCouponRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetCouponRequest", getCouponRequest); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetCouponQuery( - getCouponRequest.securityId, - getCouponRequest.couponId, - ), + new GetCouponQuery(getCouponRequest.securityId, getCouponRequest.couponId), ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getCouponRequest = new GetCouponRequest({ ...GetCouponRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if couponId is invalid', async () => { + it("should throw error if couponId is invalid", async () => { getCouponRequest = new GetCouponRequest({ ...GetCouponRequestFixture.create(), couponId: 0, }); - await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow( - ValidationError, - ); + await expect(BondToken.getCoupon(getCouponRequest)).rejects.toThrow(ValidationError); }); }); - describe('getAllCoupons', () => { - getAllCouponsRequest = new GetAllCouponsRequest( - GetAllCouponsRequestFixture.create(), - ); - it('should get all coupon successfully', async () => { + describe("getAllCoupons", () => { + getAllCouponsRequest = new GetAllCouponsRequest(GetAllCouponsRequestFixture.create()); + it("should get all coupon successfully", async () => { const expectedResponse = { payload: 1, }; @@ -1008,46 +838,31 @@ describe('Bond', () => { coupon: CouponFixture.create(), }; - queryBusMock.execute - .mockResolvedValueOnce(expectedResponse) - .mockResolvedValueOnce(expectedResponse2); + queryBusMock.execute.mockResolvedValueOnce(expectedResponse).mockResolvedValueOnce(expectedResponse2); const result = await BondToken.getAllCoupons(getAllCouponsRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetAllCouponsRequest', - getAllCouponsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetAllCouponsRequest", getAllCouponsRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(2); - expect(queryBusMock.execute).toHaveBeenNthCalledWith( - 1, - new GetCouponCountQuery(getAllCouponsRequest.securityId), - ); + expect(queryBusMock.execute).toHaveBeenNthCalledWith(1, new GetCouponCountQuery(getAllCouponsRequest.securityId)); - expect(queryBusMock.execute).toHaveBeenNthCalledWith( - 2, - new GetCouponQuery(getAllCouponsRequest.securityId, 1), - ); + expect(queryBusMock.execute).toHaveBeenNthCalledWith(2, new GetCouponQuery(getAllCouponsRequest.securityId, 1)); expect(result).toEqual( expect.arrayContaining([ { couponId: 1, - recordDate: new Date( - expectedResponse2.coupon.recordTimeStamp * ONE_THOUSAND, - ), - executionDate: new Date( - expectedResponse2.coupon.executionTimeStamp * ONE_THOUSAND, - ), + recordDate: new Date(expectedResponse2.coupon.recordTimeStamp * ONE_THOUSAND), + executionDate: new Date(expectedResponse2.coupon.executionTimeStamp * ONE_THOUSAND), rate: expectedResponse2.coupon.rate.toString(), }, ]), ); }); - it('should return empty array if count is 0', async () => { + it("should return empty array if count is 0", async () => { const expectedResponse = { payload: 0, }; @@ -1055,44 +870,30 @@ describe('Bond', () => { const result = await BondToken.getAllCoupons(getAllCouponsRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetAllCouponsRequest', - getAllCouponsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetAllCouponsRequest", getAllCouponsRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); - expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetCouponCountQuery(getAllCouponsRequest.securityId), - ); + expect(queryBusMock.execute).toHaveBeenCalledWith(new GetCouponCountQuery(getAllCouponsRequest.securityId)); expect(result).toStrictEqual([]); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getAllCoupons(getAllCouponsRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getAllCoupons(getAllCouponsRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetAllCouponsRequest', - getAllCouponsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetAllCouponsRequest", getAllCouponsRequest); - expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetCouponCountQuery(getAllCouponsRequest.securityId), - ); + expect(queryBusMock.execute).toHaveBeenCalledWith(new GetCouponCountQuery(getAllCouponsRequest.securityId)); }); }); - describe('updateMaturityDate', () => { - updateMaturityDateRequest = new UpdateMaturityDateRequest( - UpdateMaturityDateRequestFixture.create(), - ); - it('should update maturity date successfully', async () => { + describe("updateMaturityDate", () => { + updateMaturityDateRequest = new UpdateMaturityDateRequest(UpdateMaturityDateRequestFixture.create()); + it("should update maturity date successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -1100,76 +901,56 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.updateMaturityDate( - updateMaturityDateRequest, - ); + const result = await BondToken.updateMaturityDate(updateMaturityDateRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'UpdateMaturityDateRequest', - updateMaturityDateRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("UpdateMaturityDateRequest", updateMaturityDateRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); expect(commandBusMock.execute).toHaveBeenCalledWith( - new UpdateMaturityDateCommand( - updateMaturityDateRequest.maturityDate, - updateMaturityDateRequest.securityId, - ), + new UpdateMaturityDateCommand(updateMaturityDateRequest.maturityDate, updateMaturityDateRequest.securityId), ); expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.updateMaturityDate(updateMaturityDateRequest), - ).rejects.toThrow('Command execution failed'); + await expect(BondToken.updateMaturityDate(updateMaturityDateRequest)).rejects.toThrow("Command execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'UpdateMaturityDateRequest', - updateMaturityDateRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("UpdateMaturityDateRequest", updateMaturityDateRequest); expect(commandBusMock.execute).toHaveBeenCalledWith( - new UpdateMaturityDateCommand( - updateMaturityDateRequest.maturityDate, - updateMaturityDateRequest.securityId, - ), + new UpdateMaturityDateCommand(updateMaturityDateRequest.maturityDate, updateMaturityDateRequest.securityId), ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { updateMaturityDateRequest = new UpdateMaturityDateRequest({ ...UpdateMaturityDateRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.updateMaturityDate(updateMaturityDateRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.updateMaturityDate(updateMaturityDateRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if maturityDate is invalid', async () => { + it("should throw error if maturityDate is invalid", async () => { updateMaturityDateRequest = new UpdateMaturityDateRequest({ ...UpdateMaturityDateRequestFixture.create(), - maturityDate: '-1', + maturityDate: "-1", }); - await expect( - BondToken.updateMaturityDate(updateMaturityDateRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.updateMaturityDate(updateMaturityDateRequest)).rejects.toThrow(ValidationError); }); }); - describe('redeemAtMaturityByPartition', () => { + describe("redeemAtMaturityByPartition", () => { redeemAtMaturityByPartitionRequest = new RedeemAtMaturityByPartitionRequest( RedeemAtMaturityByPartitionRequestFixture.create(), ); - it('should redeem at maturity by partition successfully', async () => { + it("should redeem at maturity by partition successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -1177,9 +958,7 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ); + const result = await BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest); expect(handleValidationSpy).toHaveBeenCalledWith( RedeemAtMaturityByPartitionRequest.name, @@ -1200,15 +979,13 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ), - ).rejects.toThrow('Command execution failed'); + await expect(BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest)).rejects.toThrow( + "Command execution failed", + ); expect(handleValidationSpy).toHaveBeenCalledWith( RedeemAtMaturityByPartitionRequest.name, @@ -1225,67 +1002,53 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { - redeemAtMaturityByPartitionRequest = - new RedeemAtMaturityByPartitionRequest({ - ...RedeemAtMaturityByPartitionRequestFixture.create(), - securityId: 'invalid', - }); + it("should throw error if securityId is invalid", async () => { + redeemAtMaturityByPartitionRequest = new RedeemAtMaturityByPartitionRequest({ + ...RedeemAtMaturityByPartitionRequestFixture.create(), + securityId: "invalid", + }); - await expect( - BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ), - ).rejects.toThrow(ValidationError); + await expect(BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest)).rejects.toThrow( + ValidationError, + ); }); - it('should throw error if partitionId is invalid', async () => { - redeemAtMaturityByPartitionRequest = - new RedeemAtMaturityByPartitionRequest({ - ...RedeemAtMaturityByPartitionRequestFixture.create(), - partitionId: 'invalid', - }); + it("should throw error if partitionId is invalid", async () => { + redeemAtMaturityByPartitionRequest = new RedeemAtMaturityByPartitionRequest({ + ...RedeemAtMaturityByPartitionRequestFixture.create(), + partitionId: "invalid", + }); - await expect( - BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ), - ).rejects.toThrow(ValidationError); + await expect(BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest)).rejects.toThrow( + ValidationError, + ); }); - it('should throw error if sourceId is invalid', async () => { - redeemAtMaturityByPartitionRequest = - new RedeemAtMaturityByPartitionRequest({ - ...RedeemAtMaturityByPartitionRequestFixture.create(), - sourceId: 'invalid', - }); + it("should throw error if sourceId is invalid", async () => { + redeemAtMaturityByPartitionRequest = new RedeemAtMaturityByPartitionRequest({ + ...RedeemAtMaturityByPartitionRequestFixture.create(), + sourceId: "invalid", + }); - await expect( - BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ), - ).rejects.toThrow(ValidationError); - }); - it('should throw error if amount is invalid', async () => { - redeemAtMaturityByPartitionRequest = - new RedeemAtMaturityByPartitionRequest({ - ...RedeemAtMaturityByPartitionRequestFixture.create(), - amount: 'invalid', - }); - - await expect( - BondToken.redeemAtMaturityByPartition( - redeemAtMaturityByPartitionRequest, - ), - ).rejects.toThrow(ValidationError); + await expect(BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest)).rejects.toThrow( + ValidationError, + ); + }); + it("should throw error if amount is invalid", async () => { + redeemAtMaturityByPartitionRequest = new RedeemAtMaturityByPartitionRequest({ + ...RedeemAtMaturityByPartitionRequestFixture.create(), + amount: "invalid", + }); + + await expect(BondToken.redeemAtMaturityByPartition(redeemAtMaturityByPartitionRequest)).rejects.toThrow( + ValidationError, + ); }); }); - describe('fullRedeemAtMaturity', () => { - fullRedeemAtMaturityRequest = new FullRedeemAtMaturityRequest( - FullRedeemAtMaturityRequestFixture.create(), - ); - it('should redeem at maturity successfully', async () => { + describe("fullRedeemAtMaturity", () => { + fullRedeemAtMaturityRequest = new FullRedeemAtMaturityRequest(FullRedeemAtMaturityRequestFixture.create()); + it("should redeem at maturity successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -1293,85 +1056,56 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.fullRedeemAtMaturity( - fullRedeemAtMaturityRequest, - ); + const result = await BondToken.fullRedeemAtMaturity(fullRedeemAtMaturityRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - FullRedeemAtMaturityRequest.name, - fullRedeemAtMaturityRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith(FullRedeemAtMaturityRequest.name, fullRedeemAtMaturityRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); expect(commandBusMock.execute).toHaveBeenCalledWith( - new FullRedeemAtMaturityCommand( - fullRedeemAtMaturityRequest.securityId, - fullRedeemAtMaturityRequest.sourceId, - ), + new FullRedeemAtMaturityCommand(fullRedeemAtMaturityRequest.securityId, fullRedeemAtMaturityRequest.sourceId), ); expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.fullRedeemAtMaturity( - fullRedeemAtMaturityRequest, - ), - ).rejects.toThrow('Command execution failed'); - - expect(handleValidationSpy).toHaveBeenCalledWith( - FullRedeemAtMaturityRequest.name, - fullRedeemAtMaturityRequest, + await expect(BondToken.fullRedeemAtMaturity(fullRedeemAtMaturityRequest)).rejects.toThrow( + "Command execution failed", ); + expect(handleValidationSpy).toHaveBeenCalledWith(FullRedeemAtMaturityRequest.name, fullRedeemAtMaturityRequest); + expect(commandBusMock.execute).toHaveBeenCalledWith( - new FullRedeemAtMaturityCommand( - fullRedeemAtMaturityRequest.securityId, - fullRedeemAtMaturityRequest.sourceId, - ), + new FullRedeemAtMaturityCommand(fullRedeemAtMaturityRequest.securityId, fullRedeemAtMaturityRequest.sourceId), ); }); - it('should throw error if securityId is invalid', async () => { - fullRedeemAtMaturityRequest = - new FullRedeemAtMaturityRequest({ - ...FullRedeemAtMaturityRequestFixture.create(), - securityId: 'invalid', - }); + it("should throw error if securityId is invalid", async () => { + fullRedeemAtMaturityRequest = new FullRedeemAtMaturityRequest({ + ...FullRedeemAtMaturityRequestFixture.create(), + securityId: "invalid", + }); - await expect( - BondToken.fullRedeemAtMaturity( - fullRedeemAtMaturityRequest, - ), - ).rejects.toThrow(ValidationError); + await expect(BondToken.fullRedeemAtMaturity(fullRedeemAtMaturityRequest)).rejects.toThrow(ValidationError); }); + it("should throw error if sourceId is invalid", async () => { + fullRedeemAtMaturityRequest = new FullRedeemAtMaturityRequest({ + ...FullRedeemAtMaturityRequestFixture.create(), + sourceId: "invalid", + }); - it('should throw error if sourceId is invalid', async () => { - fullRedeemAtMaturityRequest = - new FullRedeemAtMaturityRequest({ - ...FullRedeemAtMaturityRequestFixture.create(), - sourceId: 'invalid', - }); - - await expect( - BondToken.fullRedeemAtMaturity( - fullRedeemAtMaturityRequest, - ), - ).rejects.toThrow(ValidationError); + await expect(BondToken.fullRedeemAtMaturity(fullRedeemAtMaturityRequest)).rejects.toThrow(ValidationError); }); }); - describe('getCouponHolders', () => { - getCouponHoldersRequest = new GetCouponHoldersRequest( - GetCouponHoldersQueryFixture.create(), - ); - it('should get coupon holders successfully', async () => { + describe("getCouponHolders", () => { + getCouponHoldersRequest = new GetCouponHoldersRequest(GetCouponHoldersQueryFixture.create()); + it("should get coupon holders successfully", async () => { const expectedResponse = { payload: [transactionId], }; @@ -1380,10 +1114,7 @@ describe('Bond', () => { const result = await BondToken.getCouponHolders(getCouponHoldersRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - GetCouponHoldersRequest.name, - getCouponHoldersRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith(GetCouponHoldersRequest.name, getCouponHoldersRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -1399,18 +1130,13 @@ describe('Bond', () => { expect(result).toStrictEqual(expectedResponse.payload); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getCouponHolders(getCouponHoldersRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getCouponHolders(getCouponHoldersRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - GetCouponHoldersRequest.name, - getCouponHoldersRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith(GetCouponHoldersRequest.name, getCouponHoldersRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -1424,133 +1150,103 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getCouponHoldersRequest = new GetCouponHoldersRequest({ ...GetCouponHoldersQueryFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.getCouponHolders(getCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponHolders(getCouponHoldersRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if couponId is invalid', async () => { + it("should throw error if couponId is invalid", async () => { getCouponHoldersRequest = new GetCouponHoldersRequest({ ...GetCouponHoldersQueryFixture.create(), couponId: -1, }); - await expect( - BondToken.getCouponHolders(getCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponHolders(getCouponHoldersRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if start is invalid', async () => { + it("should throw error if start is invalid", async () => { getCouponHoldersRequest = new GetCouponHoldersRequest({ ...GetCouponHoldersQueryFixture.create(), start: -1, }); - await expect( - BondToken.getCouponHolders(getCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponHolders(getCouponHoldersRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if end is invalid', async () => { + it("should throw error if end is invalid", async () => { getCouponHoldersRequest = new GetCouponHoldersRequest({ ...GetCouponHoldersQueryFixture.create(), end: -1, }); - await expect( - BondToken.getCouponHolders(getCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getCouponHolders(getCouponHoldersRequest)).rejects.toThrow(ValidationError); }); }); - describe('getTotalCouponHolders', () => { - getTotalCouponHoldersRequest = new GetTotalCouponHoldersRequest( - GetTotalCouponHoldersRequestFixture.create(), - ); - it('should get total coupon holders successfully', async () => { + describe("getTotalCouponHolders", () => { + getTotalCouponHoldersRequest = new GetTotalCouponHoldersRequest(GetTotalCouponHoldersRequestFixture.create()); + it("should get total coupon holders successfully", async () => { const expectedResponse = { payload: 1, }; queryBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.getTotalCouponHolders( - getTotalCouponHoldersRequest, - ); + const result = await BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - GetTotalCouponHoldersRequest.name, - getTotalCouponHoldersRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith(GetTotalCouponHoldersRequest.name, getTotalCouponHoldersRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetTotalCouponHoldersQuery( - getTotalCouponHoldersRequest.securityId, - getTotalCouponHoldersRequest.couponId, - ), + new GetTotalCouponHoldersQuery(getTotalCouponHoldersRequest.securityId, getTotalCouponHoldersRequest.couponId), ); expect(result).toEqual(expectedResponse.payload); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest), - ).rejects.toThrow('Query execution failed'); - - expect(handleValidationSpy).toHaveBeenCalledWith( - GetTotalCouponHoldersRequest.name, - getTotalCouponHoldersRequest, + await expect(BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest)).rejects.toThrow( + "Query execution failed", ); + expect(handleValidationSpy).toHaveBeenCalledWith(GetTotalCouponHoldersRequest.name, getTotalCouponHoldersRequest); + expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetTotalCouponHoldersQuery( - getTotalCouponHoldersRequest.securityId, - getTotalCouponHoldersRequest.couponId, - ), + new GetTotalCouponHoldersQuery(getTotalCouponHoldersRequest.securityId, getTotalCouponHoldersRequest.couponId), ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { getTotalCouponHoldersRequest = new GetTotalCouponHoldersRequest({ ...GetTotalCouponHoldersRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if couponId is invalid', async () => { + it("should throw error if couponId is invalid", async () => { getTotalCouponHoldersRequest = new GetTotalCouponHoldersRequest({ ...GetTotalCouponHoldersRequestFixture.create(), couponId: -1, }); - await expect( - BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getTotalCouponHolders(getTotalCouponHoldersRequest)).rejects.toThrow(ValidationError); }); }); - describe('createTrexSuite', () => { - createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( - CreateTrexSuiteBondRequestFixture.create(), - ); - it('should create successfully', async () => { + describe("createTrexSuite", () => { + createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest(CreateTrexSuiteBondRequestFixture.create()); + it("should create successfully", async () => { const expectedResponse = { securityId: new ContractId(HederaIdPropsFixture.create().value), transactionId: transactionId, @@ -1561,14 +1257,9 @@ describe('Bond', () => { security: security, }); - const result = await BondToken.createTrexSuite( - createTrexSuiteBondRequest, - ); + const result = await BondToken.createTrexSuite(createTrexSuiteBondRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'CreateTrexSuiteBondRequest', - createTrexSuiteBondRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("CreateTrexSuiteBondRequest", createTrexSuiteBondRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -1593,23 +1284,14 @@ describe('Bond', () => { decimals: createTrexSuiteBondRequest.decimals, isWhiteList: createTrexSuiteBondRequest.isWhiteList, isControllable: createTrexSuiteBondRequest.isControllable, - arePartitionsProtected: - createTrexSuiteBondRequest.arePartitionsProtected, + arePartitionsProtected: createTrexSuiteBondRequest.arePartitionsProtected, clearingActive: createTrexSuiteBondRequest.clearingActive, - internalKycActivated: - createTrexSuiteBondRequest.internalKycActivated, + internalKycActivated: createTrexSuiteBondRequest.internalKycActivated, isMultiPartition: createTrexSuiteBondRequest.isMultiPartition, - maxSupply: BigDecimal.fromString( - createTrexSuiteBondRequest.numberOfUnits, - ), - regulationType: CastRegulationType.fromNumber( - createTrexSuiteBondRequest.regulationType, - ), - regulationsubType: CastRegulationSubType.fromNumber( - createTrexSuiteBondRequest.regulationSubType, - ), - isCountryControlListWhiteList: - createTrexSuiteBondRequest.isCountryControlListWhiteList, + maxSupply: BigDecimal.fromString(createTrexSuiteBondRequest.numberOfUnits), + regulationType: CastRegulationType.fromNumber(createTrexSuiteBondRequest.regulationType), + regulationsubType: CastRegulationSubType.fromNumber(createTrexSuiteBondRequest.regulationSubType), + isCountryControlListWhiteList: createTrexSuiteBondRequest.isCountryControlListWhiteList, countries: createTrexSuiteBondRequest.countries, info: createTrexSuiteBondRequest.info, }), @@ -1641,18 +1323,13 @@ describe('Bond', () => { ); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow('Command execution failed'); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow("Command execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'CreateTrexSuiteBondRequest', - createTrexSuiteBondRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("CreateTrexSuiteBondRequest", createTrexSuiteBondRequest); expect(commandBusMock.execute).toHaveBeenCalledWith( new CreateTrexSuiteBondCommand( @@ -1674,23 +1351,14 @@ describe('Bond', () => { decimals: createTrexSuiteBondRequest.decimals, isWhiteList: createTrexSuiteBondRequest.isWhiteList, isControllable: createTrexSuiteBondRequest.isControllable, - arePartitionsProtected: - createTrexSuiteBondRequest.arePartitionsProtected, + arePartitionsProtected: createTrexSuiteBondRequest.arePartitionsProtected, clearingActive: createTrexSuiteBondRequest.clearingActive, - internalKycActivated: - createTrexSuiteBondRequest.internalKycActivated, + internalKycActivated: createTrexSuiteBondRequest.internalKycActivated, isMultiPartition: createTrexSuiteBondRequest.isMultiPartition, - maxSupply: BigDecimal.fromString( - createTrexSuiteBondRequest.numberOfUnits, - ), - regulationType: CastRegulationType.fromNumber( - createTrexSuiteBondRequest.regulationType, - ), - regulationsubType: CastRegulationSubType.fromNumber( - createTrexSuiteBondRequest.regulationSubType, - ), - isCountryControlListWhiteList: - createTrexSuiteBondRequest.isCountryControlListWhiteList, + maxSupply: BigDecimal.fromString(createTrexSuiteBondRequest.numberOfUnits), + regulationType: CastRegulationType.fromNumber(createTrexSuiteBondRequest.regulationType), + regulationsubType: CastRegulationSubType.fromNumber(createTrexSuiteBondRequest.regulationSubType), + isCountryControlListWhiteList: createTrexSuiteBondRequest.isCountryControlListWhiteList, countries: createTrexSuiteBondRequest.countries, info: createTrexSuiteBondRequest.info, }), @@ -1715,101 +1383,85 @@ describe('Bond', () => { ); }); - it('should throw error if name is invalid', async () => { + it("should throw error if name is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( - CreateTrexSuiteBondRequestFixture.create({ name: '' }), + CreateTrexSuiteBondRequestFixture.create({ name: "" }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if symbol is invalid', async () => { + it("should throw error if symbol is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - symbol: '', + symbol: "", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if isin is invalid', async () => { + it("should throw error if isin is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - isin: '', + isin: "", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if decimals is invalid', async () => { + it("should throw error if decimals is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ decimals: 2.85, }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if diamondOwnerAccount is invalid', async () => { + it("should throw error if diamondOwnerAccount is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - diamondOwnerAccount: 'invalid', + diamondOwnerAccount: "invalid", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if currency is invalid', async () => { + it("should throw error if currency is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - currency: 'invalid', + currency: "invalid", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if numberOfUnits is invalid', async () => { + it("should throw error if numberOfUnits is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - numberOfUnits: 'invalid', + numberOfUnits: "invalid", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if nominalValue is invalid', async () => { + it("should throw error if nominalValue is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - nominalValue: 'invalid', + nominalValue: "invalid", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if startingDate is invalid', async () => { + it("should throw error if startingDate is invalid", async () => { const time = Math.floor(faker.date.past().getTime() / 1000); createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ @@ -1818,91 +1470,73 @@ describe('Bond', () => { }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if maturityDate is invalid', async () => { + it("should throw error if maturityDate is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - maturityDate: Math.floor( - faker.date.past().getTime() / 1000, - ).toString(), + maturityDate: Math.floor(faker.date.past().getTime() / 1000).toString(), }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if regulationSubType is invalid', async () => { + it("should throw error if regulationSubType is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ regulationSubType: 5, }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if configId is invalid', async () => { + it("should throw error if configId is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - configId: 'invalid', + configId: "invalid", }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalPauses is invalid', async () => { + it("should throw error if externalPauses is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - externalPauses: ['invalid'], + externalPauses: ["invalid"], }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalControlLists is invalid', async () => { + it("should throw error if externalControlLists is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - externalControlLists: ['invalid'], + externalControlLists: ["invalid"], }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if externalKycLists is invalid', async () => { + it("should throw error if externalKycLists is invalid", async () => { createTrexSuiteBondRequest = new CreateTrexSuiteBondRequest( CreateTrexSuiteBondRequestFixture.create({ - externalKycLists: ['invalid'], + externalKycLists: ["invalid"], }), ); - await expect( - BondToken.createTrexSuite(createTrexSuiteBondRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.createTrexSuite(createTrexSuiteBondRequest)).rejects.toThrow(ValidationError); }); }); - describe('AddProceedRecipientRequest', () => { - const addProceedRecipientRequest = new AddProceedRecipientRequest( - AddProceedRecipientRequestFixture.create(), - ); - it('should add proceed recipient successfully', async () => { + describe("AddProceedRecipientRequest", () => { + const addProceedRecipientRequest = new AddProceedRecipientRequest(AddProceedRecipientRequestFixture.create()); + it("should add proceed recipient successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -1910,14 +1544,9 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.addProceedRecipient( - addProceedRecipientRequest, - ); + const result = await BondToken.addProceedRecipient(addProceedRecipientRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'AddProceedRecipientRequest', - addProceedRecipientRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("AddProceedRecipientRequest", addProceedRecipientRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); @@ -1932,19 +1561,16 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.addProceedRecipient(addProceedRecipientRequest), - ).rejects.toThrow('Command execution failed'); - - expect(handleValidationSpy).toHaveBeenCalledWith( - 'AddProceedRecipientRequest', - addProceedRecipientRequest, + await expect(BondToken.addProceedRecipient(addProceedRecipientRequest)).rejects.toThrow( + "Command execution failed", ); + expect(handleValidationSpy).toHaveBeenCalledWith("AddProceedRecipientRequest", addProceedRecipientRequest); + expect(commandBusMock.execute).toHaveBeenCalledWith( new AddProceedRecipientCommand( addProceedRecipientRequest.securityId, @@ -1954,45 +1580,39 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { let addProceedRecipientRequest = new AddProceedRecipientRequest({ ...AddProceedRecipientRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.addProceedRecipient(addProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.addProceedRecipient(addProceedRecipientRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if data is invalid', async () => { + it("should throw error if data is invalid", async () => { let addProceedRecipientRequest = new AddProceedRecipientRequest({ ...AddProceedRecipientRequestFixture.create(), - data: 'invalid', + data: "invalid", }); - await expect( - BondToken.addProceedRecipient(addProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.addProceedRecipient(addProceedRecipientRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if proceedRecipientId is invalid', async () => { + it("should throw error if proceedRecipientId is invalid", async () => { let addProceedRecipientRequest = new AddProceedRecipientRequest({ ...AddProceedRecipientRequestFixture.create(), - proceedRecipientId: 'invalid', + proceedRecipientId: "invalid", }); - await expect( - BondToken.addProceedRecipient(addProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.addProceedRecipient(addProceedRecipientRequest)).rejects.toThrow(ValidationError); }); }); - describe('RemoveProceedRecipientRequest', () => { + describe("RemoveProceedRecipientRequest", () => { const removeProceedRecipientRequest = new RemoveProceedRecipientRequest( RemoveProceedRecipientRequestFixture.create(), ); - it('should remove proceed recipient successfully', async () => { + it("should remove proceed recipient successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2000,14 +1620,9 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.removeProceedRecipient( - removeProceedRecipientRequest, - ); + const result = await BondToken.removeProceedRecipient(removeProceedRecipientRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'RemoveProceedRecipientRequest', - removeProceedRecipientRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("RemoveProceedRecipientRequest", removeProceedRecipientRequest); expect(commandBusMock.execute).toHaveBeenCalledTimes(1); @@ -2021,19 +1636,16 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.removeProceedRecipient(removeProceedRecipientRequest), - ).rejects.toThrow('Command execution failed'); - - expect(handleValidationSpy).toHaveBeenCalledWith( - 'RemoveProceedRecipientRequest', - removeProceedRecipientRequest, + await expect(BondToken.removeProceedRecipient(removeProceedRecipientRequest)).rejects.toThrow( + "Command execution failed", ); + expect(handleValidationSpy).toHaveBeenCalledWith("RemoveProceedRecipientRequest", removeProceedRecipientRequest); + expect(commandBusMock.execute).toHaveBeenCalledWith( new RemoveProceedRecipientCommand( removeProceedRecipientRequest.securityId, @@ -2042,35 +1654,30 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { let removeProceedRecipientRequest = new RemoveProceedRecipientRequest({ ...RemoveProceedRecipientRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.removeProceedRecipient(removeProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.removeProceedRecipient(removeProceedRecipientRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if proceedRecipientId is invalid', async () => { + it("should throw error if proceedRecipientId is invalid", async () => { let removeProceedRecipientRequest = new RemoveProceedRecipientRequest({ ...RemoveProceedRecipientRequestFixture.create(), - proceedRecipientId: 'invalid', + proceedRecipientId: "invalid", }); - await expect( - BondToken.removeProceedRecipient(removeProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.removeProceedRecipient(removeProceedRecipientRequest)).rejects.toThrow(ValidationError); }); }); - describe('UpdateProceedRecipientDataRequest', () => { - const updateProceedRecipientDataRequest = - new UpdateProceedRecipientDataRequest( - UpdateProceedRecipientDataRequestFixture.create(), - ); - it('should update proceed recipient data successfully', async () => { + describe("UpdateProceedRecipientDataRequest", () => { + const updateProceedRecipientDataRequest = new UpdateProceedRecipientDataRequest( + UpdateProceedRecipientDataRequestFixture.create(), + ); + it("should update proceed recipient data successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2078,12 +1685,10 @@ describe('Bond', () => { commandBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.updateProceedRecipientData( - updateProceedRecipientDataRequest, - ); + const result = await BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest); expect(handleValidationSpy).toHaveBeenCalledWith( - 'UpdateProceedRecipientDataRequest', + "UpdateProceedRecipientDataRequest", updateProceedRecipientDataRequest, ); @@ -2100,16 +1705,16 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if command execution fails', async () => { - const error = new Error('Command execution failed'); + it("should throw an error if command execution fails", async () => { + const error = new Error("Command execution failed"); commandBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest), - ).rejects.toThrow('Command execution failed'); + await expect(BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest)).rejects.toThrow( + "Command execution failed", + ); expect(handleValidationSpy).toHaveBeenCalledWith( - 'UpdateProceedRecipientDataRequest', + "UpdateProceedRecipientDataRequest", updateProceedRecipientDataRequest, ); @@ -2122,48 +1727,43 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { - let updateProceedRecipientDataRequest = - new UpdateProceedRecipientDataRequest({ - ...UpdateProceedRecipientDataRequestFixture.create(), - securityId: 'invalid', - }); + it("should throw error if securityId is invalid", async () => { + let updateProceedRecipientDataRequest = new UpdateProceedRecipientDataRequest({ + ...UpdateProceedRecipientDataRequestFixture.create(), + securityId: "invalid", + }); - await expect( - BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest)).rejects.toThrow( + ValidationError, + ); }); - it('should throw error if data is invalid', async () => { - let updateProceedRecipientDataRequest = - new UpdateProceedRecipientDataRequest({ - ...UpdateProceedRecipientDataRequestFixture.create(), - data: 'invalid', - }); + it("should throw error if data is invalid", async () => { + let updateProceedRecipientDataRequest = new UpdateProceedRecipientDataRequest({ + ...UpdateProceedRecipientDataRequestFixture.create(), + data: "invalid", + }); - await expect( - BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest)).rejects.toThrow( + ValidationError, + ); }); - it('should throw error if proceedRecipientId is invalid', async () => { - let updateProceedRecipientDataRequest = - new UpdateProceedRecipientDataRequest({ - ...UpdateProceedRecipientDataRequestFixture.create(), - proceedRecipientId: 'invalid', - }); + it("should throw error if proceedRecipientId is invalid", async () => { + let updateProceedRecipientDataRequest = new UpdateProceedRecipientDataRequest({ + ...UpdateProceedRecipientDataRequestFixture.create(), + proceedRecipientId: "invalid", + }); - await expect( - BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.updateProceedRecipientData(updateProceedRecipientDataRequest)).rejects.toThrow( + ValidationError, + ); }); }); - describe('IsProceedRecipientRequest', () => { - const isProceedRecipientRequest = new IsProceedRecipientRequest( - IsProceedRecipientRequestFixture.create(), - ); - it('should get isProceedRecipient successfully', async () => { + describe("IsProceedRecipientRequest", () => { + const isProceedRecipientRequest = new IsProceedRecipientRequest(IsProceedRecipientRequestFixture.create()); + it("should get isProceedRecipient successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2171,77 +1771,56 @@ describe('Bond', () => { queryBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.isProceedRecipient( - isProceedRecipientRequest, - ); + const result = await BondToken.isProceedRecipient(isProceedRecipientRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'IsProceedRecipientRequest', - isProceedRecipientRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("IsProceedRecipientRequest", isProceedRecipientRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new IsProceedRecipientQuery( - isProceedRecipientRequest.securityId, - isProceedRecipientRequest.proceedRecipientId, - ), + new IsProceedRecipientQuery(isProceedRecipientRequest.securityId, isProceedRecipientRequest.proceedRecipientId), ); expect(result).toEqual(expectedResponse); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.isProceedRecipient(isProceedRecipientRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.isProceedRecipient(isProceedRecipientRequest)).rejects.toThrow("Query execution failed"); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'IsProceedRecipientRequest', - isProceedRecipientRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("IsProceedRecipientRequest", isProceedRecipientRequest); expect(queryBusMock.execute).toHaveBeenCalledWith( - new IsProceedRecipientQuery( - isProceedRecipientRequest.securityId, - isProceedRecipientRequest.proceedRecipientId, - ), + new IsProceedRecipientQuery(isProceedRecipientRequest.securityId, isProceedRecipientRequest.proceedRecipientId), ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { let isProceedRecipientRequest = new IsProceedRecipientRequest({ ...AddProceedRecipientRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.isProceedRecipient(isProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.isProceedRecipient(isProceedRecipientRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if proceedRecipientId is invalid', async () => { + it("should throw error if proceedRecipientId is invalid", async () => { let isProceedRecipientRequest = new IsProceedRecipientRequest({ ...AddProceedRecipientRequestFixture.create(), - proceedRecipientId: 'invalid', + proceedRecipientId: "invalid", }); - await expect( - BondToken.isProceedRecipient(isProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.isProceedRecipient(isProceedRecipientRequest)).rejects.toThrow(ValidationError); }); }); - describe('GetProceedRecipientsCountRequest', () => { - const getProceedRecipientsCountRequest = - new GetProceedRecipientsCountRequest( - GetProceedRecipientsCountRequestFixture.create(), - ); - it('should get proceedRecipients count successfully', async () => { + describe("GetProceedRecipientsCountRequest", () => { + const getProceedRecipientsCountRequest = new GetProceedRecipientsCountRequest( + GetProceedRecipientsCountRequestFixture.create(), + ); + it("should get proceedRecipients count successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2249,64 +1828,57 @@ describe('Bond', () => { queryBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.getProceedRecipientsCount( - getProceedRecipientsCountRequest, - ); + const result = await BondToken.getProceedRecipientsCount(getProceedRecipientsCountRequest); expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientsCountRequest', + "GetProceedRecipientsCountRequest", getProceedRecipientsCountRequest, ); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetProceedRecipientsCountQuery( - getProceedRecipientsCountRequest.securityId, - ), + new GetProceedRecipientsCountQuery(getProceedRecipientsCountRequest.securityId), ); expect(result).toEqual(expectedResponse); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getProceedRecipientsCount(getProceedRecipientsCountRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getProceedRecipientsCount(getProceedRecipientsCountRequest)).rejects.toThrow( + "Query execution failed", + ); expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientsCountRequest', + "GetProceedRecipientsCountRequest", getProceedRecipientsCountRequest, ); expect(queryBusMock.execute).toHaveBeenCalledWith( - new GetProceedRecipientsCountQuery( - getProceedRecipientsCountRequest.securityId, - ), + new GetProceedRecipientsCountQuery(getProceedRecipientsCountRequest.securityId), ); }); - it('should throw error if securityId is invalid', async () => { - let getProceedRecipientsCountRequest = - new GetProceedRecipientsCountRequest({ - ...AddProceedRecipientRequestFixture.create(), - securityId: 'invalid', - }); + it("should throw error if securityId is invalid", async () => { + let getProceedRecipientsCountRequest = new GetProceedRecipientsCountRequest({ + ...AddProceedRecipientRequestFixture.create(), + securityId: "invalid", + }); - await expect( - BondToken.getProceedRecipientsCount(getProceedRecipientsCountRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getProceedRecipientsCount(getProceedRecipientsCountRequest)).rejects.toThrow( + ValidationError, + ); }); }); - describe('GetProceedRecipientDataRequest', () => { + describe("GetProceedRecipientDataRequest", () => { const getProceedRecipientDataRequest = new GetProceedRecipientDataRequest( GetProceedRecipientDataRequestFixture.create(), ); - it('should get proceed recipient data successfully', async () => { + it("should get proceed recipient data successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2314,12 +1886,10 @@ describe('Bond', () => { queryBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.getProceedRecipientData( - getProceedRecipientDataRequest, - ); + const result = await BondToken.getProceedRecipientData(getProceedRecipientDataRequest); expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientDataRequest', + "GetProceedRecipientDataRequest", getProceedRecipientDataRequest, ); @@ -2335,16 +1905,16 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getProceedRecipientData(getProceedRecipientDataRequest), - ).rejects.toThrow('Query execution failed'); + await expect(BondToken.getProceedRecipientData(getProceedRecipientDataRequest)).rejects.toThrow( + "Query execution failed", + ); expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientDataRequest', + "GetProceedRecipientDataRequest", getProceedRecipientDataRequest, ); @@ -2356,34 +1926,28 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { let isProceedRecipientRequest = new GetProceedRecipientDataRequest({ ...AddProceedRecipientRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.isProceedRecipient(isProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.isProceedRecipient(isProceedRecipientRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if proceedRecipientId is invalid', async () => { + it("should throw error if proceedRecipientId is invalid", async () => { let isProceedRecipientRequest = new GetProceedRecipientDataRequest({ ...AddProceedRecipientRequestFixture.create(), - proceedRecipientId: 'invalid', + proceedRecipientId: "invalid", }); - await expect( - BondToken.isProceedRecipient(isProceedRecipientRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.isProceedRecipient(isProceedRecipientRequest)).rejects.toThrow(ValidationError); }); }); - describe('GetProceedRecipientsRequest', () => { - const getProceedRecipientsRequest = new GetProceedRecipientsRequest( - GetProceedRecipientsRequestFixture.create(), - ); - it('should get proceedRecipients successfully', async () => { + describe("GetProceedRecipientsRequest", () => { + const getProceedRecipientsRequest = new GetProceedRecipientsRequest(GetProceedRecipientsRequestFixture.create()); + it("should get proceedRecipients successfully", async () => { const expectedResponse = { payload: true, transactionId: transactionId, @@ -2391,14 +1955,9 @@ describe('Bond', () => { queryBusMock.execute.mockResolvedValue(expectedResponse); - const result = await BondToken.getProceedRecipients( - getProceedRecipientsRequest, - ); + const result = await BondToken.getProceedRecipients(getProceedRecipientsRequest); - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientsRequest', - getProceedRecipientsRequest, - ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetProceedRecipientsRequest", getProceedRecipientsRequest); expect(queryBusMock.execute).toHaveBeenCalledTimes(1); @@ -2413,19 +1972,16 @@ describe('Bond', () => { expect(result).toEqual(expectedResponse); }); - it('should throw an error if query execution fails', async () => { - const error = new Error('Query execution failed'); + it("should throw an error if query execution fails", async () => { + const error = new Error("Query execution failed"); queryBusMock.execute.mockRejectedValue(error); - await expect( - BondToken.getProceedRecipients(getProceedRecipientsRequest), - ).rejects.toThrow('Query execution failed'); - - expect(handleValidationSpy).toHaveBeenCalledWith( - 'GetProceedRecipientsRequest', - getProceedRecipientsRequest, + await expect(BondToken.getProceedRecipients(getProceedRecipientsRequest)).rejects.toThrow( + "Query execution failed", ); + expect(handleValidationSpy).toHaveBeenCalledWith("GetProceedRecipientsRequest", getProceedRecipientsRequest); + expect(queryBusMock.execute).toHaveBeenCalledWith( new GetProceedRecipientsQuery( getProceedRecipientsRequest.securityId, @@ -2435,26 +1991,22 @@ describe('Bond', () => { ); }); - it('should throw error if securityId is invalid', async () => { + it("should throw error if securityId is invalid", async () => { let getProceedRecipientsRequest = new GetProceedRecipientsRequest({ ...GetProceedRecipientsRequestFixture.create(), - securityId: 'invalid', + securityId: "invalid", }); - await expect( - BondToken.getProceedRecipients(getProceedRecipientsRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getProceedRecipients(getProceedRecipientsRequest)).rejects.toThrow(ValidationError); }); - it('should throw error if page size is invalid', async () => { + it("should throw error if page size is invalid", async () => { let getProceedRecipientsRequest = new GetProceedRecipientsRequest({ ...GetProceedRecipientsRequestFixture.create(), pageSize: -1, }); - await expect( - BondToken.getProceedRecipients(getProceedRecipientsRequest), - ).rejects.toThrow(ValidationError); + await expect(BondToken.getProceedRecipients(getProceedRecipientsRequest)).rejects.toThrow(ValidationError); }); }); }); diff --git a/packages/ats/sdk/src/port/in/response/CouponForViewModel.ts b/packages/ats/sdk/src/port/in/response/CouponForViewModel.ts index fd56df2fd..e7a60affb 100644 --- a/packages/ats/sdk/src/port/in/response/CouponForViewModel.ts +++ b/packages/ats/sdk/src/port/in/response/CouponForViewModel.ts @@ -1,210 +1,8 @@ -/* - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +// SPDX-License-Identifier: Apache-2.0 - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -import { QueryResponse } from '@core/query/QueryResponse'; +import { QueryResponse } from "@core/query/QueryResponse"; export default interface CouponForViewModel extends QueryResponse { - value: string; + tokenBalance: string; + decimals: string; } diff --git a/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts b/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts index 2207b4e72..554bc519c 100644 --- a/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts +++ b/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts @@ -293,6 +293,7 @@ import { HoldDetails } from '@domain/context/security/Hold'; import { CouponAmountFor } from '@domain/context/bond/CouponAmountFor'; import {PrincipalFor} from '@domain/context/bond/PrincipalFor'; import { DividendAmountFor } from '@domain/context/equity/DividendAmountFor'; +import { CouponFor } from '@domain/context/bond/CouponFor'; const LOCAL_JSON_RPC_RELAY_URL = 'http://127.0.0.1:7546/api'; @@ -854,7 +855,7 @@ export class RPCQueryAdapter { address: EvmAddress, target: EvmAddress, coupon: number, - ): Promise { + ): Promise { LogService.logTrace(`Getting Coupon for`); const couponFor = await this.connect( @@ -862,7 +863,10 @@ export class RPCQueryAdapter { address.toString(), ).getCouponFor(coupon, target.toString()); - return couponFor.tokenBalance; + return new CouponFor( + new BigDecimal(couponFor.tokenBalance), + couponFor.decimals, + ); } async getCouponAmountFor(