diff --git a/apps/ats/web/eslint.config.mjs b/apps/ats/web/eslint.config.mjs index 850fc97a4..20bed0850 100644 --- a/apps/ats/web/eslint.config.mjs +++ b/apps/ats/web/eslint.config.mjs @@ -52,4 +52,4 @@ const webConfig = baseConfig }, ]); -export default webConfig; \ No newline at end of file +export default webConfig; diff --git a/apps/ats/web/prettier.config.mjs b/apps/ats/web/prettier.config.mjs index 91bbee268..4810489f6 100644 --- a/apps/ats/web/prettier.config.mjs +++ b/apps/ats/web/prettier.config.mjs @@ -4,4 +4,4 @@ */ import baseConfig from '../../../prettier.config.mjs'; -export default baseConfig; \ No newline at end of file +export default baseConfig; diff --git a/apps/ats/web/src/hooks/mutations/useBeneficiaries.tsx b/apps/ats/web/src/hooks/mutations/useBeneficiaries.tsx new file mode 100644 index 000000000..d3716a380 --- /dev/null +++ b/apps/ats/web/src/hooks/mutations/useBeneficiaries.tsx @@ -0,0 +1,158 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import SDKService from '../../services/SDKService'; +import { + AddBeneficiaryRequest, + RemoveBeneficiaryRequest, + UpdateBeneficiaryDataRequest, +} from '@hashgraph/asset-tokenization-sdk'; +import { useToast } from 'io-bricks-ui'; +import { useTranslation } from 'react-i18next'; +import { GET_BENEFICIARY_LIST } from '../queries/useBeneficiaries'; + +export const useAddBeneficiary = () => { + const queryClient = useQueryClient(); + const toast = useToast(); + const { t } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.create.messages', + }); + + return useMutation( + (req: AddBeneficiaryRequest) => SDKService.addBeneficiary(req), + { + onSuccess(data, variables) { + queryClient.invalidateQueries({ + queryKey: [GET_BENEFICIARY_LIST(variables.securityId)], + }); + + console.log( + 'SDK message --> Add beneficiary operation success: ', + data, + ); + + if (!data) { + return; + } + + toast.show({ + duration: 3000, + title: t('success'), + description: t('descriptionSuccess'), + variant: 'subtle', + status: 'success', + }); + }, + onError: (error) => { + console.log('SDK message --> Add beneficiary operation error: ', error); + + toast.show({ + duration: 3000, + title: t('error'), + description: t('descriptionFailed'), + variant: 'subtle', + status: 'error', + }); + }, + }, + ); +}; + +export const useUpdateBeneficiary = () => { + const queryClient = useQueryClient(); + const toast = useToast(); + const { t } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.update.messages', + }); + + return useMutation( + (req: UpdateBeneficiaryDataRequest) => + SDKService.updateBeneficiaryData(req), + { + onSuccess(data, variables) { + queryClient.invalidateQueries({ + queryKey: [GET_BENEFICIARY_LIST(variables.securityId)], + }); + + console.log( + 'SDK message --> Update beneficiary operation success: ', + data, + ); + + if (!data) { + return; + } + + toast.show({ + duration: 3000, + title: t('success'), + description: t('descriptionSuccess'), + variant: 'subtle', + status: 'success', + }); + }, + onError: (error) => { + console.log( + 'SDK message --> Update beneficiary operation error: ', + error, + ); + + toast.show({ + duration: 3000, + title: t('error'), + description: t('descriptionFailed'), + variant: 'subtle', + status: 'error', + }); + }, + }, + ); +}; + +export const useRemoveBeneficiary = () => { + const queryClient = useQueryClient(); + const toast = useToast(); + const { t } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.remove.messages', + }); + + return useMutation( + (req: RemoveBeneficiaryRequest) => SDKService.removeBeneficiary(req), + { + onSuccess(data, variables) { + queryClient.invalidateQueries({ + queryKey: [GET_BENEFICIARY_LIST(variables.securityId)], + }); + + console.log( + 'SDK message --> Remove beneficiary operation success: ', + data, + ); + + if (!data) { + return; + } + + toast.show({ + duration: 3000, + title: t('success'), + description: t('descriptionSuccess'), + variant: 'subtle', + status: 'success', + }); + }, + onError: (error) => { + console.log( + 'SDK message --> Remove beneficiary operation error: ', + error, + ); + + toast.show({ + duration: 3000, + title: t('error'), + description: t('descriptionFailed'), + variant: 'subtle', + status: 'error', + }); + }, + }, + ); +}; diff --git a/apps/ats/web/src/hooks/queries/useBeneficiaries.ts b/apps/ats/web/src/hooks/queries/useBeneficiaries.ts new file mode 100644 index 000000000..ad97e096c --- /dev/null +++ b/apps/ats/web/src/hooks/queries/useBeneficiaries.ts @@ -0,0 +1,277 @@ +/* + 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 { useQuery, UseQueryOptions } from '@tanstack/react-query'; +import SDKService from '../../services/SDKService'; +import { + GetBeneficiariesCountRequest, + GetBeneficiariesRequest, + GetBeneficiaryDataRequest, +} from '@hashgraph/asset-tokenization-sdk'; + +export interface BeneficiaryDataViewModelResponse { + address: string; + data?: string; +} + +export const GET_BENEFICIARY_LIST = (securityId: string) => + `GET_BENEFICIARY_LIST_${securityId}`; + +export const IS_INTERNAL_BENEFICIARY_ACTIVATED = (securityId: string) => + `IS_INTERNAL_BENEFICIARY_ACTIVATED_${securityId}`; + +export const useGetBeneficiaryList = ( + request: GetBeneficiariesCountRequest, + options?: UseQueryOptions< + BeneficiaryDataViewModelResponse[], + unknown, + BeneficiaryDataViewModelResponse[], + string[] + >, +) => { + return useQuery( + [GET_BENEFICIARY_LIST(request.securityId)], + async () => { + try { + const beneficiariesCount = + await SDKService.getBeneficiariesCount(request); + + const beneficiaries = await SDKService.getBeneficiaries( + new GetBeneficiariesRequest({ + securityId: request.securityId, + pageIndex: 0, + pageSize: beneficiariesCount ?? 100, + }), + ); + + const beneficiariesWithData = await Promise.all( + beneficiaries.map(async (beneficiary) => { + try { + const data = await SDKService.getBeneficiaryData( + new GetBeneficiaryDataRequest({ + securityId: request.securityId, + beneficiaryId: beneficiary, + }), + ); + return { + address: beneficiary, + data, + } as BeneficiaryDataViewModelResponse; + } catch (error) { + console.error('Error fetching beneficiary data', error); + return { address: beneficiary, data: undefined }; + } + }), + ); + + return beneficiariesWithData; + } catch (error) { + console.error('Error fetching beneficiaries', error); + throw error; + } + }, + options, + ); +}; diff --git a/apps/ats/web/src/i18n/en/index.ts b/apps/ats/web/src/i18n/en/index.ts index be31af155..8b7cf42a9 100644 --- a/apps/ats/web/src/i18n/en/index.ts +++ b/apps/ats/web/src/i18n/en/index.ts @@ -326,6 +326,7 @@ export default { internalKYCManager: 'Internal KYC Manager role', freezer: 'Freeze Manager Role', trexOwner: 'TREX Owner Role', + beneficiaryManager: 'Beneficiary Manager Role', }, landing, routes, diff --git a/apps/ats/web/src/i18n/en/rules.ts b/apps/ats/web/src/i18n/en/rules.ts index 5bca0db96..76fb6e739 100644 --- a/apps/ats/web/src/i18n/en/rules.ts +++ b/apps/ats/web/src/i18n/en/rules.ts @@ -218,4 +218,5 @@ export default { isISINValid: 'Length should be {{length}}.', isISINValidFormat: 'Invalid format', isValidHederaId: 'Wrong id', + isValidHex: 'Invalid hex format', }; diff --git a/apps/ats/web/src/i18n/en/security/beneficiaries.ts b/apps/ats/web/src/i18n/en/security/beneficiaries.ts new file mode 100644 index 000000000..abd086b0d --- /dev/null +++ b/apps/ats/web/src/i18n/en/security/beneficiaries.ts @@ -0,0 +1,284 @@ +/* + 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. + +*/ + +export default { + title: 'Beneficiaries', + subtitle: 'List of beneficiaries of the bond', + add: 'Add', + table: { + fields: { + address: 'Address', + data: 'Data', + actions: 'Actions', + edit: 'Edit', + remove: 'Remove', + }, + }, + create: { + title: 'Add Beneficiary', + description: 'Fill in the form below to add a beneficiary', + form: { + address: { + label: 'Address', + placeholder: '0.0.1234567', + }, + data: { + label: 'Data', + placeholder: '0x', + invalidHexFormat: 'Invalid hex format', + }, + }, + buttons: { + cancel: 'Cancel', + add: 'Add', + }, + messages: { + success: 'Success: ', + descriptionSuccess: 'Beneficiary creation was successful', + error: 'Error: ', + descriptionFailed: 'Beneficiary creation failed', + }, + }, + update: { + title: 'Update Beneficiary', + description: 'Fill in the form below to update a beneficiary', + form: { + address: { + label: 'Address', + placeholder: '0.0.1234567', + }, + data: { + label: 'Data', + placeholder: '0x', + invalidHexFormat: 'Invalid hex format', + }, + }, + buttons: { + cancel: 'Cancel', + update: 'Update', + }, + messages: { + success: 'Success: ', + descriptionSuccess: 'Beneficiary update was successful', + error: 'Error: ', + descriptionFailed: 'Beneficiary update failed', + }, + }, + remove: { + confirmPopUp: { + title: 'Remove Beneficiary', + description: 'Are you sure you want to remove this beneficiary?', + confirmText: 'Remove', + cancelText: 'Cancel', + }, + messages: { + success: 'Success: ', + descriptionSuccess: + 'The removal operation has been executed successfully', + error: 'Error: ', + descriptionFailed: 'The removal operation has failed', + }, + }, +}; diff --git a/apps/ats/web/src/i18n/en/security/createBond.ts b/apps/ats/web/src/i18n/en/security/createBond.ts index 609d9ec8f..87b6c83b4 100644 --- a/apps/ats/web/src/i18n/en/security/createBond.ts +++ b/apps/ats/web/src/i18n/en/security/createBond.ts @@ -293,6 +293,20 @@ export default { totalCoupons: 'Total coupons', }, + stepBeneficiaries: { + title: 'Beneficiaries', + subtitle: 'Add beneficiaries', + mandatoryFields: '*Mandatory fields', + address: 'Address', + addressPlaceholder: '0.0.1234567', + data: 'Data', + dataPlaceholder: '0x', + invalidHederaId: 'Invalid Hedera ID', + actions: 'Actions', + invalidHexFormat: 'Invalid hex format', + addBeneficiary: 'Add beneficiary', + }, + stepERC3643: { title: 'ERC3643', subtitle: 'Add ERC3643 configurations', diff --git a/apps/ats/web/src/i18n/en/security/details.ts b/apps/ats/web/src/i18n/en/security/details.ts index c11a194e9..ccff73ba0 100644 --- a/apps/ats/web/src/i18n/en/security/details.ts +++ b/apps/ats/web/src/i18n/en/security/details.ts @@ -219,6 +219,7 @@ import clearingOperations from './clearingOperations'; import externalPause from './externalPause'; import externalControl from './externalControl'; import externalKYC from './externalKYC'; +import beneficiaries from './beneficiaries'; export default { header: { @@ -249,6 +250,7 @@ export default { externalPause: 'External Pause', externalKYCList: 'External KYC', freeze: 'Freeze', + beneficiaries: 'Beneficiaries', }, actions: { redeem: 'Redeem', @@ -309,6 +311,7 @@ export default { externalPause, externalControl, externalKYC, + beneficiaries, benefits: { dividends: 'Dividends', balanceAdjustments: 'Balance Adjustments', diff --git a/apps/ats/web/src/services/SDKService.ts b/apps/ats/web/src/services/SDKService.ts index 97e989ef6..88f44012a 100644 --- a/apps/ats/web/src/services/SDKService.ts +++ b/apps/ats/web/src/services/SDKService.ts @@ -372,6 +372,13 @@ import { GetVotingHoldersRequest, SetComplianceRequest, SetIdentityRegistryRequest, + AddBeneficiaryRequest, + RemoveBeneficiaryRequest, + UpdateBeneficiaryDataRequest, + GetBeneficiariesCountRequest, + GetBeneficiariesRequest, + IsBeneficiaryRequest, + GetBeneficiaryDataRequest, } from '@hashgraph/asset-tokenization-sdk'; export class SDKService { @@ -565,6 +572,56 @@ export class SDKService { return await Security.setIdentityRegistry(req); } + // Beneficiaries + public static async getBeneficiariesCount( + req: GetBeneficiariesCountRequest, + ): Promise { + const request = await Bond.getBeneficiariesCount(req); + return request.payload; + } + + public static async getBeneficiaries( + req: GetBeneficiariesRequest, + ): Promise { + const request = await Bond.getBeneficiaries(req); + return request.payload; + } + + public static async getBeneficiaryData( + req: GetBeneficiaryDataRequest, + ): Promise { + const request = await Bond.getBeneficiaryData(req); + return request.payload; + } + + public static async isBeneficiary( + req: IsBeneficiaryRequest, + ): Promise { + const request = await Bond.isBeneficiary(req); + return request.payload; + } + + public static async addBeneficiary( + req: AddBeneficiaryRequest, + ): Promise { + const response = await Bond.addBeneficiary(req); + return response.payload; + } + + public static async removeBeneficiary( + req: RemoveBeneficiaryRequest, + ): Promise { + const response = await Bond.removeBeneficiary(req); + return response.payload; + } + + public static async updateBeneficiaryData( + req: UpdateBeneficiaryDataRequest, + ): Promise { + const response = await Bond.updateBeneficiaryData(req); + return response.payload; + } + // COUPONS //////////////////////////////////////////// public static async setCoupon(req: SetCouponRequest): Promise { const response = await Bond.setCoupon(req); diff --git a/apps/ats/web/src/utils/SecurityRole.ts b/apps/ats/web/src/utils/SecurityRole.ts index 9a420a0f2..91dedd4a5 100644 --- a/apps/ats/web/src/utils/SecurityRole.ts +++ b/apps/ats/web/src/utils/SecurityRole.ts @@ -229,4 +229,5 @@ export enum SecurityRole { _KYC_MANAGER_ROLE = '0x8ebae577938c1afa7fb3dc7b06459c79c86ffd2ac9805b6da92ee4cbbf080449', _INTERNAL_KYC_MANAGER_ROLE = '0x3916c5c9e68488134c2ee70660332559707c133d0a295a25971da4085441522e', _TREX_OWNER_ROLE = '0x03ce2fdc316501dd97f5219e6ad908a3238f1e90f910aa17b627f801a6aafab7', + _BENEFICIARY_MANAGER_ROLE = '0xebc53fe99fea28c7aa9476a714959af5b931f34a8a8734365ec63113198d512f', } diff --git a/apps/ats/web/src/utils/rules.ts b/apps/ats/web/src/utils/rules.ts index 54909d2f0..94ad0f932 100644 --- a/apps/ats/web/src/utils/rules.ts +++ b/apps/ats/web/src/utils/rules.ts @@ -322,6 +322,20 @@ export const isValidHederaId = (val: string) => { return maskRegex.test(val) || t('isValidHederaId'); }; +export const isValidHex = (val: string) => { + const hexRegex = /^0x[0-9a-fA-F]*$/; + if (!hexRegex.test(val)) { + return t('isValidHex'); + } + + const hexPart = val.slice(2); + if (hexPart.length % 2 !== 0) { + return t('isValidHex'); + } + + return true; +}; + export const isValidCouponPeriod = (val: string) => { try { // Period is required - cannot be empty or null diff --git a/apps/ats/web/src/views/CreateBond/Components/StepBeneficiaries.tsx b/apps/ats/web/src/views/CreateBond/Components/StepBeneficiaries.tsx new file mode 100644 index 000000000..ea9900a7b --- /dev/null +++ b/apps/ats/web/src/views/CreateBond/Components/StepBeneficiaries.tsx @@ -0,0 +1,409 @@ +/* + 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 { Flex, HStack, Stack } from '@chakra-ui/react'; +import { useTranslation } from 'react-i18next'; +import { + PhosphorIcon, + Text, + Table, + Button, + InputController, +} from 'io-bricks-ui'; +import { CancelButton } from '../../../components/CancelButton'; +import { NextStepButton } from './NextStepButton'; +import { PreviousStepButton } from './PreviousStepButton'; +import { ICreateBondFormValues } from '../ICreateBondFormValues'; +import { useFormContext, useFormState, useForm } from 'react-hook-form'; +import { FormStepContainer } from '../../../components/FormStepContainer'; +import { Trash } from '@phosphor-icons/react'; +import { createColumnHelper } from '@tanstack/table-core'; +import { isValidHederaId, isValidHex, required } from '../../../utils/rules'; + +interface IBeneficiary { + address: string; + data?: string; +} + +interface ILocalBeneficiaryForm { + address: string; + data?: string; +} + +export const StepBeneficiaries = () => { + const { t } = useTranslation('security', { keyPrefix: 'createBond' }); + const { control, watch, setValue } = useFormContext(); + const stepFormState = useFormState({ control }); + + const { + control: localControl, + handleSubmit: handleLocalSubmit, + reset: resetLocalForm, + formState: localFormState, + } = useForm({ + defaultValues: { + address: '', + data: '', + }, + mode: 'onChange', + }); + + const currentBeneficiariesIds = watch('beneficiariesIds') || []; + const currentBeneficiariesData = watch('beneficiariesData') || []; + + const beneficiaries: IBeneficiary[] = currentBeneficiariesIds.map( + (address, index) => ({ + address, + data: currentBeneficiariesData[index] || '', + }), + ); + + const handleAddBeneficiary = handleLocalSubmit((data) => { + const newBeneficiariesIds = [ + ...currentBeneficiariesIds, + data.address.trim(), + ]; + const newBeneficiariesData = [ + ...currentBeneficiariesData, + data?.data?.trim() ?? '', + ]; + + setValue('beneficiariesIds', newBeneficiariesIds); + setValue('beneficiariesData', newBeneficiariesData); + + resetLocalForm(); + }); + + const handleRemoveBeneficiary = (addressToRemove: string) => { + const indexToRemove = currentBeneficiariesIds.indexOf(addressToRemove); + if (indexToRemove !== -1) { + const newBeneficiariesIds = currentBeneficiariesIds.filter( + (_, index) => index !== indexToRemove, + ); + const newBeneficiariesData = currentBeneficiariesData.filter( + (_, index) => index !== indexToRemove, + ); + + setValue('beneficiariesIds', newBeneficiariesIds); + setValue('beneficiariesData', newBeneficiariesData); + } + }; + + const columnsHelper = createColumnHelper(); + + const columns = [ + columnsHelper.accessor('address', { + header: t('stepBeneficiaries.address'), + enableSorting: false, + }), + columnsHelper.accessor('data', { + header: t('stepBeneficiaries.data'), + enableSorting: false, + }), + columnsHelper.display({ + id: 'actions', + header: t('stepBeneficiaries.actions'), + enableSorting: false, + cell(props) { + const { + row: { + original: { address }, + }, + } = props; + + return ( + + ); + }, + }), + ]; + + return ( + + + {t('stepBeneficiaries.title')} + + {t('stepBeneficiaries.subtitle')} + + + {t('stepBeneficiaries.mandatoryFields')} + + + + + {t('stepBeneficiaries.address')} + + + !value || + isValidHederaId(value) || + t('stepBeneficiaries.invalidHederaId'), + }} + /> + + + {t('stepBeneficiaries.data')} + + !value || + isValidHex(value) || + t('stepBeneficiaries.invalidHexFormat'), + }} + /> + + + + + + The list is empty + + } + /> + + + + + + + ); +}; diff --git a/apps/ats/web/src/views/CreateBond/Components/StepReview.tsx b/apps/ats/web/src/views/CreateBond/Components/StepReview.tsx index b30b4e87e..0fec1564d 100644 --- a/apps/ats/web/src/views/CreateBond/Components/StepReview.tsx +++ b/apps/ats/web/src/views/CreateBond/Components/StepReview.tsx @@ -212,7 +212,7 @@ import { } from '@chakra-ui/react'; import { useTranslation } from 'react-i18next'; import { PreviousStepButton } from './PreviousStepButton'; -import { PhosphorIcon } from 'io-bricks-ui'; +import { PhosphorIcon, Table, Text } from 'io-bricks-ui'; import { useFormContext } from 'react-hook-form'; import { Button, @@ -240,6 +240,12 @@ import { COUNTRY_LIST_ALLOWED, COUNTRY_LIST_BLOCKED, } from '../../../utils/countriesConfig'; +import { createColumnHelper } from '@tanstack/table-core'; + +interface IBeneficiary { + address: string; + data?: string; +} export const StepReview = () => { const { t } = useTranslation('security', { keyPrefix: 'createBond' }); @@ -286,11 +292,32 @@ export const StepReview = () => { const internalKycActivated = getValues('internalKycActivated'); const complianceId = getValues('complianceId'); const identityRegistryId = getValues('identityRegistryId'); + const beneficiariesIds = getValues('beneficiariesIds'); + const beneficiariesData = getValues('beneficiariesData'); countriesList = countriesList.concat( countriesListType === 2 ? COUNTRY_LIST_ALLOWED : COUNTRY_LIST_BLOCKED, ); + const beneficiariesTableData: IBeneficiary[] = (beneficiariesIds || []).map( + (address, index) => ({ + address, + data: (beneficiariesData || [])[index] || '', + }), + ); + + const columnsHelper = createColumnHelper(); + const columnsBeneficiaries = [ + columnsHelper.accessor('address', { + header: t('stepBeneficiaries.address'), + enableSorting: false, + }), + columnsHelper.accessor('data', { + header: t('stepBeneficiaries.data'), + enableSorting: false, + }), + ]; + const submit = () => { const request = new CreateBondRequest({ name, @@ -339,6 +366,12 @@ export const StepReview = () => { ...(identityRegistryId && { identityRegistryId: identityRegistryId, }), + ...(beneficiariesIds && { + beneficiariesIds: beneficiariesIds, + }), + ...(beneficiariesData && { + beneficiariesData: beneficiariesData, + }), }); createBond(request); @@ -470,7 +503,23 @@ export const StepReview = () => { ))} - + + + {beneficiariesTableData.length > 0 && ( +
+ )} + {!beneficiariesTableData.length && -} + + + {erc3643Details.map((props) => ( @@ -478,7 +527,7 @@ export const StepReview = () => { @@ -488,7 +537,7 @@ export const StepReview = () => { ))} - + {regulationDetails.map((props) => ( diff --git a/apps/ats/web/src/views/CreateBond/CreateBond.tsx b/apps/ats/web/src/views/CreateBond/CreateBond.tsx index 36c36be20..16ba9d2de 100644 --- a/apps/ats/web/src/views/CreateBond/CreateBond.tsx +++ b/apps/ats/web/src/views/CreateBond/CreateBond.tsx @@ -219,6 +219,7 @@ import { StepReview } from './Components/StepReview'; import { StepRegulation } from '../CreateSecurityCommons/StepRegulation'; import { StepExternalManagement } from '../CreateSecurityCommons/StepExternalManagement'; import { StepERC3643 } from '../CreateSecurityCommons/StepERC3643'; +import { StepBeneficiaries } from './Components/StepBeneficiaries'; export const CreateBond = () => { const { t } = useTranslation('security', { keyPrefix: 'createBond' }); @@ -253,6 +254,10 @@ export const CreateBond = () => { title: t('header.configuration'), content: , }, + { + title: t('stepBeneficiaries.title'), + content: , + }, { title: t('stepERC3643.title'), content: , diff --git a/apps/ats/web/src/views/CreateBond/ICreateBondFormValues.ts b/apps/ats/web/src/views/CreateBond/ICreateBondFormValues.ts index 83627710c..9ccd87ac6 100644 --- a/apps/ats/web/src/views/CreateBond/ICreateBondFormValues.ts +++ b/apps/ats/web/src/views/CreateBond/ICreateBondFormValues.ts @@ -228,4 +228,6 @@ export interface ICreateBondFormValues { internalKycActivated: boolean; complianceId?: string; identityRegistryId?: string; + beneficiariesIds?: string[]; + beneficiariesData?: string[]; } diff --git a/apps/ats/web/src/views/CreateBond/__tests__/__snapshots__/CreateBond.test.tsx.snap b/apps/ats/web/src/views/CreateBond/__tests__/__snapshots__/CreateBond.test.tsx.snap index 6a2ac5fc0..ee94cfc38 100644 --- a/apps/ats/web/src/views/CreateBond/__tests__/__snapshots__/CreateBond.test.tsx.snap +++ b/apps/ats/web/src/views/CreateBond/__tests__/__snapshots__/CreateBond.test.tsx.snap @@ -173,7 +173,7 @@ exports[`CreateBond render correctly 1`] = ` class="chakra-step__title css-gryw16" data-status="incomplete" > - ERC3643 + Beneficiaries
- External Lists + ERC3643
- Regulation + External Lists
+
+

+ Regulation +

+
+ +
+
+
+ 7 +
+
diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/AddBeneficiaryModal.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/AddBeneficiaryModal.tsx new file mode 100644 index 000000000..7f6307d35 --- /dev/null +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/AddBeneficiaryModal.tsx @@ -0,0 +1,132 @@ +import { + HStack, + Modal, + ModalBody, + ModalCloseButton, + ModalContent, + ModalFooter, + ModalHeader, + ModalOverlay, + ModalProps, + VStack, +} from '@chakra-ui/react'; +import { Button, InputController } from 'io-bricks-ui'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import { useParams } from 'react-router-dom'; +import { isValidHederaId, isValidHex, required } from '../../../../utils/rules'; +import { useAddBeneficiary } from '../../../../hooks/mutations/useBeneficiaries'; +import { AddBeneficiaryRequest } from '@hashgraph/asset-tokenization-sdk'; + +interface FormValues { + address: string; + data?: string; +} + +interface AddBeneficiaryModalProps extends Omit {} + +export const AddBeneficiaryModal = ({ + isOpen, + onClose, +}: AddBeneficiaryModalProps) => { + const { id: securityId = '' } = useParams(); + + const { t: tCreate } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.create', + }); + + const { + control, + formState: { isValid }, + handleSubmit, + reset, + } = useForm({ + mode: 'onChange', + }); + + const { mutate: addBeneficiaryMutation, isPending: isPendingAddBeneficiary } = + useAddBeneficiary(); + + const onSubmit = (values: FormValues) => { + const request = new AddBeneficiaryRequest({ + securityId, + beneficiaryId: values.address, + data: values.data ?? '', + }); + + addBeneficiaryMutation(request, { + onSettled() { + onClose(); + }, + onSuccess() { + reset(); + }, + }); + }; + + return ( + { + reset(); + onClose(); + }} + > + + + {tCreate('title')} + + + + + + !value || + isValidHex(value) || + tCreate('form.data.invalidHexFormat'), + }} + /> + + + + + + + + + + + ); +}; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/Beneficiaries.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/Beneficiaries.tsx new file mode 100644 index 000000000..6ea206f9e --- /dev/null +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/Beneficiaries.tsx @@ -0,0 +1,207 @@ +import { Flex, HStack, Stack, useDisclosure } from '@chakra-ui/react'; +import { Button, PhosphorIcon, PopUp, Table, Text } from 'io-bricks-ui'; +import { useMemo, useState } from 'react'; +import { SecurityRole } from '../../../../utils/SecurityRole'; +import { useRolesStore } from '../../../../store/rolesStore'; +import { useTranslation } from 'react-i18next'; +import { useParams } from 'react-router-dom'; +import { createColumnHelper } from '@tanstack/table-core'; +import { Pencil, Trash } from '@phosphor-icons/react'; +import { AddBeneficiaryModal } from './AddBeneficiaryModal'; +import { + GetBeneficiariesCountRequest, + RemoveBeneficiaryRequest, +} from '@hashgraph/asset-tokenization-sdk'; +import { + BeneficiaryDataViewModelResponse, + useGetBeneficiaryList, +} from '../../../../hooks/queries/useBeneficiaries'; +import { UpdateBeneficiaryModal } from './UpdateBeneficiaryModal'; +import { useRemoveBeneficiary } from '../../../../hooks/mutations/useBeneficiaries'; + +export const Beneficiaries = () => { + const { id: securityId = '' } = useParams(); + + const { roles: accountRoles } = useRolesStore(); + + const { t: tBeneficiaries } = useTranslation('security', { + keyPrefix: 'details.beneficiaries', + }); + const { t: tTable } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.table', + }); + const { t: tRemove } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.remove', + }); + + const [beneficiaryIdSelected, setBeneficiaryIdSelected] = useState(''); + + const { isOpen, onClose, onOpen } = useDisclosure(); + const { + isOpen: isOpenUpdate, + onClose: onCloseUpdate, + onOpen: onOpenUpdate, + } = useDisclosure(); + const { + isOpen: isOpenRemoveBeneficiaryModal, + onClose: onCloseRemoveBeneficiaryModal, + onOpen: onOpenRemoveBeneficiaryModal, + } = useDisclosure(); + + const hasBeneficiaryManagerRole = useMemo( + () => + accountRoles.findIndex( + (rol) => rol === SecurityRole._BENEFICIARY_MANAGER_ROLE, + ) !== -1, + [accountRoles], + ); + + const { data: beneficiaries, isLoading: isLoadingBeneficiaries } = + useGetBeneficiaryList( + new GetBeneficiariesCountRequest({ + securityId, + }), + ); + + const { + mutate: removeBeneficiaryMutation, + isPending: isPendingRemoveBeneficiary, + } = useRemoveBeneficiary(); + + const columnsHelper = createColumnHelper(); + + const columns = [ + columnsHelper.accessor('address', { + header: tTable('fields.address'), + enableSorting: false, + }), + columnsHelper.accessor('data', { + header: tTable('fields.data'), + enableSorting: false, + cell({ + row: { + original: { data }, + }, + }) { + return data === '0x' ? '-' : data; + }, + }), + ...(hasBeneficiaryManagerRole + ? [ + columnsHelper.display({ + id: 'remove', + header: tTable('fields.actions'), + size: 5, + enableSorting: false, + cell(props) { + const { + row: { + original: { address }, + }, + } = props; + + return ( + + + + + ); + }, + }), + ] + : []), + ]; + + return ( + <> + + + + {tBeneficiaries('title')} + + {hasBeneficiaryManagerRole && ( + + )} + +
+ No beneficiaries + + } + /> + + + + } + title={tRemove('confirmPopUp.title')} + description={tRemove('confirmPopUp.description')} + confirmText={tRemove('confirmPopUp.confirmText')} + onConfirm={() => { + const request = new RemoveBeneficiaryRequest({ + securityId, + beneficiaryId: beneficiaryIdSelected, + }); + + removeBeneficiaryMutation(request, { + onSuccess() { + onCloseRemoveBeneficiaryModal(); + }, + }); + }} + onCancel={onCloseRemoveBeneficiaryModal} + cancelText={tRemove('confirmPopUp.cancelText')} + confirmButtonProps={{ + isLoading: isPendingRemoveBeneficiary, + }} + /> + + ); +}; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/RemoveBeneficiaryModal.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/RemoveBeneficiaryModal.tsx new file mode 100644 index 000000000..18aec38c1 --- /dev/null +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/RemoveBeneficiaryModal.tsx @@ -0,0 +1,126 @@ +import { + HStack, + Modal, + ModalBody, + ModalCloseButton, + ModalContent, + ModalFooter, + ModalHeader, + ModalOverlay, + ModalProps, + VStack, +} from '@chakra-ui/react'; +import { Button, InputController } from 'io-bricks-ui'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import { useParams } from 'react-router-dom'; +import { isValidHederaId, required } from '../../../../utils/rules'; +import { useAddBeneficiary } from '../../../../hooks/mutations/useBeneficiaries'; +import { AddBeneficiaryRequest } from '@hashgraph/asset-tokenization-sdk'; + +interface FormValues { + address: string; + data?: string; +} + +interface AddBeneficiaryModalProps extends Omit {} + +export const AddBeneficiaryModal = ({ + isOpen, + onClose, +}: AddBeneficiaryModalProps) => { + const { id: securityId = '' } = useParams(); + + const { t: tCreate } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.create', + }); + + const { + control, + formState: { isValid }, + handleSubmit, + reset, + } = useForm({ + mode: 'onChange', + }); + + const { mutate: addBeneficiaryMutation, isPending: isPendingAddBeneficiary } = + useAddBeneficiary(); + + const onSubmit = (values: FormValues) => { + const request = new AddBeneficiaryRequest({ + securityId, + beneficiaryId: values.address, + data: values.data ?? '', + }); + + console.log('request', request); + + addBeneficiaryMutation(request, { + onSettled() { + onClose(); + }, + onSuccess() { + reset(); + }, + }); + }; + + return ( + { + reset(); + onClose(); + }} + > + + + {tCreate('title')} + + + + + + + + + + + + + + + + ); +}; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/UpdateBeneficiaryModal.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/UpdateBeneficiaryModal.tsx new file mode 100644 index 000000000..763e481b5 --- /dev/null +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Beneficiaries/UpdateBeneficiaryModal.tsx @@ -0,0 +1,136 @@ +import { + HStack, + Modal, + ModalBody, + ModalCloseButton, + ModalContent, + ModalFooter, + ModalHeader, + ModalOverlay, + ModalProps, + VStack, +} from '@chakra-ui/react'; +import { Button, Input, InputController } from 'io-bricks-ui'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import { useParams } from 'react-router-dom'; +import { useUpdateBeneficiary } from '../../../../hooks/mutations/useBeneficiaries'; +import { UpdateBeneficiaryDataRequest } from '@hashgraph/asset-tokenization-sdk'; +import { isValidHex } from '../../../../utils/rules'; + +interface FormValues { + address: string; + data?: string; +} + +interface UpdateBeneficiaryModalProps extends Omit { + beneficiaryId: string; +} + +export const UpdateBeneficiaryModal = ({ + isOpen, + onClose, + beneficiaryId, +}: UpdateBeneficiaryModalProps) => { + const { id: securityId = '' } = useParams(); + + const { t: tUpdate } = useTranslation('security', { + keyPrefix: 'details.beneficiaries.update', + }); + + const { + control, + formState: { isValid }, + handleSubmit, + reset, + } = useForm({ + mode: 'onChange', + defaultValues: { + address: beneficiaryId, + }, + }); + + const { + mutate: updateBeneficiaryMutation, + isPending: isPendingUpdateBeneficiary, + } = useUpdateBeneficiary(); + + const onSubmit = (values: FormValues) => { + const request = new UpdateBeneficiaryDataRequest({ + securityId, + beneficiaryId, + data: values.data ?? '', + }); + + updateBeneficiaryMutation(request, { + onSettled() { + onClose(); + }, + onSuccess() { + reset(); + }, + }); + }; + + return ( + { + reset(); + onClose(); + }} + > + + + {tUpdate('title')} + + + + + + !value || + isValidHex(value) || + tUpdate('form.data.invalidHexFormat'), + }} + /> + + + + + + + + + + + ); +}; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/RoleManagement/rolesList.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/RoleManagement/rolesList.tsx index b618296ca..7da0a87eb 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/RoleManagement/rolesList.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/RoleManagement/rolesList.tsx @@ -324,4 +324,9 @@ export const rolesList: TRole[] = [ value: SecurityRole._TREX_OWNER_ROLE, allowedSecurities: ['BOND', 'EQUITY'], }, + { + label: 'beneficiaryManager', + value: SecurityRole._BENEFICIARY_MANAGER_ROLE, + allowedSecurities: ['BOND'], + }, ]; diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Tabs/Control.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Tabs/Control.tsx index fa9d1c6c2..34c770764 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/Components/Tabs/Control.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/Components/Tabs/Control.tsx @@ -10,10 +10,12 @@ import { ExternalControl } from '../ExternalControl/ExternalControl'; import { ExternalKYC } from '../ExternalKYC/ExternalKYC'; import { AdminControlActionsButtons } from '../AdminControlActionsButtons'; import { Tabs } from 'io-bricks-ui'; +import { Beneficiaries } from '../Beneficiaries/Beneficiaries'; interface ControlTabProps { details: SecurityViewModel; config: { + showBeneficiaries: boolean; showControlList: boolean; showKYC: boolean; showSSIManager: boolean; @@ -30,6 +32,9 @@ export const ControlTab = ({ details, config }: ControlTabProps) => { const tabs = useMemo(() => { const tabs = []; + if (config.showBeneficiaries) { + tabs.push({ content: , header: tTabs('beneficiaries') }); + } if (config.showControlList) { tabs.push({ content: , @@ -42,7 +47,6 @@ export const ControlTab = ({ details, config }: ControlTabProps) => { if (config.showSSIManager) { tabs.push({ content: , header: tTabs('ssiManager') }); } - tabs.push({ content: , header: tTabs('externalPause') }); tabs.push({ content: , diff --git a/apps/ats/web/src/views/DigitalSecurityDetails/DigitalSecurityDetails.tsx b/apps/ats/web/src/views/DigitalSecurityDetails/DigitalSecurityDetails.tsx index 401eb05d8..213507aec 100644 --- a/apps/ats/web/src/views/DigitalSecurityDetails/DigitalSecurityDetails.tsx +++ b/apps/ats/web/src/views/DigitalSecurityDetails/DigitalSecurityDetails.tsx @@ -400,6 +400,7 @@ export const DigitalSecurityDetails = () => { }; const controlConfig = { + showBeneficiaries: !isSecurityPaused && securityDetails?.type === 'BOND', showControlList: !isSecurityPaused && hasRole(rolesStored, SecurityRole._CONTROLLIST_ROLE), diff --git a/apps/ats/web/vite.config.ts b/apps/ats/web/vite.config.ts index bbf1917d3..75215645f 100644 --- a/apps/ats/web/vite.config.ts +++ b/apps/ats/web/vite.config.ts @@ -220,12 +220,12 @@ export default { EnvironmentPlugin('all'), pluginRewriteAll(), { - name: 'singleHMR', - handleHotUpdate({ modules }) { - modules.map((m) => { - m.importedModules = new Set(); - m.importers = new Set(); - }); + name: 'selectiveHMR', + handleHotUpdate({ file, modules }) { + if (file.includes('problematic-file.ts')) { + return []; + } + return modules; }, }, @@ -288,6 +288,10 @@ export default { include: [ '@hashgraph/asset-tokenization-contracts', '@hashgraph/asset-tokenization-sdk', + '@chakra-ui/react', + '@emotion/react', + '@emotion/styled', + 'framer-motion', ], exclude: ['winston', 'winston-daily-rotate-file', 'winston-transport'], esbuildOptions: { diff --git a/packages/ats/contracts/Configuration.ts b/packages/ats/contracts/Configuration.ts index 12f4dd7e9..228142726 100644 --- a/packages/ats/contracts/Configuration.ts +++ b/packages/ats/contracts/Configuration.ts @@ -264,10 +264,11 @@ export const CONTRACT_NAMES = [ 'ClearingTransferFacet', 'ClearingReadFacet', 'ClearingActionsFacet', + 'BeneficiariesFacet', 'ExternalPauseManagementFacet', 'ExternalControlListManagementFacet', 'ExternalKycListManagementFacet', - 'ERC3643Facet', + 'ERC3643', 'FreezeFacet', 'ERC3643ManagementFacet', 'ERC3643ReadFacet', diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol index 4cc547036..dbeff17b6 100644 --- a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol @@ -260,6 +260,8 @@ interface TRexIFactory { struct BondData { SecurityData security; IBondRead.BondDetailsData bondDetails; + address[] beneficiaries; + bytes[] beneficiariesData; } event EquityDeployed( diff --git a/packages/ats/contracts/contracts/factory/Factory.sol b/packages/ats/contracts/contracts/factory/Factory.sol index 38d2f72cc..fb3d66050 100644 --- a/packages/ats/contracts/contracts/factory/Factory.sol +++ b/packages/ats/contracts/contracts/factory/Factory.sol @@ -237,6 +237,9 @@ import { } from '../layer_3/constants/regulation.sol'; import {IEquityUSA} from '../layer_3/interfaces/IEquityUSA.sol'; import {IBondUSA} from '../layer_3/interfaces/IBondUSA.sol'; +import { + IBeneficiaries +} from '../layer_2/interfaces/beneficiaries/IBeneficiaries.sol'; import { IProtectedPartitions } from '../layer_1/interfaces/protectedPartitions/IProtectedPartitions.sol'; @@ -368,6 +371,11 @@ contract Factory is IFactory, LocalContext { _factoryRegulationData.additionalSecurityData ); + IBeneficiaries(bondAddress_).initialize_Beneficiaries( + _bondData.beneficiaries, + _bondData.beneficiariesData + ); + emit BondDeployed( _msgSender(), bondAddress_, diff --git a/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol b/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol index a67dc0b87..d6480cdf7 100644 --- a/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol +++ b/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol @@ -258,6 +258,8 @@ interface IFactory { struct BondData { SecurityData security; IBondRead.BondDetailsData bondDetails; + address[] beneficiaries; + bytes[] beneficiariesData; } event EquityDeployed( diff --git a/packages/ats/contracts/contracts/layer_0/ERC3643/ERC3643StorageWrapper1.sol b/packages/ats/contracts/contracts/layer_0/ERC3643/ERC3643StorageWrapper1.sol index 153434ccb..5807bf0ac 100644 --- a/packages/ats/contracts/contracts/layer_0/ERC3643/ERC3643StorageWrapper1.sol +++ b/packages/ats/contracts/contracts/layer_0/ERC3643/ERC3643StorageWrapper1.sol @@ -233,6 +233,9 @@ import { } from '../constants/storagePositions.sol'; import {ICompliance} from '../../layer_1/interfaces/ERC3643/ICompliance.sol'; import {LowLevelCall} from '../common/libraries/LowLevelCall.sol'; +import { + BeneficiariesStorageWrapper +} from '../beneficiaries/BeneficiariesStorageWrapper.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {_AGENT_ROLE} from '../constants/roles.sol'; import { @@ -241,7 +244,7 @@ import { abstract contract ERC3643StorageWrapper1 is IERC3643StorageWrapper, - TotalBalancesStorageWrapper + BeneficiariesStorageWrapper { using LowLevelCall for address; diff --git a/packages/ats/contracts/contracts/layer_0/beneficiaries/BeneficiariesStorageWrapper.sol b/packages/ats/contracts/contracts/layer_0/beneficiaries/BeneficiariesStorageWrapper.sol new file mode 100644 index 000000000..bb2f9ec82 --- /dev/null +++ b/packages/ats/contracts/contracts/layer_0/beneficiaries/BeneficiariesStorageWrapper.sol @@ -0,0 +1,280 @@ +/* + 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: MIT +pragma solidity 0.8.18; + +import { + TotalBalancesStorageWrapper +} from '../totalBalances/totalBalancesStorageWrapper.sol'; +import { + _BENEFICIARIES_STORAGE_POSITION, + _BENEFICIARIES_DATA_STORAGE_POSITION +} from '../constants/storagePositions.sol'; +import { + IBeneficiaries +} from '../../layer_2/interfaces/beneficiaries/IBeneficiaries.sol'; + +abstract contract BeneficiariesStorageWrapper is TotalBalancesStorageWrapper { + struct BeneficiariesDataStorage { + mapping(address => bytes) beneficiaryData; + } + + modifier onlyIfBeneficiary(address _beneficiary) { + if (!_isExternalList(_BENEFICIARIES_STORAGE_POSITION, _beneficiary)) { + revert IBeneficiaries.BeneficiaryNotFound(_beneficiary); + } + _; + } + + modifier onlyIfNotBeneficiary(address _beneficiary) { + if (_isExternalList(_BENEFICIARIES_STORAGE_POSITION, _beneficiary)) { + revert IBeneficiaries.BeneficiaryAlreadyExists(_beneficiary); + } + _; + } + + function _addBeneficiary( + address _beneficiary, + bytes calldata _data + ) internal { + _addExternalList(_BENEFICIARIES_STORAGE_POSITION, _beneficiary); + _setBeneficiaryData(_beneficiary, _data); + } + + function _removeBeneficiary(address _beneficiary) internal { + _removeExternalList(_BENEFICIARIES_STORAGE_POSITION, _beneficiary); + _removeBeneficiaryData(_beneficiary); + } + + function _setBeneficiaryData( + address _beneficiary, + bytes calldata _data + ) internal { + _beneficiariesDataStorage().beneficiaryData[_beneficiary] = _data; + } + + function _removeBeneficiaryData(address _beneficiary) internal { + delete _beneficiariesDataStorage().beneficiaryData[_beneficiary]; + } + + function _getBeneficiaryData( + address _beneficiary + ) internal view returns (bytes memory) { + return _beneficiariesDataStorage().beneficiaryData[_beneficiary]; + } + + function _beneficiariesDataStorage() + internal + pure + returns (BeneficiariesDataStorage storage beneficiariesDataStorage_) + { + bytes32 position = _BENEFICIARIES_DATA_STORAGE_POSITION; + // solhint-disable-next-line no-inline-assembly + assembly { + beneficiariesDataStorage_.slot := position + } + } +} diff --git a/packages/ats/contracts/contracts/layer_0/constants/storagePositions.sol b/packages/ats/contracts/contracts/layer_0/constants/storagePositions.sol index abccfbb1d..d665d6709 100644 --- a/packages/ats/contracts/contracts/layer_0/constants/storagePositions.sol +++ b/packages/ats/contracts/contracts/layer_0/constants/storagePositions.sol @@ -294,3 +294,9 @@ bytes32 constant _ERC3643_STORAGE_POSITION = 0xba82ce8c38a926a01a84988222ab779cf // keccak256('security.token.standard.resolverProxy.storage'); bytes32 constant _RESOLVER_PROXY_STORAGE_POSITION = 0x4833864335c8f29dd85e3f7a36869cb90d5dc7167ae5000f7e1ce4d7c15d14ad; + +// keccak256('security.token.standard.beneficiaries.storage'); +bytes32 constant _BENEFICIARIES_STORAGE_POSITION = 0xd76ee368b4f6f14377350eb4eeded82471ef0e0208749dc135673661ed492f43; + +// keccak256('security.token.standard.beneficiaries.data.storage'); +bytes32 constant _BENEFICIARIES_DATA_STORAGE_POSITION = 0xc7c4e0ff0ace36b5d2de5287c034dccef63aa2fb6c2498a31a48fd5516019f8c; diff --git a/packages/ats/contracts/contracts/layer_2/beneficiaries/Beneficiaries.sol b/packages/ats/contracts/contracts/layer_2/beneficiaries/Beneficiaries.sol new file mode 100644 index 000000000..0e5ee4559 --- /dev/null +++ b/packages/ats/contracts/contracts/layer_2/beneficiaries/Beneficiaries.sol @@ -0,0 +1,312 @@ +/* + 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. + +*/ + +pragma solidity 0.8.18; +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +import {IBeneficiaries} from '../interfaces/beneficiaries/IBeneficiaries.sol'; +import {Common} from '../../layer_1/common/Common.sol'; +import {_BENEFICIARY_MANAGER_ROLE} from '../constants/roles.sol'; +import { + _BENEFICIARIES_STORAGE_POSITION +} from '../../layer_0/constants/storagePositions.sol'; + +contract Beneficiaries is IBeneficiaries, Common { + // solhint-disable-next-line func-name-mixedcase + function initialize_Beneficiaries( + address[] calldata _beneficiaries, + bytes[] calldata _data + ) + external + override + onlyUninitialized( + _externalListStorage(_BENEFICIARIES_STORAGE_POSITION).initialized + ) + { + uint256 length = _beneficiaries.length; + for (uint256 index; index < length; ) { + _addExternalList( + _BENEFICIARIES_STORAGE_POSITION, + _beneficiaries[index] + ); + _setBeneficiaryData(_beneficiaries[index], _data[index]); + unchecked { + ++index; + } + } + + _externalListStorage(_BENEFICIARIES_STORAGE_POSITION) + .initialized = true; + } + + function addBeneficiary( + address _beneficiary, + bytes calldata _data + ) + external + override + onlyUnpaused + onlyRole(_BENEFICIARY_MANAGER_ROLE) + onlyIfNotBeneficiary(_beneficiary) + { + _addBeneficiary(_beneficiary, _data); + emit BeneficiaryAdded(_msgSender(), _beneficiary, _data); + } + + function removeBeneficiary( + address _beneficiary + ) + external + override + onlyUnpaused + onlyRole(_BENEFICIARY_MANAGER_ROLE) + onlyIfBeneficiary(_beneficiary) + { + _removeBeneficiary(_beneficiary); + emit BeneficiaryRemoved(_msgSender(), _beneficiary); + } + + function updateBeneficiaryData( + address _beneficiary, + bytes calldata _data + ) + external + override + onlyUnpaused + onlyRole(_BENEFICIARY_MANAGER_ROLE) + onlyIfBeneficiary(_beneficiary) + { + _setBeneficiaryData(_beneficiary, _data); + emit BeneficiaryDataUpdated(_msgSender(), _beneficiary, _data); + } + + function isBeneficiary( + address _beneficiary + ) external view override returns (bool) { + return _isExternalList(_BENEFICIARIES_STORAGE_POSITION, _beneficiary); + } + + function getBeneficiaryData( + address _beneficiary + ) external view override returns (bytes memory) { + return _getBeneficiaryData(_beneficiary); + } + + function getBeneficiariesCount() external view override returns (uint256) { + return _getExternalListsCount(_BENEFICIARIES_STORAGE_POSITION); + } + + function getBeneficiaries( + uint256 _pageIndex, + uint256 _pageLength + ) external view override returns (address[] memory beneficiaries_) { + return + _getExternalListsMembers( + _BENEFICIARIES_STORAGE_POSITION, + _pageIndex, + _pageLength + ); + } +} diff --git a/packages/ats/contracts/contracts/layer_2/beneficiaries/BeneficiariesFacet.sol b/packages/ats/contracts/contracts/layer_2/beneficiaries/BeneficiariesFacet.sol new file mode 100644 index 000000000..4a964b6ae --- /dev/null +++ b/packages/ats/contracts/contracts/layer_2/beneficiaries/BeneficiariesFacet.sol @@ -0,0 +1,269 @@ +/* + 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. + +*/ + +pragma solidity 0.8.18; +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +import { + IStaticFunctionSelectors +} from '../../interfaces/resolver/resolverProxy/IStaticFunctionSelectors.sol'; +import {Beneficiaries} from './Beneficiaries.sol'; +import {IBeneficiaries} from '../interfaces/beneficiaries/IBeneficiaries.sol'; +import {_BENEFICIARIES_RESOLVER_KEY} from '../constants/resolverKeys.sol'; + +contract BeneficiariesFacet is Beneficiaries, IStaticFunctionSelectors { + function getStaticResolverKey() + external + pure + override + returns (bytes32 staticResolverKey_) + { + staticResolverKey_ = _BENEFICIARIES_RESOLVER_KEY; + } + + function getStaticFunctionSelectors() + external + pure + override + returns (bytes4[] memory staticFunctionSelectors_) + { + uint256 selectorIndex; + staticFunctionSelectors_ = new bytes4[](8); + staticFunctionSelectors_[selectorIndex++] = this + .initialize_Beneficiaries + .selector; + staticFunctionSelectors_[selectorIndex++] = this + .addBeneficiary + .selector; + staticFunctionSelectors_[selectorIndex++] = this + .removeBeneficiary + .selector; + staticFunctionSelectors_[selectorIndex++] = this + .updateBeneficiaryData + .selector; + staticFunctionSelectors_[selectorIndex++] = this.isBeneficiary.selector; + staticFunctionSelectors_[selectorIndex++] = this + .getBeneficiaryData + .selector; + staticFunctionSelectors_[selectorIndex++] = this + .getBeneficiariesCount + .selector; + staticFunctionSelectors_[selectorIndex++] = this + .getBeneficiaries + .selector; + } + + function getStaticInterfaceIds() + external + pure + override + returns (bytes4[] memory staticInterfaceIds_) + { + staticInterfaceIds_ = new bytes4[](1); + uint256 selectorsIndex; + staticInterfaceIds_[selectorsIndex++] = type(IBeneficiaries) + .interfaceId; + } +} diff --git a/packages/ats/contracts/contracts/layer_2/constants/resolverKeys.sol b/packages/ats/contracts/contracts/layer_2/constants/resolverKeys.sol index c0982f11a..13fc6439d 100644 --- a/packages/ats/contracts/contracts/layer_2/constants/resolverKeys.sol +++ b/packages/ats/contracts/contracts/layer_2/constants/resolverKeys.sol @@ -228,3 +228,6 @@ bytes32 constant _SCHEDULED_TASKS_RESOLVER_KEY = 0xa4934195ab83f1497ce5fc99b68d0 // keccak256('security.token.standard.balanceAdjustments.resolverKey'); bytes32 constant _BALANCE_ADJUSTMENTS_RESOLVER_KEY = 0x2bbe9fb018f1e7dd12b4442154e7fdfd75aec7b0a65d07debf49de4ece5fe8b8; + +// keccak256('security.token.standard.beneficiaries.resolverKey'); +bytes32 constant _BENEFICIARIES_RESOLVER_KEY = 0x87f4b676bf89cd24a01a78fd8e7fb2102c2f6d034be73d16402f7297e0ae625b; diff --git a/packages/ats/contracts/contracts/layer_2/constants/roles.sol b/packages/ats/contracts/contracts/layer_2/constants/roles.sol index fed60b3dd..3c2236f7c 100644 --- a/packages/ats/contracts/contracts/layer_2/constants/roles.sol +++ b/packages/ats/contracts/contracts/layer_2/constants/roles.sol @@ -210,3 +210,6 @@ pragma solidity 0.8.18; // keccak256('security.token.standard.role.adjustmentBalance'); bytes32 constant _ADJUSTMENT_BALANCE_ROLE = 0x6d0d63b623e69df3a6ea8aebd01f360a0250a880cbc44f7f10c49726a80a78a9; + +// keccak256('security.token.standard.role.beneficiary'); +bytes32 constant _BENEFICIARY_MANAGER_ROLE = 0xebc53fe99fea28c7aa9476a714959af5b931f34a8a8734365ec63113198d512f; diff --git a/packages/ats/contracts/contracts/layer_2/interfaces/beneficiaries/IBeneficiaries.sol b/packages/ats/contracts/contracts/layer_2/interfaces/beneficiaries/IBeneficiaries.sol new file mode 100644 index 000000000..0365768ca --- /dev/null +++ b/packages/ats/contracts/contracts/layer_2/interfaces/beneficiaries/IBeneficiaries.sol @@ -0,0 +1,265 @@ +/* + 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. + +*/ + +pragma solidity 0.8.18; + +// SPDX-License-Identifier: MIT + +interface IBeneficiaries { + event BeneficiaryAdded( + address indexed operator, + address indexed beneficiary, + bytes data + ); + + event BeneficiaryRemoved( + address indexed operator, + address indexed beneficiary + ); + + event BeneficiaryDataUpdated( + address indexed operator, + address indexed beneficiary, + bytes newData + ); + + error BeneficiaryAlreadyExists(address beneficiary); + error BeneficiaryNotFound(address beneficiary); + + /** + * @notice Initializes the beneficiaries contract with a list of initial beneficiaries. + * @param _beneficiaries An array of addresses representing the initial beneficiaries. + */ + // solhint-disable-next-line func-name-mixedcase + function initialize_Beneficiaries( + address[] calldata _beneficiaries, + bytes[] calldata _data + ) external; + + function addBeneficiary( + address _beneficiary, + bytes calldata _data + ) external; + + function removeBeneficiary(address _beneficiary) external; + + function updateBeneficiaryData( + address _beneficiary, + bytes calldata _data + ) external; + + function isBeneficiary(address _beneficiary) external view returns (bool); + + function getBeneficiaryData( + address _beneficiary + ) external view returns (bytes memory); + + function getBeneficiariesCount() external view returns (uint256); + + function getBeneficiaries( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory beneficiaries_); +} diff --git a/packages/ats/contracts/contracts/test/testTimeTravel/facetsTimeTravel/BeneficiariesFacetTimeTravel.sol b/packages/ats/contracts/contracts/test/testTimeTravel/facetsTimeTravel/BeneficiariesFacetTimeTravel.sol new file mode 100644 index 000000000..47c399b3b --- /dev/null +++ b/packages/ats/contracts/contracts/test/testTimeTravel/facetsTimeTravel/BeneficiariesFacetTimeTravel.sol @@ -0,0 +1,238 @@ +/* + 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: BSD-3-Clause-Attribution +pragma solidity 0.8.18; + +import { + BeneficiariesFacet +} from '../../../layer_2/beneficiaries/BeneficiariesFacet.sol'; +import { + TimeTravelStorageWrapper +} from '../timeTravel/TimeTravelStorageWrapper.sol'; +import {LocalContext} from '../../../layer_0/context/LocalContext.sol'; + +contract BeneficiariesFacetTimeTravel is + BeneficiariesFacet, + TimeTravelStorageWrapper +{ + function _blockTimestamp() + internal + view + override(LocalContext, TimeTravelStorageWrapper) + returns (uint256) + { + return TimeTravelStorageWrapper._blockTimestamp(); + } + + function _blockNumber() + internal + view + override(LocalContext, TimeTravelStorageWrapper) + returns (uint256) + { + return TimeTravelStorageWrapper._blockNumber(); + } +} diff --git a/packages/ats/contracts/scripts/businessLogicResolver.ts b/packages/ats/contracts/scripts/businessLogicResolver.ts index 582dfa833..0d061005e 100644 --- a/packages/ats/contracts/scripts/businessLogicResolver.ts +++ b/packages/ats/contracts/scripts/businessLogicResolver.ts @@ -271,6 +271,7 @@ export interface DeployedBusinessLogics { holdReadFacet: IStaticFunctionSelectors holdManagementFacet: IStaticFunctionSelectors holdTokenHolderFacet: IStaticFunctionSelectors + beneficiariesFacet: IStaticFunctionSelectors externalPauseManagementFacet: IStaticFunctionSelectors externalControlListManagementFacet: IStaticFunctionSelectors externalKycListManagementFacet: IStaticFunctionSelectors diff --git a/packages/ats/contracts/scripts/commands/CreateConfigurationsForDeployedContractsCommand.ts b/packages/ats/contracts/scripts/commands/CreateConfigurationsForDeployedContractsCommand.ts index acf90d51b..75ddd67ba 100644 --- a/packages/ats/contracts/scripts/commands/CreateConfigurationsForDeployedContractsCommand.ts +++ b/packages/ats/contracts/scripts/commands/CreateConfigurationsForDeployedContractsCommand.ts @@ -251,7 +251,10 @@ export default class CreateConfigurationsForDeployedContractsCommand extends Bas overrides, }) this.equityUsaAddress = equityUsaFacet.address - this.excludeEquityAddresses = [deployedContractList.bondUsaRead.address] + this.excludeEquityAddresses = [ + deployedContractList.bondUsaRead.address, + deployedContractList.beneficiariesFacet.address, + ] this.bondUsaAddress = bondUsaFacet.address this.excludeBondAddresses = [ deployedContractList.adjustBalancesFacet.address, diff --git a/packages/ats/contracts/scripts/constants.ts b/packages/ats/contracts/scripts/constants.ts index ee415629a..ec5df7063 100644 --- a/packages/ats/contracts/scripts/constants.ts +++ b/packages/ats/contracts/scripts/constants.ts @@ -288,6 +288,8 @@ export const MATURITY_REDEEMER_ROLE = '0xa0d696902e9ed231892dc96649f0c62b808a1cb9dd1269e78e0adc1cc4b8358c' export const TREX_OWNER_ROLE = '0x03ce2fdc316501dd97f5219e6ad908a3238f1e90f910aa17b627f801a6aafab7' +export const BENEFICIARY_MANAGER_ROLE = + '0xebc53fe99fea28c7aa9476a714959af5b931f34a8a8734365ec63113198d512f' // * Errors export const IS_PAUSED_ERROR_ID = '0x40' export const OPERATOR_ACCOUNT_BLOCKED_ERROR_ID = '0x41' diff --git a/packages/ats/contracts/scripts/deploy.ts b/packages/ats/contracts/scripts/deploy.ts index 134e73fc0..4d4de47e7 100644 --- a/packages/ats/contracts/scripts/deploy.ts +++ b/packages/ats/contracts/scripts/deploy.ts @@ -327,6 +327,8 @@ import { TimeTravel__factory, ProxyAdmin__factory, TransparentUpgradeableProxy__factory, + BeneficiariesFacetTimeTravel__factory, + BeneficiariesFacet__factory, } from '@typechain' export let environment = Environment.empty() @@ -391,7 +393,6 @@ export async function deployAtsFullInfrastructure({ signer, }) await registerDeployedContractBusinessLogics(registerCommand) - // * Create configurations for all Securities (EquityUSA, BondUSA) console.log(MESSAGES.businessLogicResolver.info.creatingConfigurations) const createCommand = @@ -887,6 +888,19 @@ export async function deployAtsContracts({ : undefined, overrides, }), + beneficiaries: new DeployContractWithFactoryCommand({ + factory: getFactory( + new BeneficiariesFacet__factory(), + new BeneficiariesFacetTimeTravel__factory() + ), + signer, + deployedContract: useDeployed + ? Configuration.contracts.BeneficiariesFacet.addresses?.[ + network + ] + : undefined, + overrides, + }), externalPauseManagementFacet: new DeployContractWithFactoryCommand({ factory: getFactory( new ExternalPauseManagementFacet__factory(), @@ -1356,6 +1370,14 @@ export async function deployAtsContracts({ ) return result }), + beneficiariesFacet: await deployContractWithFactory( + commands.beneficiaries + ).then((result) => { + console.log( + `Beneficiaries has been deployed successfully at ${result.address}` + ) + return result + }), externalPauseManagementFacet: await deployContractWithFactory( commands.externalPauseManagementFacet ).then((result) => { diff --git a/packages/ats/contracts/scripts/deployEnvironmentByRpc.ts b/packages/ats/contracts/scripts/deployEnvironmentByRpc.ts index 20b6995e7..72a09dcc6 100644 --- a/packages/ats/contracts/scripts/deployEnvironmentByRpc.ts +++ b/packages/ats/contracts/scripts/deployEnvironmentByRpc.ts @@ -309,6 +309,7 @@ function buildEmptyEnvironment(): Environment { externalControlListManagementFacet: {} as IStaticFunctionSelectors, externalKycListManagementFacet: {} as IStaticFunctionSelectors, freezeFacet: {} as IStaticFunctionSelectors, + beneficiariesFacet: {} as IStaticFunctionSelectors, ERC3643Management: {} as IStaticFunctionSelectors, ERC3643Operations: {} as IStaticFunctionSelectors, ERC3643Read: {} as IStaticFunctionSelectors, diff --git a/packages/ats/contracts/scripts/factory.ts b/packages/ats/contracts/scripts/factory.ts index 4bbf220f4..7d3ef3847 100644 --- a/packages/ats/contracts/scripts/factory.ts +++ b/packages/ats/contracts/scripts/factory.ts @@ -311,6 +311,8 @@ export interface BondData { security: SecurityData bondDetails: BondDetailsData couponDetails: CouponDetailsData + beneficiaries: string[] + beneficiariesData: string[] } export interface AdditionalSecurityData { @@ -521,6 +523,8 @@ export async function setBondData({ externalKycLists, compliance, identityRegistry, + beneficiariesList, + beneficiariesListData, }: { adminAccount: string isWhiteList: boolean @@ -551,6 +555,8 @@ export async function setBondData({ externalKycLists?: string[] compliance?: string identityRegistry?: string + beneficiariesList?: string[] + beneficiariesListData?: string[] }) { let rbacs: Rbac[] = [] @@ -612,10 +618,15 @@ export async function setBondData({ firstCouponDate: firstCouponDate, } + const beneficiaries = beneficiariesList ?? [] + const beneficiariesData = beneficiariesListData ?? [] + const bondData: BondData = { security, bondDetails, couponDetails, + beneficiaries, + beneficiariesData, } return bondData @@ -780,6 +791,8 @@ export async function deployBondFromFactory({ businessLogicResolver, compliance, identityRegistry, + beneficiariesList, + beneficiariesListData, }: { adminAccount: string isWhiteList: boolean @@ -813,6 +826,8 @@ export async function deployBondFromFactory({ businessLogicResolver: string compliance?: string identityRegistry?: string + beneficiariesList?: string[] + beneficiariesListData?: string[] }) { const bondData = await setBondData({ adminAccount, @@ -841,6 +856,8 @@ export async function deployBondFromFactory({ businessLogicResolver, compliance, identityRegistry, + beneficiariesList, + beneficiariesListData, }) const factoryRegulationData = await setFactoryRegulationData( diff --git a/packages/ats/contracts/scripts/results/DeployAtsContractsResult.ts b/packages/ats/contracts/scripts/results/DeployAtsContractsResult.ts index 878ede07f..e5b46461f 100644 --- a/packages/ats/contracts/scripts/results/DeployAtsContractsResult.ts +++ b/packages/ats/contracts/scripts/results/DeployAtsContractsResult.ts @@ -251,6 +251,7 @@ import { SsiManagementFacet, TransferAndLockFacet, ERC20Votes, + Beneficiaries, } from '@typechain' import { DeployContractWithFactoryResult } from '../index' @@ -292,6 +293,7 @@ export interface DeployAtsContractsResultParams { clearingHoldCreationFacet: DeployContractWithFactoryResult clearingReadFacet: DeployContractWithFactoryResult clearingActionsFacet: DeployContractWithFactoryResult + beneficiariesFacet: DeployContractWithFactoryResult externalPauseManagementFacet: DeployContractWithFactoryResult externalControlListManagementFacet: DeployContractWithFactoryResult externalKycListManagementFacet: DeployContractWithFactoryResult @@ -342,6 +344,7 @@ export default class DeployAtsContractsResult { public readonly clearingHoldCreationFacet: DeployContractWithFactoryResult public readonly clearingReadFacet: DeployContractWithFactoryResult public readonly clearingActionsFacet: DeployContractWithFactoryResult + public readonly beneficiariesFacet: DeployContractWithFactoryResult public readonly externalPauseManagementFacet: DeployContractWithFactoryResult public readonly externalControlListManagementFacet: DeployContractWithFactoryResult public readonly externalKycListManagementFacet: DeployContractWithFactoryResult @@ -388,6 +391,7 @@ export default class DeployAtsContractsResult { clearingHoldCreationFacet, clearingReadFacet, clearingActionsFacet, + beneficiariesFacet, externalPauseManagementFacet, externalControlListManagementFacet, externalKycListManagementFacet, @@ -439,6 +443,7 @@ export default class DeployAtsContractsResult { this.clearingHoldCreationFacet = clearingHoldCreationFacet this.clearingReadFacet = clearingReadFacet this.clearingActionsFacet = clearingActionsFacet + this.beneficiariesFacet = beneficiariesFacet this.externalPauseManagementFacet = externalPauseManagementFacet this.externalControlListManagementFacet = externalControlListManagementFacet diff --git a/packages/ats/contracts/tasks/deploy.ts b/packages/ats/contracts/tasks/deploy.ts index 3a4539048..e925bcb94 100644 --- a/packages/ats/contracts/tasks/deploy.ts +++ b/packages/ats/contracts/tasks/deploy.ts @@ -301,6 +301,7 @@ task( clearingHoldCreationFacet, clearingReadFacet, externalPauseManagementFacet, + beneficiariesFacet, externalControlListManagementFacet, externalKycListManagementFacet, protectedPartitionsFacet, @@ -362,6 +363,7 @@ task( 'Clearing Redeem Facet': clearingRedeemFacet.address, 'Clearing Hold Creation Facet': clearingHoldCreationFacet.address, 'Clearing Read Facet': clearingReadFacet.address, + 'Beneficiaries Facet': beneficiariesFacet.address, 'External Pause Management Facet': externalPauseManagementFacet.address, 'External Control List Management Facet': diff --git a/packages/ats/contracts/test/unitTests/layer_1/beneficiaries/beneficiaries.test.ts b/packages/ats/contracts/test/unitTests/layer_1/beneficiaries/beneficiaries.test.ts new file mode 100644 index 000000000..e8d355809 --- /dev/null +++ b/packages/ats/contracts/test/unitTests/layer_1/beneficiaries/beneficiaries.test.ts @@ -0,0 +1,316 @@ +import { expect } from 'chai' +import { ethers } from 'hardhat' +import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers.js' +import { isinGenerator } from '@thomaschaplin/isin-generator' +import { + BusinessLogicResolver, + Beneficiaries, + Beneficiaries__factory, + IFactory, + ResolverProxy, + AccessControl, + AccessControlFacet__factory, + Pause, + PauseFacet__factory, +} from '@typechain' +import { + deployAtsFullInfrastructure, + DeployAtsFullInfrastructureCommand, + deployBondFromFactory, + GAS_LIMIT, + BENEFICIARY_MANAGER_ROLE, + RegulationSubType, + RegulationType, + PAUSER_ROLE, +} from '@scripts' + +const BENEFICIARY_1 = '0x1234567890123456789012345678901234567890' +const BENEFICIARY_1_DATA = '0xabcdef' +const BENEFICIARY_2 = '0x2345678901234567890123456789012345678901' +const BENEFICIARY_2_DATA = '0x88888888' +const numberOfUnits = 1000 +let startingDate = 999999999999990 +const couponRateDecimals = 2 +const couponFrequency = 0 +const couponRate = 0 +let maturityDate = 999999999999999 +let firstCouponDate = 0 +const countriesControlListType = true +const listOfCountries = 'ES,FR,CH' +const info = 'info' + +describe('Beneficiaries Tests', () => { + let signer_A: SignerWithAddress + let signer_B: SignerWithAddress + let account_A: string + + let diamond: ResolverProxy + let factory: IFactory + let businessLogicResolver: BusinessLogicResolver + let beneficiariesFacet: Beneficiaries + let accessControlFacet: AccessControl + let pauseFacet: Pause + + before(async () => { + // mute | mock console.log + console.log = () => {} + ;[signer_A, signer_B] = await ethers.getSigners() + account_A = signer_A.address + + const { ...deployedContracts } = await deployAtsFullInfrastructure( + await DeployAtsFullInfrastructureCommand.newInstance({ + signer: signer_A, + useDeployed: false, + useEnvironment: false, + timeTravelEnabled: true, + }) + ) + + factory = deployedContracts.factory.contract + businessLogicResolver = deployedContracts.businessLogicResolver.contract + }) + + beforeEach(async () => { + // Deploy a fresh diamond proxy (implicitly initialized) + diamond = await deployBondFromFactory({ + adminAccount: account_A, + isWhiteList: false, + isControllable: true, + arePartitionsProtected: false, + clearingActive: false, + internalKycActivated: false, + isMultiPartition: false, + name: 'TEST_Beneficiaries', + symbol: 'TB', + decimals: 6, + isin: isinGenerator(), + currency: '0x455552', + numberOfUnits, + nominalValue: 100, + startingDate, + maturityDate, + couponFrequency, + couponRate, + couponRateDecimals, + firstCouponDate, + regulationType: RegulationType.REG_D, + regulationSubType: RegulationSubType.REG_D_506_C, + countriesControlListType, + listOfCountries, + info, + factory, + businessLogicResolver: businessLogicResolver.address, + beneficiariesList: [BENEFICIARY_2], + beneficiariesListData: [BENEFICIARY_2_DATA], + }) + + beneficiariesFacet = Beneficiaries__factory.connect( + diamond.address, + signer_A + ) + + accessControlFacet = AccessControlFacet__factory.connect( + diamond.address, + signer_A + ) + + pauseFacet = PauseFacet__factory.connect(diamond.address, signer_A) + + await accessControlFacet.grantRole(BENEFICIARY_MANAGER_ROLE, account_A) + + await accessControlFacet.grantRole(PAUSER_ROLE, account_A) + }) + + describe('Initialization Tests', () => { + it('GIVEN a token WHEN initializing the beneficiary again THEN it reverts with AlreadyInitialized', async () => { + await expect( + beneficiariesFacet.initialize_Beneficiaries( + [BENEFICIARY_1], + [BENEFICIARY_1_DATA], + { gasLimit: GAS_LIMIT.default } + ) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'AlreadyInitialized' + ) + }) + }) + + describe('Add Tests', () => { + it('GIVEN an unlisted beneficiary WHEN unauthorized user adds it THEN it reverts with AccountHasNoRole', async () => { + await expect( + beneficiariesFacet + .connect(signer_B) + .addBeneficiary(BENEFICIARY_1, BENEFICIARY_1_DATA, { + gasLimit: GAS_LIMIT.default, + }) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'AccountHasNoRole' + ) + }) + + it('GIVEN an unlisted beneficiary WHEN user adds if token is paused THEN it reverts with TokenIsPaused', async () => { + await pauseFacet.pause({ gasLimit: GAS_LIMIT.default }) + + await expect( + beneficiariesFacet.addBeneficiary( + BENEFICIARY_1, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ).to.be.revertedWithCustomError(beneficiariesFacet, 'TokenIsPaused') + }) + + it('GIVEN a listed beneficiary WHEN adding it again THEN it reverts with BeneficiaryAlreadyExists', async () => { + await expect( + beneficiariesFacet.addBeneficiary( + BENEFICIARY_2, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'BeneficiaryAlreadyExists' + ) + }) + + it('GIVEN a unlisted beneficiary WHEN authorized user adds it THEN it is listed and event is emitted', async () => { + await expect( + beneficiariesFacet.addBeneficiary( + BENEFICIARY_1, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ) + .to.emit(beneficiariesFacet, 'BeneficiaryAdded') + .withArgs(signer_A.address, BENEFICIARY_1, BENEFICIARY_1_DATA) + + expect(await beneficiariesFacet.isBeneficiary(BENEFICIARY_1)).to.be + .true + + expect( + await beneficiariesFacet.getBeneficiaryData(BENEFICIARY_1) + ).to.equal(BENEFICIARY_1_DATA) + + expect(await beneficiariesFacet.getBeneficiariesCount()).to.equal(2) + + expect( + await beneficiariesFacet.getBeneficiaries(0, 100) + ).to.have.same.members([BENEFICIARY_2, BENEFICIARY_1]) + }) + }) + + describe('Remove Tests', () => { + it('GIVEN a listed beneficiary WHEN unauthorized user removes it THEN it reverts with AccountHasNoRole', async () => { + await expect( + beneficiariesFacet + .connect(signer_B) + .removeBeneficiary(BENEFICIARY_2, { + gasLimit: GAS_LIMIT.default, + }) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'AccountHasNoRole' + ) + }) + + it('GIVEN an listed beneficiary WHEN user removes it if token is paused THEN it reverts with TokenIsPaused', async () => { + await pauseFacet.pause({ gasLimit: GAS_LIMIT.default }) + await expect( + beneficiariesFacet.removeBeneficiary(BENEFICIARY_2, { + gasLimit: GAS_LIMIT.default, + }) + ).to.be.revertedWithCustomError(beneficiariesFacet, 'TokenIsPaused') + }) + + it('GIVEN a unlisted beneficiary WHEN removing it again THEN it reverts with BeneficiaryNotFound', async () => { + await expect( + beneficiariesFacet.removeBeneficiary(BENEFICIARY_1, { + gasLimit: GAS_LIMIT.default, + }) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'BeneficiaryNotFound' + ) + }) + + it('GIVEN a listed beneficiary WHEN authorized user removes it THEN it is removed and event is emitted', async () => { + await expect( + beneficiariesFacet.removeBeneficiary(BENEFICIARY_2, { + gasLimit: GAS_LIMIT.default, + }) + ) + .to.emit(beneficiariesFacet, 'BeneficiaryRemoved') + .withArgs(signer_A.address, BENEFICIARY_2) + + expect(await beneficiariesFacet.isBeneficiary(BENEFICIARY_2)).to.be + .false + + expect(await beneficiariesFacet.getBeneficiariesCount()).to.equal(0) + + expect( + await beneficiariesFacet.getBeneficiaries(0, 100) + ).to.have.same.members([]) + }) + }) + + describe('Update Data Tests', () => { + it('GIVEN a listed beneficiary WHEN unauthorized user updates its data THEN it reverts with AccountHasNoRole', async () => { + await expect( + beneficiariesFacet + .connect(signer_B) + .updateBeneficiaryData(BENEFICIARY_2, BENEFICIARY_1_DATA, { + gasLimit: GAS_LIMIT.default, + }) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'AccountHasNoRole' + ) + }) + + it('GIVEN an listed beneficiary WHEN user updates its data if token is paused THEN it reverts with TokenIsPaused', async () => { + await pauseFacet.pause({ gasLimit: GAS_LIMIT.default }) + await expect( + beneficiariesFacet.updateBeneficiaryData( + BENEFICIARY_2, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ).to.be.revertedWithCustomError(beneficiariesFacet, 'TokenIsPaused') + }) + + it('GIVEN a unlisted beneficiary WHEN updating its data THEN it reverts with BeneficiaryNotFound', async () => { + await expect( + beneficiariesFacet.updateBeneficiaryData( + BENEFICIARY_1, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ).to.be.revertedWithCustomError( + beneficiariesFacet, + 'BeneficiaryNotFound' + ) + }) + + it('GIVEN a listed beneficiary WHEN authorized user updates its data THEN it is updated and event is emitted', async () => { + expect( + await beneficiariesFacet.getBeneficiaryData(BENEFICIARY_2) + ).to.equal(BENEFICIARY_2_DATA) + + await expect( + beneficiariesFacet.updateBeneficiaryData( + BENEFICIARY_2, + BENEFICIARY_1_DATA, + { gasLimit: GAS_LIMIT.default } + ) + ) + .to.emit(beneficiariesFacet, 'BeneficiaryDataUpdated') + .withArgs(signer_A.address, BENEFICIARY_2, BENEFICIARY_1_DATA) + + expect( + await beneficiariesFacet.getBeneficiaryData(BENEFICIARY_2) + ).to.equal(BENEFICIARY_1_DATA) + }) + }) +}) diff --git a/packages/ats/sdk/__tests__/fixtures/beneficiary/BeneficiaryFixture.ts b/packages/ats/sdk/__tests__/fixtures/beneficiary/BeneficiaryFixture.ts new file mode 100644 index 000000000..5e72bffe9 --- /dev/null +++ b/packages/ats/sdk/__tests__/fixtures/beneficiary/BeneficiaryFixture.ts @@ -0,0 +1,62 @@ +import { HederaId } from '@domain/context/shared/HederaId'; +import { createFixture } from '../config'; +import { HederaIdPropsFixture } from '../shared/DataFixture'; +import { IsBeneficiaryQuery } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery'; +import { AddBeneficiaryCommand } from '@command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand'; +import { RemoveBeneficiaryCommand } from '@command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand'; +import { UpdateBeneficiaryDataCommand } from '@command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand'; +import { GetBeneficiaryDataQuery } from '@query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery'; +import { GetBeneficiariesCountQuery } from '@query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery'; +import { GetBeneficiariesQuery } from '@query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery'; + +export const IsBeneficiaryQueryFixture = createFixture( + (query) => { + query.securityId.as( + () => new HederaId(HederaIdPropsFixture.create().value), + ); + query.targetId.as(() => new HederaId(HederaIdPropsFixture.create().value)); + }, +); + +export const GetBeneficiaryDataQueryFixture = + createFixture((query) => { + query.securityId.as( + () => new HederaId(HederaIdPropsFixture.create().value), + ); + query.targetId.as(() => new HederaId(HederaIdPropsFixture.create().value)); + }); +export const GetBeneficiariesCountQueryFixture = + createFixture((query) => { + query.securityId.as( + () => new HederaId(HederaIdPropsFixture.create().value), + ); + }); + +export const GetBeneficiariesQueryFixture = + createFixture((query) => { + query.securityId.as( + () => new HederaId(HederaIdPropsFixture.create().value), + ); + query.pageIndex.faker((f) => f.number.int({ min: 1, max: 20 })); + query.pageSize.faker((f) => f.number.int({ min: 1, max: 100 })); + }); + +export const AddBeneficiaryCommandFixture = + createFixture((command) => { + command.securityId.as(() => HederaIdPropsFixture.create().value); + command.beneficiary.as(() => HederaIdPropsFixture.create().value); + command.data?.as(() => '0x'); + }); + +export const RemoveBeneficiaryCommandFixture = + createFixture((command) => { + command.securityId.as(() => HederaIdPropsFixture.create().value); + command.beneficiary.as(() => HederaIdPropsFixture.create().value); + }); + +export const UpdateBeneficiaryDataCommandFixture = + createFixture((command) => { + command.securityId.as(() => HederaIdPropsFixture.create().value); + command.beneficiary.as(() => HederaIdPropsFixture.create().value); + command.data.as(() => '0x'); + }); diff --git a/packages/ats/sdk/__tests__/fixtures/bond/BondFixture.ts b/packages/ats/sdk/__tests__/fixtures/bond/BondFixture.ts index 9a7a62725..3ae3c1eab 100644 --- a/packages/ats/sdk/__tests__/fixtures/bond/BondFixture.ts +++ b/packages/ats/sdk/__tests__/fixtures/bond/BondFixture.ts @@ -245,7 +245,16 @@ import { GetTotalCouponHoldersQuery } from '@query/bond/coupons/getTotalCouponHo import GetCouponHoldersRequest from '@port/in/request/bond/GetCouponHoldersRequest'; import GetTotalCouponHoldersRequest from '@port/in/request/bond/GetTotalCouponHoldersRequest'; import { CreateTrexSuiteBondCommand } from '@command/bond/createTrexSuite/CreateTrexSuiteBondCommand'; -import { CreateTrexSuiteBondRequest } from 'src'; +import { + CreateTrexSuiteBondRequest, + GetBeneficiariesCountRequest, + GetBeneficiariesRequest, + GetBeneficiaryDataRequest, + IsBeneficiaryRequest, +} from 'src'; +import AddBeneficiaryRequest from '@port/in/request/bond/AddBeneficiaryRequest'; +import RemoveBeneficiaryRequest from '@port/in/request/bond/RemoveBeneficiaryRequest'; +import UpdateBeneficiaryDataRequest from '@port/in/request/bond/UpdateBeneficiaryDataRequest'; export const SetCouponCommandFixture = createFixture( (command) => { @@ -297,6 +306,10 @@ export const CreateBondCommandFixture = createFixture( ]); command.complianceId?.as(() => HederaIdPropsFixture.create().value); command.identityRegistryId?.as(() => HederaIdPropsFixture.create().value); + command.beneficiariesIds?.faker((faker) => [ + HederaIdPropsFixture.create().value, + ]); + command.beneficiariesData?.as(() => ['0x0000']); }, ); @@ -350,6 +363,12 @@ export const CreateTrexSuiteBondCommandFixture = command.externalKycLists?.as(() => [HederaIdPropsFixture.create().value]); command.compliance?.as(() => HederaIdPropsFixture.create().value); command.identityRegistry?.as(() => HederaIdPropsFixture.create().value); + command.beneficiariesIds?.faker((faker) => [ + faker.finance.ethereumAddress(), + ]); + command.beneficiariesData?.faker((faker) => [ + faker.string.alphanumeric({ length: 32 }), + ]); }); export const UpdateMaturityDateCommandFixture = @@ -526,6 +545,10 @@ export const CreateBondRequestFixture = createFixture( ]); request.complianceId?.as(() => HederaIdPropsFixture.create().value); request.identityRegistryId?.as(() => HederaIdPropsFixture.create().value); + request.beneficiariesIds?.faker((faker) => [ + HederaIdPropsFixture.create().value, + ]); + request.beneficiariesData?.as(() => ['0x0000']); }, ); @@ -680,6 +703,10 @@ export const CreateTrexSuiteBondRequestFixture = ); request.configVersion.as(() => 1); request.diamondOwnerAccount?.as(() => HederaIdPropsFixture.create().value); + request.beneficiariesIds?.faker((faker) => [ + faker.finance.ethereumAddress(), + ]); + request.beneficiariesData?.faker((faker) => ['0x0000']); request.externalPauses?.as(() => [HederaIdPropsFixture.create().value]); request.externalControlLists?.as(() => [ HederaIdPropsFixture.create().value, @@ -688,3 +715,46 @@ export const CreateTrexSuiteBondRequestFixture = request.complianceId?.as(() => HederaIdPropsFixture.create().value); request.identityRegistryId?.as(() => HederaIdPropsFixture.create().value); }); + +export const AddBeneficiaryRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.beneficiaryId.as(() => HederaIdPropsFixture.create().value); + request.data?.as(() => '0x'); + }); +export const UpdateBeneficiaryDataRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.beneficiaryId.as(() => HederaIdPropsFixture.create().value); + request.data.as(() => '0x'); + }); + +export const RemoveBeneficiaryRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.beneficiaryId.as(() => HederaIdPropsFixture.create().value); + }); + +export const IsBeneficiaryRequestFixture = createFixture( + (request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.beneficiaryId.as(() => HederaIdPropsFixture.create().value); + }, +); + +export const GetBeneficiariesRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.pageIndex.faker((faker) => faker.number.int({ min: 1, max: 10 })); + request.pageSize.faker((faker) => faker.number.int({ min: 1, max: 50 })); + }); + +export const GetBeneficiariesCountRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + }); +export const GetBeneficiaryDataRequestFixture = + createFixture((request) => { + request.securityId.as(() => HederaIdPropsFixture.create().value); + request.beneficiaryId.as(() => HederaIdPropsFixture.create().value); + }); diff --git a/packages/ats/sdk/__tests__/fixtures/erc1400/ERC1400Fixture.ts b/packages/ats/sdk/__tests__/fixtures/erc1400/ERC1400Fixture.ts index bf3719b8a..c58b4bc96 100644 --- a/packages/ats/sdk/__tests__/fixtures/erc1400/ERC1400Fixture.ts +++ b/packages/ats/sdk/__tests__/fixtures/erc1400/ERC1400Fixture.ts @@ -219,14 +219,14 @@ import { GetMaxSupplyByPartitionQuery } from '@query/security/cap/getMaxSupplyBy import { GetTotalSupplyByPartitionQuery } from '@query/security/cap/getTotalSupplyByPartition/GetTotalSupplyByPartitionQuery'; import { IsOperatorQuery } from '@query/security/operator/isOperator/IsOperatorQuery'; import { IsOperatorForPartitionQuery } from '@query/security/operator/isOperatorForPartition/IsOperatorForPartitionQuery'; +import GetAccountBalanceRequest from '@port/in/request/account/GetAccountBalanceRequest'; +import SetMaxSupplyRequest from '@port/in/request/security/operations/cap/SetMaxSupplyRequest'; +import GetMaxSupplyRequest from '@port/in/request/security/operations/cap/GetMaxSupplyRequest'; export const BalanceOfQueryFixture = createFixture((query) => { query.securityId.as(() => new HederaId(HederaIdPropsFixture.create().value)); query.targetId.as(() => new HederaId(HederaIdPropsFixture.create().value)); }); -import GetAccountBalanceRequest from '@port/in/request/account/GetAccountBalanceRequest'; -import SetMaxSupplyRequest from '@port/in/request/security/operations/cap/SetMaxSupplyRequest'; -import GetMaxSupplyRequest from '@port/in/request/security/operations/cap/GetMaxSupplyRequest'; export const GetSecurityDetailsRequestFixture = createFixture((request) => { diff --git a/packages/ats/sdk/__tests__/fixtures/shared/SecurityFixture.ts b/packages/ats/sdk/__tests__/fixtures/shared/SecurityFixture.ts index ea3b40cff..83d6cc313 100644 --- a/packages/ats/sdk/__tests__/fixtures/shared/SecurityFixture.ts +++ b/packages/ats/sdk/__tests__/fixtures/shared/SecurityFixture.ts @@ -229,6 +229,7 @@ export const SecurityPropsFixture = createFixture((security) => { ); security.decimals.faker((faker) => faker.number.int({ min: 0, max: 18 })); security.isWhiteList.faker((faker) => faker.datatype.boolean()); + security.erc20VotesActivated?.faker((faker) => faker.datatype.boolean()); security.isControllable.faker((faker) => faker.datatype.boolean()); security.arePartitionsProtected.faker((faker) => faker.datatype.boolean()); security.clearingActive.faker((faker) => faker.datatype.boolean()); diff --git a/packages/ats/sdk/eslint.config.mjs b/packages/ats/sdk/eslint.config.mjs index 67bf953cd..fde2049cd 100644 --- a/packages/ats/sdk/eslint.config.mjs +++ b/packages/ats/sdk/eslint.config.mjs @@ -62,4 +62,4 @@ const sdkConfig = baseConfig }, ]); -export default sdkConfig; \ No newline at end of file +export default sdkConfig; diff --git a/packages/ats/sdk/prettier.config.mjs b/packages/ats/sdk/prettier.config.mjs index 9f45a1663..a10de9eed 100644 --- a/packages/ats/sdk/prettier.config.mjs +++ b/packages/ats/sdk/prettier.config.mjs @@ -4,4 +4,4 @@ */ import baseConfig from '../../../prettier.config.mjs'; -export default baseConfig; \ No newline at end of file +export default baseConfig; diff --git a/packages/ats/sdk/src/app/service/validation/ValidationService.ts b/packages/ats/sdk/src/app/service/validation/ValidationService.ts index 290280e72..87ce2aca1 100644 --- a/packages/ats/sdk/src/app/service/validation/ValidationService.ts +++ b/packages/ats/sdk/src/app/service/validation/ValidationService.ts @@ -268,6 +268,9 @@ import { IsInternalKycActivatedQuery } from '@query/security/kyc/isInternalKycAc import { IsExternallyGrantedQuery } from '@query/security/externalKycLists/isExternallyGranted/IsExternallyGrantedQuery'; import { GetTokenBySaltQuery } from '@query/factory/trex/getTokenBySalt/GetTokenBySaltQuery'; import { InvalidTrexTokenSalt } from '@domain/context/factory/error/InvalidTrexTokenSalt'; +import { IsBeneficiaryQuery } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery'; +import { AccountIsNotBeneficiary } from '@domain/context/security/error/operations/AccountIsNotBeneficiary'; +import { AccountIsBeneficiary } from '@domain/context/security/error/operations/AccountIsBeneficiary'; @singleton() export default class ValidationService extends Service { @@ -764,4 +767,37 @@ export default class ValidationService extends Service { ); return kycResult.payload === kycStatus; } + + async checkIsBeneficiary( + securityId: string, + beneficiary: string, + ): Promise { + this.queryBus = Injectable.resolve(QueryBus); + const res = ( + await this.queryBus.execute( + new IsBeneficiaryQuery(securityId, beneficiary), + ) + ).payload; + if (!res) { + throw new AccountIsNotBeneficiary(securityId, beneficiary); + } + + return res; + } + async checkIsNotBeneficiary( + securityId: string, + beneficiary: string, + ): Promise { + this.queryBus = Injectable.resolve(QueryBus); + const res = ( + await this.queryBus.execute( + new IsBeneficiaryQuery(securityId, beneficiary), + ) + ).payload; + if (res) { + throw new AccountIsBeneficiary(securityId, beneficiary); + } + + return !res; + } } diff --git a/packages/ats/sdk/src/app/service/validation/ValidationService.unit.test.ts b/packages/ats/sdk/src/app/service/validation/ValidationService.unit.test.ts index a45e10e52..685dac015 100644 --- a/packages/ats/sdk/src/app/service/validation/ValidationService.unit.test.ts +++ b/packages/ats/sdk/src/app/service/validation/ValidationService.unit.test.ts @@ -273,6 +273,9 @@ import { OperationNotAllowed } from '@domain/context/security/error/operations/O import { KycStatus } from '@domain/context/kyc/Kyc'; import { IsInternalKycActivatedQuery } from '@query/security/kyc/isInternalKycActivated/IsInternalKycActivatedQuery'; import { IsExternallyGrantedQuery } from '@query/security/externalKycLists/isExternallyGranted/IsExternallyGrantedQuery'; +import { IsBeneficiaryQuery } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery'; +import { AccountIsNotBeneficiary } from '@domain/context/security/error/operations/AccountIsNotBeneficiary'; +import { AccountIsBeneficiary } from '@domain/context/security/error/operations/AccountIsBeneficiary'; describe('ValidationService', () => { let service: ValidationService; @@ -1313,4 +1316,48 @@ describe('ValidationService', () => { ).rejects.toThrow(OperationNotAllowed); }); }); + + describe('checkIsBeneficiary', () => { + it('should resolve successfully when address is a beneficiary', async () => { + queryBusMock.execute.mockResolvedValueOnce({ payload: true }); + const res = await service.checkIsBeneficiary( + securityId.value, + targetId.value, + ); + + expect(res).toBe(true); + expect(queryBusMock.execute).toHaveBeenCalledWith( + new IsBeneficiaryQuery(securityId.value, targetId.value), + ); + }); + + it('should throw AccountIsNotBeneficiary when security is not issuable', async () => { + queryBusMock.execute.mockResolvedValueOnce({ payload: false }); + await expect( + service.checkIsBeneficiary(securityId.value, targetId.value), + ).rejects.toThrow(AccountIsNotBeneficiary); + }); + }); + + describe('checkIsNotBeneficiary', () => { + it('should resolve successfully when address is not a beneficiary', async () => { + queryBusMock.execute.mockResolvedValueOnce({ payload: false }); + const res = await service.checkIsNotBeneficiary( + securityId.value, + targetId.value, + ); + + expect(res).toBe(true); + expect(queryBusMock.execute).toHaveBeenCalledWith( + new IsBeneficiaryQuery(securityId.value, targetId.value), + ); + }); + + it('should throw AccountIsBeneficiary when security is not issuable', async () => { + queryBusMock.execute.mockResolvedValueOnce({ payload: true }); + await expect( + service.checkIsNotBeneficiary(securityId.value, targetId.value), + ).rejects.toThrow(AccountIsBeneficiary); + }); + }); }); diff --git a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommand.ts b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommand.ts index ab30f5e16..baad25954 100644 --- a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommand.ts +++ b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommand.ts @@ -235,6 +235,8 @@ export class CreateBondCommand extends Command { public readonly externalKycListsIds?: string[], public readonly complianceId?: string, public readonly identityRegistryId?: string, + public readonly beneficiariesIds?: string[], + public readonly beneficiariesData?: string[], ) { super(); } diff --git a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.ts b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.ts index b5e52d5ac..dc56695b9 100644 --- a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.ts +++ b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.ts @@ -262,6 +262,8 @@ export class CreateBondCommandHandler externalKycListsIds, complianceId, identityRegistryId, + beneficiariesIds, + beneficiariesData, } = command; //TODO: Boy scout: remove request validations and adjust test @@ -308,6 +310,14 @@ export class CreateBondCommandHandler this.contractService.getEvmAddressesFromHederaIds(externalKycListsIds), ]); + let beneficiariesEvmAddresses: EvmAddress[] = []; + if (beneficiariesIds) + beneficiariesEvmAddresses = await Promise.all( + beneficiariesIds.map( + async (id) => await this.accountService.getAccountEvmAddress(id), + ), + ); + const complianceEvmAddress = complianceId ? await this.contractService.getContractEvmAddress(complianceId) : new EvmAddress(EVM_ZERO_ADDRESS); @@ -338,6 +348,8 @@ export class CreateBondCommandHandler externalControlListsEvmAddresses, externalKycListsEvmAddresses, diamondOwnerAccountEvmAddress, + beneficiariesEvmAddresses, + beneficiariesData, factory.toString(), ); diff --git a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.unit.test.ts index e066471d2..96c3abdc6 100644 --- a/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.unit.test.ts +++ b/packages/ats/sdk/src/app/usecase/command/bond/create/CreateBondCommandHandler.unit.test.ts @@ -357,7 +357,9 @@ describe('CreateBondCommandHandler', () => { .mockResolvedValueOnce([externalPauseEvmAddress]) .mockResolvedValueOnce([externalControlEvmAddress]) .mockResolvedValueOnce([externalKycEvmAddress]); - accountServiceMock.getAccountEvmAddress.mockResolvedValue(evmAddress); + accountServiceMock.getAccountEvmAddress + .mockResolvedValue(evmAddress) + .mockResolvedValue(evmAddress); transactionServiceMock.getHandler().createBond.mockResolvedValue({ id: transactionId, @@ -384,7 +386,7 @@ describe('CreateBondCommandHandler', () => { contractServiceMock.getEvmAddressesFromHederaIds, ).toHaveBeenCalledTimes(3); expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes( - 1, + 2, ); expect( transactionServiceMock.getHandler().createBond, @@ -415,6 +417,8 @@ describe('CreateBondCommandHandler', () => { [externalControlEvmAddress], [externalKycEvmAddress], evmAddress, + [evmAddress], + command.beneficiariesData, command.factory?.toString(), ); expect( diff --git a/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommand.ts b/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommand.ts index 46c78c418..d05a7e76d 100644 --- a/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommand.ts +++ b/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommand.ts @@ -244,6 +244,9 @@ export class CreateTrexSuiteBondCommand extends Command await this.accountService.getAccountEvmAddress(id), + ), + ); + const diamondOwnerAccountEvmAddress: EvmAddress = await this.accountService.getAccountEvmAddress(diamondOwnerAccount!); const resolverEvmAddress: EvmAddress = @@ -371,6 +383,8 @@ export class CreateTrexSuiteBondCommandHandler complianceEvmAddress, identityRegistryAddress, diamondOwnerAccountEvmAddress, + beneficiariesEvmAddresses, + beneficiariesData, externalPausesEvmAddresses, externalControlListsEvmAddresses, externalKycListsEvmAddresses, diff --git a/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommandHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommandHandler.unit.test.ts index 49f88ee93..40e02eab1 100644 --- a/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommandHandler.unit.test.ts +++ b/packages/ats/sdk/src/app/usecase/command/bond/createTrexSuite/CreateTrexSuiteBondCommandHandler.unit.test.ts @@ -299,7 +299,8 @@ describe('CreateTrexSuiteBondCommandHandler', () => { contractServiceMock.getEvmAddressesFromHederaIds .mockResolvedValueOnce([externalPauseEvmAddress]) .mockResolvedValueOnce([externalControlEvmAddress]) - .mockResolvedValueOnce([externalKycEvmAddress]); + .mockResolvedValueOnce([externalKycEvmAddress]) + .mockResolvedValueOnce([evmAddress]); // beneficiaries accountServiceMock.getAccountEvmAddress.mockResolvedValue(evmAddress); transactionServiceMock @@ -330,7 +331,7 @@ describe('CreateTrexSuiteBondCommandHandler', () => { contractServiceMock.getEvmAddressesFromHederaIds, ).toHaveBeenCalledTimes(3); expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes( - 1, + 2, ); expect( transactionServiceMock.getHandler().createTrexSuiteBond, @@ -369,6 +370,8 @@ describe('CreateTrexSuiteBondCommandHandler', () => { evmAddress, evmAddress, evmAddress, + [evmAddress], + command.beneficiariesData, [externalPauseEvmAddress], [externalControlEvmAddress], [externalKycEvmAddress], diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand.ts new file mode 100644 index 000000000..79c77ebc2 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand.ts @@ -0,0 +1,191 @@ +/* + 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 { Command } from '@core/command/Command'; +import { CommandResponse } from '@core/command/CommandResponse'; + +export class AddBeneficiaryCommandResponse implements CommandResponse { + constructor( + public readonly payload: boolean, + public readonly transactionId: string, + ) {} +} + +export class AddBeneficiaryCommand extends Command { + constructor( + public readonly securityId: string, + public readonly beneficiary: string, + public readonly data?: string, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.ts new file mode 100644 index 000000000..2ed426958 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.ts @@ -0,0 +1,246 @@ +/* + 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 { ICommandHandler } from '@core/command/CommandHandler'; +import { CommandHandler } from '@core/decorator/CommandHandlerDecorator'; +import AccountService from '@service/account/AccountService'; +import TransactionService from '@service/transaction/TransactionService'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import ValidationService from '@service/validation/ValidationService'; +import ContractService from '@service/contract/ContractService'; +import { + AddBeneficiaryCommand, + AddBeneficiaryCommandResponse, +} from './AddBeneficiaryCommand'; +import { AddBeneficiaryCommandError } from './error/AddBeneficiaryCommandError'; + +@CommandHandler(AddBeneficiaryCommand) +export class AddBeneficiaryCommandHandler + implements ICommandHandler +{ + constructor( + @lazyInject(AccountService) + private readonly accountService: AccountService, + @lazyInject(TransactionService) + private readonly transactionService: TransactionService, + @lazyInject(ValidationService) + private readonly validationService: ValidationService, + @lazyInject(ContractService) + private readonly contractService: ContractService, + ) {} + + async execute( + command: AddBeneficiaryCommand, + ): Promise { + try { + const { securityId, beneficiary, data } = command; + const handler = this.transactionService.getHandler(); + const account = this.accountService.getCurrentAccount(); + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + + const beneficiaryEvmAddress: EvmAddress = + await this.accountService.getAccountEvmAddress(beneficiary); + + await this.validationService.checkPause(securityId); + + await this.validationService.checkRole( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + securityId, + ); + + await this.validationService.checkIsNotBeneficiary( + securityId, + beneficiary, + ); + + const dataToValidate = !data || data === '' ? '0x' : data; + + const res = await handler.addBeneficiary( + securityEvmAddress, + beneficiaryEvmAddress, + dataToValidate, + securityId, + ); + + return Promise.resolve( + new AddBeneficiaryCommandResponse(res.error === undefined, res.id!), + ); + } catch (error) { + throw new AddBeneficiaryCommandError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.unit.test.ts new file mode 100644 index 000000000..fea5de008 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler.unit.test.ts @@ -0,0 +1,310 @@ +/* + 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 TransactionService from '@service/transaction/TransactionService'; +import { createMock } from '@golevelup/ts-jest'; +import AccountService from '@service/account/AccountService'; +import { + ErrorMsgFixture, + EvmAddressPropsFixture, + HederaIdPropsFixture, + TransactionIdFixture, +} from '@test/fixtures/shared/DataFixture'; +import ContractService from '@service/contract/ContractService'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ValidationService from '@service/validation/ValidationService'; +import Account from '@domain/context/account/Account'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import { ErrorCode } from '@core/error/BaseError'; +import { AddBeneficiaryCommandHandler } from './AddBeneficiaryCommandHandler'; +import { + AddBeneficiaryCommand, + AddBeneficiaryCommandResponse, +} from './AddBeneficiaryCommand'; + +import { AddBeneficiaryCommandError } from './error/AddBeneficiaryCommandError'; +import { AddBeneficiaryCommandFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('AddBeneficiaryCommandHandler', () => { + let handler: AddBeneficiaryCommandHandler; + let command: AddBeneficiaryCommand; + + const transactionServiceMock = createMock(); + const validationServiceMock = createMock(); + const accountServiceMock = createMock(); + const contractServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const beneficiaryEvmAddress = new EvmAddress( + EvmAddressPropsFixture.create().value, + ); + + const account = new Account({ + id: HederaIdPropsFixture.create().value, + evmAddress: EvmAddressPropsFixture.create().value, + }); + const transactionId = TransactionIdFixture.create().id; + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new AddBeneficiaryCommandHandler( + accountServiceMock, + transactionServiceMock, + validationServiceMock, + contractServiceMock, + ); + command = AddBeneficiaryCommandFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws AddBeneficiaryCommandError when command fails with uncaught error', async () => { + const fakeError = new Error(errorMsg); + + contractServiceMock.getContractEvmAddress.mockRejectedValue(fakeError); + + const resultPromise = handler.execute(command); + + await expect(resultPromise).rejects.toBeInstanceOf( + AddBeneficiaryCommandError, + ); + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while adding beneficiary: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtCommandError, + }); + }); + it('should successfully add beneficiary', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + + accountServiceMock.getCurrentAccount.mockReturnValue(account); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( + beneficiaryEvmAddress, + ); + validationServiceMock.checkPause.mockResolvedValue(undefined); + validationServiceMock.checkRole.mockResolvedValue(undefined); + validationServiceMock.checkIsNotBeneficiary.mockResolvedValue(true); + transactionServiceMock.getHandler().addBeneficiary.mockResolvedValue({ + id: transactionId, + }); + + const result = await handler.execute(command); + + expect(result).toBeInstanceOf(AddBeneficiaryCommandResponse); + expect(result.payload).toBe(true); + expect(result.transactionId).toBe(transactionId); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + expect(validationServiceMock.checkPause).toHaveBeenCalledTimes(1); + expect(validationServiceMock.checkRole).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getCurrentAccount).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); + expect( + transactionServiceMock.getHandler().addBeneficiary, + ).toHaveBeenCalledTimes(1); + + expect(validationServiceMock.checkPause).toHaveBeenCalledWith( + command.securityId, + ); + expect(validationServiceMock.checkRole).toHaveBeenCalledWith( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + command.securityId, + ); + expect(contractServiceMock.getContractEvmAddress).toHaveBeenNthCalledWith( + 1, + command.securityId, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenNthCalledWith( + 1, + command.beneficiary, + ); + + expect( + transactionServiceMock.getHandler().addBeneficiary, + ).toHaveBeenCalledWith( + evmAddress, + beneficiaryEvmAddress, + command.data, + command.securityId, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/error/AddBeneficiaryCommandError.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/error/AddBeneficiaryCommandError.ts new file mode 100644 index 000000000..efe88a2b9 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/addBeneficiary/error/AddBeneficiaryCommandError.ts @@ -0,0 +1,181 @@ +/* + 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 { CommandError } from '@command/error/CommandError'; +import BaseError from '@core/error/BaseError'; + +export class AddBeneficiaryCommandError extends CommandError { + constructor(error: Error) { + const msg = `An error occurred while adding beneficiary: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand.ts new file mode 100644 index 000000000..78a41dbd7 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand.ts @@ -0,0 +1,190 @@ +/* + 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 { Command } from '@core/command/Command'; +import { CommandResponse } from '@core/command/CommandResponse'; + +export class RemoveBeneficiaryCommandResponse implements CommandResponse { + constructor( + public readonly payload: boolean, + public readonly transactionId: string, + ) {} +} + +export class RemoveBeneficiaryCommand extends Command { + constructor( + public readonly securityId: string, + public readonly beneficiary: string, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.ts new file mode 100644 index 000000000..a39d4ac2a --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.ts @@ -0,0 +1,240 @@ +/* + 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 { ICommandHandler } from '@core/command/CommandHandler'; +import { CommandHandler } from '@core/decorator/CommandHandlerDecorator'; +import AccountService from '@service/account/AccountService'; +import TransactionService from '@service/transaction/TransactionService'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import ValidationService from '@service/validation/ValidationService'; +import ContractService from '@service/contract/ContractService'; +import { + RemoveBeneficiaryCommand, + RemoveBeneficiaryCommandResponse, +} from './RemoveBeneficiaryCommand'; +import { RemoveBeneficiaryCommandError } from './error/RemoveBeneficiaryCommandError'; + +@CommandHandler(RemoveBeneficiaryCommand) +export class RemoveBeneficiaryCommandHandler + implements ICommandHandler +{ + constructor( + @lazyInject(AccountService) + private readonly accountService: AccountService, + @lazyInject(TransactionService) + private readonly transactionService: TransactionService, + @lazyInject(ValidationService) + private readonly validationService: ValidationService, + @lazyInject(ContractService) + private readonly contractService: ContractService, + ) {} + + async execute( + command: RemoveBeneficiaryCommand, + ): Promise { + try { + const { securityId, beneficiary } = command; + const handler = this.transactionService.getHandler(); + const account = this.accountService.getCurrentAccount(); + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + + const beneficiaryEvmAddress: EvmAddress = + await this.accountService.getAccountEvmAddress(beneficiary); + + await this.validationService.checkPause(securityId); + + await this.validationService.checkRole( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + securityId, + ); + + await this.validationService.checkIsBeneficiary(securityId, beneficiary); + + const res = await handler.removeBeneficiary( + securityEvmAddress, + beneficiaryEvmAddress, + securityId, + ); + + return Promise.resolve( + new RemoveBeneficiaryCommandResponse(res.error === undefined, res.id!), + ); + } catch (error) { + throw new RemoveBeneficiaryCommandError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.unit.test.ts new file mode 100644 index 000000000..c252b9cc3 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler.unit.test.ts @@ -0,0 +1,308 @@ +/* + 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 TransactionService from '@service/transaction/TransactionService'; +import { createMock } from '@golevelup/ts-jest'; +import AccountService from '@service/account/AccountService'; +import { + ErrorMsgFixture, + EvmAddressPropsFixture, + HederaIdPropsFixture, + TransactionIdFixture, +} from '@test/fixtures/shared/DataFixture'; +import ContractService from '@service/contract/ContractService'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ValidationService from '@service/validation/ValidationService'; +import Account from '@domain/context/account/Account'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import { ErrorCode } from '@core/error/BaseError'; +import { RemoveBeneficiaryCommandHandler } from './RemoveBeneficiaryCommandHandler'; +import { + RemoveBeneficiaryCommand, + RemoveBeneficiaryCommandResponse, +} from './RemoveBeneficiaryCommand'; + +import { RemoveBeneficiaryCommandError } from './error/RemoveBeneficiaryCommandError'; +import { RemoveBeneficiaryCommandFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('RemoveBeneficiaryCommandHandler', () => { + let handler: RemoveBeneficiaryCommandHandler; + let command: RemoveBeneficiaryCommand; + + const transactionServiceMock = createMock(); + const validationServiceMock = createMock(); + const accountServiceMock = createMock(); + const contractServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const beneficiaryEvmAddress = new EvmAddress( + EvmAddressPropsFixture.create().value, + ); + + const account = new Account({ + id: HederaIdPropsFixture.create().value, + evmAddress: EvmAddressPropsFixture.create().value, + }); + const transactionId = TransactionIdFixture.create().id; + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new RemoveBeneficiaryCommandHandler( + accountServiceMock, + transactionServiceMock, + validationServiceMock, + contractServiceMock, + ); + command = RemoveBeneficiaryCommandFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws RemoveBeneficiaryCommandError when command fails with uncaught error', async () => { + const fakeError = new Error(errorMsg); + + contractServiceMock.getContractEvmAddress.mockRejectedValue(fakeError); + + const resultPromise = handler.execute(command); + + await expect(resultPromise).rejects.toBeInstanceOf( + RemoveBeneficiaryCommandError, + ); + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while removing beneficiary: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtCommandError, + }); + }); + it('should successfully add beneficiary', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + accountServiceMock.getCurrentAccount.mockReturnValue(account); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( + beneficiaryEvmAddress, + ); + validationServiceMock.checkPause.mockResolvedValue(undefined); + validationServiceMock.checkRole.mockResolvedValue(undefined); + validationServiceMock.checkIsBeneficiary.mockResolvedValue(true); + transactionServiceMock.getHandler().removeBeneficiary.mockResolvedValue({ + id: transactionId, + }); + + const result = await handler.execute(command); + + expect(result).toBeInstanceOf(RemoveBeneficiaryCommandResponse); + expect(result.payload).toBe(true); + expect(result.transactionId).toBe(transactionId); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + expect(validationServiceMock.checkPause).toHaveBeenCalledTimes(1); + expect(validationServiceMock.checkRole).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getCurrentAccount).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); + expect( + transactionServiceMock.getHandler().removeBeneficiary, + ).toHaveBeenCalledTimes(1); + + expect(validationServiceMock.checkPause).toHaveBeenCalledWith( + command.securityId, + ); + expect(validationServiceMock.checkRole).toHaveBeenCalledWith( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + command.securityId, + ); + expect(contractServiceMock.getContractEvmAddress).toHaveBeenNthCalledWith( + 1, + command.securityId, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenNthCalledWith( + 1, + command.beneficiary, + ); + + expect( + transactionServiceMock.getHandler().removeBeneficiary, + ).toHaveBeenCalledWith( + evmAddress, + beneficiaryEvmAddress, + command.securityId, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/error/RemoveBeneficiaryCommandError.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/error/RemoveBeneficiaryCommandError.ts new file mode 100644 index 000000000..b4c12daa9 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/removeBeneficiary/error/RemoveBeneficiaryCommandError.ts @@ -0,0 +1,181 @@ +/* + 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 { CommandError } from '@command/error/CommandError'; +import BaseError from '@core/error/BaseError'; + +export class RemoveBeneficiaryCommandError extends CommandError { + constructor(error: Error) { + const msg = `An error occurred while removing beneficiary: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand.ts new file mode 100644 index 000000000..cb95376c6 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand.ts @@ -0,0 +1,191 @@ +/* + 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 { Command } from '@core/command/Command'; +import { CommandResponse } from '@core/command/CommandResponse'; + +export class UpdateBeneficiaryDataCommandResponse implements CommandResponse { + constructor( + public readonly payload: boolean, + public readonly transactionId: string, + ) {} +} + +export class UpdateBeneficiaryDataCommand extends Command { + constructor( + public readonly securityId: string, + public readonly beneficiary: string, + public readonly data: string, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.ts new file mode 100644 index 000000000..3c0e02c93 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.ts @@ -0,0 +1,245 @@ +/* + 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 { ICommandHandler } from '@core/command/CommandHandler'; +import { CommandHandler } from '@core/decorator/CommandHandlerDecorator'; +import AccountService from '@service/account/AccountService'; +import TransactionService from '@service/transaction/TransactionService'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import ValidationService from '@service/validation/ValidationService'; +import ContractService from '@service/contract/ContractService'; +import { + UpdateBeneficiaryDataCommand, + UpdateBeneficiaryDataCommandResponse, +} from './UpdateBeneficiaryDataCommand'; +import { UpdateBeneficiaryDataCommandError } from './error/UpdateBeneficiaryDataCommandError'; + +@CommandHandler(UpdateBeneficiaryDataCommand) +export class UpdateBeneficiaryDataCommandHandler + implements ICommandHandler +{ + constructor( + @lazyInject(AccountService) + private readonly accountService: AccountService, + @lazyInject(TransactionService) + private readonly transactionService: TransactionService, + @lazyInject(ValidationService) + private readonly validationService: ValidationService, + @lazyInject(ContractService) + private readonly contractService: ContractService, + ) {} + + async execute( + command: UpdateBeneficiaryDataCommand, + ): Promise { + try { + const { securityId, beneficiary, data } = command; + const handler = this.transactionService.getHandler(); + const account = this.accountService.getCurrentAccount(); + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + + const beneficiaryEvmAddress: EvmAddress = + await this.accountService.getAccountEvmAddress(beneficiary); + + await this.validationService.checkPause(securityId); + + await this.validationService.checkRole( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + securityId, + ); + + await this.validationService.checkIsBeneficiary(securityId, beneficiary); + const finalData = data === '' ? '0x' : data; + + const res = await handler.updateBeneficiaryData( + securityEvmAddress, + beneficiaryEvmAddress, + finalData, + securityId, + ); + + return Promise.resolve( + new UpdateBeneficiaryDataCommandResponse( + res.error === undefined, + res.id!, + ), + ); + } catch (error) { + throw new UpdateBeneficiaryDataCommandError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.unit.test.ts new file mode 100644 index 000000000..b96c8fdd1 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler.unit.test.ts @@ -0,0 +1,311 @@ +/* + 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 TransactionService from '@service/transaction/TransactionService'; +import { createMock } from '@golevelup/ts-jest'; +import AccountService from '@service/account/AccountService'; +import { + ErrorMsgFixture, + EvmAddressPropsFixture, + HederaIdPropsFixture, + TransactionIdFixture, +} from '@test/fixtures/shared/DataFixture'; +import ContractService from '@service/contract/ContractService'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ValidationService from '@service/validation/ValidationService'; +import Account from '@domain/context/account/Account'; +import { SecurityRole } from '@domain/context/security/SecurityRole'; +import { ErrorCode } from '@core/error/BaseError'; +import { UpdateBeneficiaryDataCommandHandler } from './UpdateBeneficiaryDataCommandHandler'; +import { + UpdateBeneficiaryDataCommand, + UpdateBeneficiaryDataCommandResponse, +} from './UpdateBeneficiaryDataCommand'; + +import { UpdateBeneficiaryDataCommandError } from './error/UpdateBeneficiaryDataCommandError'; +import { UpdateBeneficiaryDataCommandFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('UpdateBeneficiaryDataCommandHandler', () => { + let handler: UpdateBeneficiaryDataCommandHandler; + let command: UpdateBeneficiaryDataCommand; + + const transactionServiceMock = createMock(); + const validationServiceMock = createMock(); + const accountServiceMock = createMock(); + const contractServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const beneficiaryEvmAddress = new EvmAddress( + EvmAddressPropsFixture.create().value, + ); + + const account = new Account({ + id: HederaIdPropsFixture.create().value, + evmAddress: EvmAddressPropsFixture.create().value, + }); + const transactionId = TransactionIdFixture.create().id; + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new UpdateBeneficiaryDataCommandHandler( + accountServiceMock, + transactionServiceMock, + validationServiceMock, + contractServiceMock, + ); + command = UpdateBeneficiaryDataCommandFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws UpdateBeneficiaryDataCommandError when command fails with uncaught error', async () => { + const fakeError = new Error(errorMsg); + + contractServiceMock.getContractEvmAddress.mockRejectedValue(fakeError); + + const resultPromise = handler.execute(command); + + await expect(resultPromise).rejects.toBeInstanceOf( + UpdateBeneficiaryDataCommandError, + ); + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while updating beneficiary data: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtCommandError, + }); + }); + it('should successfully update beneficiary', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + accountServiceMock.getCurrentAccount.mockReturnValue(account); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( + beneficiaryEvmAddress, + ); + validationServiceMock.checkPause.mockResolvedValue(undefined); + validationServiceMock.checkRole.mockResolvedValue(undefined); + validationServiceMock.checkIsBeneficiary.mockResolvedValue(true); + transactionServiceMock + .getHandler() + .updateBeneficiaryData.mockResolvedValue({ + id: transactionId, + }); + + const result = await handler.execute(command); + + expect(result).toBeInstanceOf(UpdateBeneficiaryDataCommandResponse); + expect(result.payload).toBe(true); + expect(result.transactionId).toBe(transactionId); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + expect(validationServiceMock.checkPause).toHaveBeenCalledTimes(1); + expect(validationServiceMock.checkRole).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getCurrentAccount).toHaveBeenCalledTimes(1); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); + expect( + transactionServiceMock.getHandler().updateBeneficiaryData, + ).toHaveBeenCalledTimes(1); + + expect(validationServiceMock.checkPause).toHaveBeenCalledWith( + command.securityId, + ); + expect(validationServiceMock.checkRole).toHaveBeenCalledWith( + SecurityRole._BENEFICIARY_MANAGER_ROLE, + account.id.toString(), + command.securityId, + ); + expect(contractServiceMock.getContractEvmAddress).toHaveBeenNthCalledWith( + 1, + command.securityId, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenNthCalledWith( + 1, + command.beneficiary, + ); + + expect( + transactionServiceMock.getHandler().updateBeneficiaryData, + ).toHaveBeenCalledWith( + evmAddress, + beneficiaryEvmAddress, + command.data, + command.securityId, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/error/UpdateBeneficiaryDataCommandError.ts b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/error/UpdateBeneficiaryDataCommandError.ts new file mode 100644 index 000000000..38f16f2b9 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/command/security/beneficiaries/updateBeneficiaryData/error/UpdateBeneficiaryDataCommandError.ts @@ -0,0 +1,181 @@ +/* + 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 { CommandError } from '@command/error/CommandError'; +import BaseError from '@core/error/BaseError'; + +export class UpdateBeneficiaryDataCommandError extends CommandError { + constructor(error: Error) { + const msg = `An error occurred while updating beneficiary data: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery.ts new file mode 100644 index 000000000..79b8a2285 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery.ts @@ -0,0 +1,221 @@ +/* + 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 { Query } from '@core/query/Query'; +import { QueryResponse } from '@core/query/QueryResponse'; + +export class GetBeneficiariesQueryResponse implements QueryResponse { + constructor(public readonly payload: string[]) {} +} + +export class GetBeneficiariesQuery extends Query { + constructor( + public readonly securityId: string, + public readonly pageIndex: number, + public readonly pageSize: number, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.ts new file mode 100644 index 000000000..6d60985d1 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.ts @@ -0,0 +1,258 @@ +/* + 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 { + GetBeneficiariesQuery, + GetBeneficiariesQueryResponse, +} from './GetBeneficiariesQuery'; +import { QueryHandler } from '@core/decorator/QueryHandlerDecorator'; +import { IQueryHandler } from '@core/query/QueryHandler'; +import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiariesQueryError } from './error/GetBeneficiariesQueryError'; +import AccountService from '@service/account/AccountService'; + +@QueryHandler(GetBeneficiariesQuery) +export class GetBeneficiariesQueryHandler + implements IQueryHandler +{ + constructor( + @lazyInject(ContractService) + private readonly contractService: ContractService, + @lazyInject(RPCQueryAdapter) + private readonly queryAdapter: RPCQueryAdapter, + @lazyInject(AccountService) + private readonly accountService: AccountService, + ) {} + + async execute( + query: GetBeneficiariesQuery, + ): Promise { + try { + const { pageIndex, pageSize, securityId } = query; + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + + const res = await this.queryAdapter.getBeneficiaries( + securityEvmAddress, + pageIndex, + pageSize, + ); + + const beneficiariesIds = await Promise.all( + res.map(async (b) => { + return (await this.accountService.getAccountInfo(b)).id.toString(); + }), + ); + + return new GetBeneficiariesQueryResponse(beneficiariesIds); + } catch (error) { + throw new GetBeneficiariesQueryError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.unit.test.ts new file mode 100644 index 000000000..094b936c8 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler.unit.test.ts @@ -0,0 +1,297 @@ +/* + 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 { + AccountPropsFixture, + ErrorMsgFixture, + EvmAddressPropsFixture, +} from '@test/fixtures/shared/DataFixture'; +import { ErrorCode } from '@core/error/BaseError'; +import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiariesQueryHandler } from './GetBeneficiariesQueryHandler'; +import { + GetBeneficiariesQuery, + GetBeneficiariesQueryResponse, +} from './GetBeneficiariesQuery'; +import { GetBeneficiariesQueryError } from './error/GetBeneficiariesQueryError'; +import { GetBeneficiariesQueryFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; +import AccountService from '@service/account/AccountService'; +import Account from '@domain/context/account/Account'; + +describe('GetBeneficiariesQueryHandler', () => { + let handler: GetBeneficiariesQueryHandler; + let query: GetBeneficiariesQuery; + + const queryAdapterServiceMock = createMock(); + const contractServiceMock = createMock(); + const accountServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const account = new Account(AccountPropsFixture.create()); + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new GetBeneficiariesQueryHandler( + contractServiceMock, + queryAdapterServiceMock, + accountServiceMock, + ); + query = GetBeneficiariesQueryFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws GetBeneficiariesQueryError 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( + GetBeneficiariesQueryError, + ); + + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while querying GetBeneficiaries: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtQueryError, + }); + }); + + it('should successfully get beneficiaries data', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + queryAdapterServiceMock.getBeneficiaries.mockResolvedValueOnce(['0x']); + + accountServiceMock.getAccountInfo.mockResolvedValueOnce(account); + + const result = await handler.execute(query); + + expect(result).toBeInstanceOf(GetBeneficiariesQueryResponse); + expect(result.payload).toStrictEqual([account.id.toString()]); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith( + query.securityId, + ); + + expect(queryAdapterServiceMock.getBeneficiaries).toHaveBeenCalledWith( + evmAddress, + query.pageIndex, + query.pageSize, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/error/GetBeneficiariesQueryError.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/error/GetBeneficiariesQueryError.ts new file mode 100644 index 000000000..d4ba03a0d --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaries/error/GetBeneficiariesQueryError.ts @@ -0,0 +1,214 @@ +/* + 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 { QueryError } from '@query/error/QueryError'; +import BaseError from '@core/error/BaseError'; + +export class GetBeneficiariesQueryError extends QueryError { + constructor(error: Error) { + const msg = `An error occurred while querying GetBeneficiaries: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery.ts new file mode 100644 index 000000000..091d3effb --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery.ts @@ -0,0 +1,217 @@ +/* + 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 { Query } from '@core/query/Query'; +import { QueryResponse } from '@core/query/QueryResponse'; + +export class GetBeneficiariesCountQueryResponse implements QueryResponse { + constructor(public readonly payload: number) {} +} + +export class GetBeneficiariesCountQuery extends Query { + constructor(public readonly securityId: string) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.ts new file mode 100644 index 000000000..8b71f688b --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.ts @@ -0,0 +1,246 @@ +/* + 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 { + GetBeneficiariesCountQuery, + GetBeneficiariesCountQueryResponse, +} from './GetBeneficiariesCountQuery'; +import { QueryHandler } from '@core/decorator/QueryHandlerDecorator'; +import { IQueryHandler } from '@core/query/QueryHandler'; +import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiariesCountQueryError } from './error/GetBeneficiariesCountQueryError'; + +@QueryHandler(GetBeneficiariesCountQuery) +export class GetBeneficiariesCountQueryHandler + implements IQueryHandler +{ + constructor( + @lazyInject(ContractService) + private readonly contractService: ContractService, + @lazyInject(RPCQueryAdapter) + private readonly queryAdapter: RPCQueryAdapter, + ) {} + + async execute( + query: GetBeneficiariesCountQuery, + ): Promise { + try { + const { securityId } = query; + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + + const res = + await this.queryAdapter.getBeneficiariesCount(securityEvmAddress); + + return new GetBeneficiariesCountQueryResponse(res); + } catch (error) { + throw new GetBeneficiariesCountQueryError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.unit.test.ts new file mode 100644 index 000000000..bb3303932 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler.unit.test.ts @@ -0,0 +1,292 @@ +/* + 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 EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiariesCountQueryHandler } from './GetBeneficiariesCountQueryHandler'; +import { + GetBeneficiariesCountQuery, + GetBeneficiariesCountQueryResponse, +} from './GetBeneficiariesCountQuery'; +import { GetBeneficiariesCountQueryError } from './error/GetBeneficiariesCountQueryError'; +import { GetBeneficiariesCountQueryFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('GetBeneficiariesCountQueryHandler', () => { + let handler: GetBeneficiariesCountQueryHandler; + let query: GetBeneficiariesCountQuery; + + const queryAdapterServiceMock = createMock(); + const contractServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new GetBeneficiariesCountQueryHandler( + contractServiceMock, + queryAdapterServiceMock, + ); + query = GetBeneficiariesCountQueryFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws GetBeneficiariesCountQueryError 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( + GetBeneficiariesCountQueryError, + ); + + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while querying GetBeneficiariesCount: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtQueryError, + }); + }); + + it('should successfully get beneficiaries count', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + + const responseAdapter = 45; + queryAdapterServiceMock.getBeneficiariesCount.mockResolvedValueOnce( + responseAdapter, + ); + + const result = await handler.execute(query); + + expect(result).toBeInstanceOf(GetBeneficiariesCountQueryResponse); + expect(result.payload).toStrictEqual(responseAdapter); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith( + query.securityId, + ); + + expect( + queryAdapterServiceMock.getBeneficiariesCount, + ).toHaveBeenCalledWith(evmAddress); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/error/GetBeneficiariesCountQueryError.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/error/GetBeneficiariesCountQueryError.ts new file mode 100644 index 000000000..71ef9c759 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiariesCount/error/GetBeneficiariesCountQueryError.ts @@ -0,0 +1,214 @@ +/* + 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 { QueryError } from '@query/error/QueryError'; +import BaseError from '@core/error/BaseError'; + +export class GetBeneficiariesCountQueryError extends QueryError { + constructor(error: Error) { + const msg = `An error occurred while querying GetBeneficiariesCount: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery.ts new file mode 100644 index 000000000..f22ef64df --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery.ts @@ -0,0 +1,220 @@ +/* + 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 { Query } from '@core/query/Query'; +import { QueryResponse } from '@core/query/QueryResponse'; + +export class GetBeneficiaryDataQueryResponse implements QueryResponse { + constructor(public readonly payload: string) {} +} + +export class GetBeneficiaryDataQuery extends Query { + constructor( + public readonly securityId: string, + public readonly targetId: string, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.ts new file mode 100644 index 000000000..6be064945 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.ts @@ -0,0 +1,253 @@ +/* + 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 { + GetBeneficiaryDataQuery, + GetBeneficiaryDataQueryResponse, +} from './GetBeneficiaryDataQuery'; +import { QueryHandler } from '@core/decorator/QueryHandlerDecorator'; +import { IQueryHandler } from '@core/query/QueryHandler'; +import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import AccountService from '@service/account/AccountService'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiaryDataQueryError } from './error/GetBeneficiaryDataQueryError'; + +@QueryHandler(GetBeneficiaryDataQuery) +export class GetBeneficiaryDataQueryHandler + implements IQueryHandler +{ + constructor( + @lazyInject(ContractService) + private readonly contractService: ContractService, + @lazyInject(RPCQueryAdapter) + private readonly queryAdapter: RPCQueryAdapter, + @lazyInject(AccountService) + private readonly accountService: AccountService, + ) {} + + async execute( + query: GetBeneficiaryDataQuery, + ): Promise { + try { + const { targetId, securityId } = query; + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + const targetEvmAddress: EvmAddress = + await this.accountService.getAccountEvmAddress(targetId); + + const res = await this.queryAdapter.getBeneficiaryData( + securityEvmAddress, + targetEvmAddress, + ); + + return new GetBeneficiaryDataQueryResponse(res); + } catch (error) { + throw new GetBeneficiaryDataQueryError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.unit.test.ts new file mode 100644 index 000000000..d08e86ed8 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler.unit.test.ts @@ -0,0 +1,302 @@ +/* + 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 EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { GetBeneficiaryDataQueryHandler } from './GetBeneficiaryDataQueryHandler'; +import { + GetBeneficiaryDataQuery, + GetBeneficiaryDataQueryResponse, +} from './GetBeneficiaryDataQuery'; +import AccountService from '@service/account/AccountService'; +import { GetBeneficiaryDataQueryError } from './error/GetBeneficiaryDataQueryError'; +import { GetBeneficiaryDataQueryFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('GetBeneficiaryDataQueryHandler', () => { + let handler: GetBeneficiaryDataQueryHandler; + let query: GetBeneficiaryDataQuery; + + const queryAdapterServiceMock = createMock(); + const contractServiceMock = createMock(); + const accountServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const targetEvmAddress = new EvmAddress( + EvmAddressPropsFixture.create().value, + ); + + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new GetBeneficiaryDataQueryHandler( + contractServiceMock, + queryAdapterServiceMock, + accountServiceMock, + ); + query = GetBeneficiaryDataQueryFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws GetBeneficiaryDataQueryError 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( + GetBeneficiaryDataQueryError, + ); + + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while querying GetBeneficiaryData: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtQueryError, + }); + }); + + it('should successfully get beneficiarydata', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( + targetEvmAddress, + ); + + queryAdapterServiceMock.getBeneficiaryData.mockResolvedValueOnce('0x123'); + + const result = await handler.execute(query); + + expect(result).toBeInstanceOf(GetBeneficiaryDataQueryResponse); + expect(result.payload).toStrictEqual('0x123'); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith( + query.securityId, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledWith( + query.targetId, + ); + expect(queryAdapterServiceMock.getBeneficiaryData).toHaveBeenCalledWith( + evmAddress, + targetEvmAddress, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/error/GetBeneficiaryDataQueryError.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/error/GetBeneficiaryDataQueryError.ts new file mode 100644 index 000000000..fa4dff56b --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/getBeneficiaryData/error/GetBeneficiaryDataQueryError.ts @@ -0,0 +1,214 @@ +/* + 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 { QueryError } from '@query/error/QueryError'; +import BaseError from '@core/error/BaseError'; + +export class GetBeneficiaryDataQueryError extends QueryError { + constructor(error: Error) { + const msg = `An error occurred while querying GetBeneficiaryData: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery.ts new file mode 100644 index 000000000..ed0cae933 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery.ts @@ -0,0 +1,220 @@ +/* + 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 { Query } from '@core/query/Query'; +import { QueryResponse } from '@core/query/QueryResponse'; + +export class IsBeneficiaryQueryResponse implements QueryResponse { + constructor(public readonly payload: boolean) {} +} + +export class IsBeneficiaryQuery extends Query { + constructor( + public readonly securityId: string, + public readonly targetId: string, + ) { + super(); + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.ts new file mode 100644 index 000000000..c5971bf36 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.ts @@ -0,0 +1,253 @@ +/* + 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 { + IsBeneficiaryQuery, + IsBeneficiaryQueryResponse, +} from './IsBeneficiaryQuery'; +import { QueryHandler } from '@core/decorator/QueryHandlerDecorator'; +import { IQueryHandler } from '@core/query/QueryHandler'; +import { RPCQueryAdapter } from '@port/out/rpc/RPCQueryAdapter'; +import { lazyInject } from '@core/decorator/LazyInjectDecorator'; +import AccountService from '@service/account/AccountService'; +import EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { IsBeneficiaryQueryError } from './error/IsBeneficiaryQueryError'; + +@QueryHandler(IsBeneficiaryQuery) +export class IsBeneficiaryQueryHandler + implements IQueryHandler +{ + constructor( + @lazyInject(ContractService) + private readonly contractService: ContractService, + @lazyInject(RPCQueryAdapter) + private readonly queryAdapter: RPCQueryAdapter, + @lazyInject(AccountService) + private readonly accountService: AccountService, + ) {} + + async execute( + query: IsBeneficiaryQuery, + ): Promise { + try { + const { targetId, securityId } = query; + + const securityEvmAddress: EvmAddress = + await this.contractService.getContractEvmAddress(securityId); + const targetEvmAddress: EvmAddress = + await this.accountService.getAccountEvmAddress(targetId); + + const res = await this.queryAdapter.isBeneficiary( + securityEvmAddress, + targetEvmAddress, + ); + + return new IsBeneficiaryQueryResponse(res); + } catch (error) { + throw new IsBeneficiaryQueryError(error as Error); + } + } +} diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.unit.test.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.unit.test.ts new file mode 100644 index 000000000..a477ffec2 --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler.unit.test.ts @@ -0,0 +1,301 @@ +/* + 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 EvmAddress from '@domain/context/contract/EvmAddress'; +import ContractService from '@service/contract/ContractService'; +import { IsBeneficiaryQueryHandler } from './IsBeneficiaryQueryHandler'; +import { + IsBeneficiaryQuery, + IsBeneficiaryQueryResponse, +} from './IsBeneficiaryQuery'; +import AccountService from '@service/account/AccountService'; +import { IsBeneficiaryQueryError } from './error/IsBeneficiaryQueryError'; +import { IsBeneficiaryQueryFixture } from '@test/fixtures/beneficiary/BeneficiaryFixture'; + +describe('IsBeneficiaryQueryHandler', () => { + let handler: IsBeneficiaryQueryHandler; + let query: IsBeneficiaryQuery; + + const queryAdapterServiceMock = createMock(); + const contractServiceMock = createMock(); + const accountServiceMock = createMock(); + + const evmAddress = new EvmAddress(EvmAddressPropsFixture.create().value); + const targetEvmAddress = new EvmAddress( + EvmAddressPropsFixture.create().value, + ); + + const errorMsg = ErrorMsgFixture.create().msg; + + beforeEach(() => { + handler = new IsBeneficiaryQueryHandler( + contractServiceMock, + queryAdapterServiceMock, + accountServiceMock, + ); + query = IsBeneficiaryQueryFixture.create(); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + describe('execute', () => { + it('throws IsBeneficiaryQueryError 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( + IsBeneficiaryQueryError, + ); + + await expect(resultPromise).rejects.toMatchObject({ + message: expect.stringContaining( + `An error occurred while querying isBeneficiary: ${errorMsg}`, + ), + errorCode: ErrorCode.UncaughtQueryError, + }); + }); + + it('should successfully get data', async () => { + contractServiceMock.getContractEvmAddress.mockResolvedValueOnce( + evmAddress, + ); + accountServiceMock.getAccountEvmAddress.mockResolvedValueOnce( + targetEvmAddress, + ); + queryAdapterServiceMock.isBeneficiary.mockResolvedValueOnce(true); + + const result = await handler.execute(query); + + expect(result).toBeInstanceOf(IsBeneficiaryQueryResponse); + expect(result.payload).toStrictEqual(true); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes( + 1, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1); + + expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledWith( + query.securityId, + ); + expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledWith( + query.targetId, + ); + expect(queryAdapterServiceMock.isBeneficiary).toHaveBeenCalledWith( + evmAddress, + targetEvmAddress, + ); + }); + }); +}); diff --git a/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/error/IsBeneficiaryQueryError.ts b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/error/IsBeneficiaryQueryError.ts new file mode 100644 index 000000000..de777be3b --- /dev/null +++ b/packages/ats/sdk/src/app/usecase/query/security/beneficiary/isBeneficiary/error/IsBeneficiaryQueryError.ts @@ -0,0 +1,214 @@ +/* + 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 { QueryError } from '@query/error/QueryError'; +import BaseError from '@core/error/BaseError'; + +export class IsBeneficiaryQueryError extends QueryError { + constructor(error: Error) { + const msg = `An error occurred while querying isBeneficiary: ${error.message}`; + super(msg, error instanceof BaseError ? error.errorCode : undefined); + } +} diff --git a/packages/ats/sdk/src/core/Constants.ts b/packages/ats/sdk/src/core/Constants.ts index a9137a099..d97d7aec8 100644 --- a/packages/ats/sdk/src/core/Constants.ts +++ b/packages/ats/sdk/src/core/Constants.ts @@ -348,6 +348,9 @@ export const GAS = { REMOVE_AGENT: 7000000, REDEEM_AT_MATURITY_BY_PARTITION_GAS: 700000, TREX_CREATE_SUITE: 20000000, + ADD_BENEFICIARY: 7000000, + REMOVE_BENEFICIARY: 7000000, + UPDATE_BENEFICIARY: 7000000, } as const; export const _PARTITION_ID_1 = diff --git a/packages/ats/sdk/src/core/error/BaseError.ts b/packages/ats/sdk/src/core/error/BaseError.ts index 1559e847e..80eb50452 100644 --- a/packages/ats/sdk/src/core/error/BaseError.ts +++ b/packages/ats/sdk/src/core/error/BaseError.ts @@ -279,6 +279,8 @@ export enum ErrorCode { InvalidKycStatus = '20041', WalletRecovered = '20042', AddressNotVerified = '20043', + AccountIsBeneficiary = '20044', + AccountIsNotBeneficiary = '20045', // Error codes for System Errors (Prefix: 3XXXX) ContractNotFound = '30002', diff --git a/packages/ats/sdk/src/core/injectable/Handlers.ts b/packages/ats/sdk/src/core/injectable/Handlers.ts index d49137738..cd5e7bf9a 100644 --- a/packages/ats/sdk/src/core/injectable/Handlers.ts +++ b/packages/ats/sdk/src/core/injectable/Handlers.ts @@ -301,6 +301,10 @@ import { COMMAND_HANDLERS_TREX_FACTORY, QUERY_HANDLERS_TREX_FACTORY, } from './trexFactory/InjectableTrexFactory'; +import { + QUERY_HANDLERS_BENEFICIARY, + COMMAND_HANDLERS_BENEFICIARY, +} from './beneficiary/BeneficiaryInjectable'; export const COMMAND_HANDLERS = [ ...COMMAND_HANDLERS_AGENT, @@ -329,6 +333,7 @@ export const COMMAND_HANDLERS = [ ...COMMAND_HANDLERS_TRANSFER, ...COMMAND_HANDLERS_BALANCE, ...COMMAND_HANDLERS_TREX_FACTORY, + ...COMMAND_HANDLERS_BENEFICIARY, ]; export const QUERY_HANDLERS = [ @@ -357,6 +362,7 @@ export const QUERY_HANDLERS = [ ...QUERY_HANDLERS_OPERATOR, ...QUERY_HANDLERS_SNAPSHOT, ...QUERY_HANDLERS_TREX_FACTORY, + ...QUERY_HANDLERS_BENEFICIARY, ]; export const TRANSACTION_HANDLER = [ diff --git a/packages/ats/sdk/src/core/injectable/beneficiary/BeneficiaryInjectable.ts b/packages/ats/sdk/src/core/injectable/beneficiary/BeneficiaryInjectable.ts new file mode 100644 index 000000000..a7e225eeb --- /dev/null +++ b/packages/ats/sdk/src/core/injectable/beneficiary/BeneficiaryInjectable.ts @@ -0,0 +1,238 @@ +/* + 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 { AddBeneficiaryCommandHandler } from '@command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommandHandler'; +import { RemoveBeneficiaryCommandHandler } from '@command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommandHandler'; +import { UpdateBeneficiaryDataCommandHandler } from '@command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommandHandler'; +import { GetBeneficiariesQueryHandler } from '@query/security/beneficiary/getBeneficiaries/GetBeneficiariesQueryHandler'; +import { GetBeneficiariesCountQueryHandler } from '@query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQueryHandler'; +import { GetBeneficiaryDataQueryHandler } from '@query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQueryHandler'; +import { IsBeneficiaryQueryHandler } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQueryHandler'; + +export const COMMAND_HANDLERS_BENEFICIARY = [ + { + token: TOKENS.COMMAND_HANDLER, + useClass: AddBeneficiaryCommandHandler, + }, + { + token: TOKENS.COMMAND_HANDLER, + useClass: RemoveBeneficiaryCommandHandler, + }, + { + token: TOKENS.COMMAND_HANDLER, + useClass: UpdateBeneficiaryDataCommandHandler, + }, +]; + +export const QUERY_HANDLERS_BENEFICIARY = [ + { + token: TOKENS.QUERY_HANDLER, + useClass: IsBeneficiaryQueryHandler, + }, + { token: TOKENS.QUERY_HANDLER, useClass: GetBeneficiaryDataQueryHandler }, + { token: TOKENS.QUERY_HANDLER, useClass: GetBeneficiariesCountQueryHandler }, + { token: TOKENS.QUERY_HANDLER, useClass: GetBeneficiariesQueryHandler }, +]; diff --git a/packages/ats/sdk/src/domain/context/factory/FactorySecurityToken.ts b/packages/ats/sdk/src/domain/context/factory/FactorySecurityToken.ts index 776bc3d3d..c8860b7de 100644 --- a/packages/ats/sdk/src/domain/context/factory/FactorySecurityToken.ts +++ b/packages/ats/sdk/src/domain/context/factory/FactorySecurityToken.ts @@ -222,9 +222,19 @@ export class FactoryBondToken { public security: SecurityData; public bondDetails: BondDetailsData; - constructor(security: SecurityData, bondDetails: BondDetailsData) { + public beneficiaries: string[]; + public beneficiariesData: string[]; + + constructor( + security: SecurityData, + bondDetails: BondDetailsData, + beneficiaries: string[], + beneficiariesData: string[], + ) { this.security = security; this.bondDetails = bondDetails; + this.beneficiaries = beneficiaries; + this.beneficiariesData = beneficiariesData; } } diff --git a/packages/ats/sdk/src/domain/context/security/SecurityRole.ts b/packages/ats/sdk/src/domain/context/security/SecurityRole.ts index c501884d4..b9546310f 100644 --- a/packages/ats/sdk/src/domain/context/security/SecurityRole.ts +++ b/packages/ats/sdk/src/domain/context/security/SecurityRole.ts @@ -234,6 +234,7 @@ export enum SecurityRole { _AGENT_ROLE = '0xc4aed0454da9bde6defa5baf93bb49d4690626fc243d138104e12d1def783ea6', _TREX_OWNER_ROLE = '0x03ce2fdc316501dd97f5219e6ad908a3238f1e90f910aa17b627f801a6aafab7', _MATURITY_REDEEMER_ROLE = '0xa0d696902e9ed231892dc96649f0c62b808a1cb9dd1269e78e0adc1cc4b8358c', + _BENEFICIARY_MANAGER_ROLE = '0xebc53fe99fea28c7aa9476a714959af5b931f34a8a8734365ec63113198d512f', } export function getProtectedPartitionRole(partitionId: string): string { diff --git a/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsBeneficiary.ts b/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsBeneficiary.ts new file mode 100644 index 000000000..ec6b47265 --- /dev/null +++ b/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsBeneficiary.ts @@ -0,0 +1,215 @@ +/* + 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 BaseError, { ErrorCode } from '@core/error/BaseError'; + +export class AccountIsBeneficiary extends BaseError { + constructor(securityId: string, targetId: string) { + super( + ErrorCode.AccountIsBeneficiary, + `The account ${targetId} is beneficiary of security ${securityId}`, + ); + } +} diff --git a/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsNotBeneficiary.ts b/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsNotBeneficiary.ts new file mode 100644 index 000000000..3328dc31f --- /dev/null +++ b/packages/ats/sdk/src/domain/context/security/error/operations/AccountIsNotBeneficiary.ts @@ -0,0 +1,215 @@ +/* + 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 BaseError, { ErrorCode } from '@core/error/BaseError'; + +export class AccountIsNotBeneficiary extends BaseError { + constructor(securityId: string, targetId: string) { + super( + ErrorCode.AccountIsNotBeneficiary, + `The account ${targetId} is not a beneficiary of security ${securityId}`, + ); + } +} diff --git a/packages/ats/sdk/src/port/in/bond/Bond.ts b/packages/ats/sdk/src/port/in/bond/Bond.ts index b51527fd6..d2b1469b0 100644 --- a/packages/ats/sdk/src/port/in/bond/Bond.ts +++ b/packages/ats/sdk/src/port/in/bond/Bond.ts @@ -239,14 +239,29 @@ import UpdateMaturityDateRequest from '../request/bond/UpdateMaturityDateRequest import { UpdateMaturityDateCommand } from '@command/bond/updateMaturityDate/UpdateMaturityDateCommand'; import { RedeemAtMaturityByPartitionCommand } from '@command/bond/redeemAtMaturityByPartition/RedeemAtMaturityByPartitionCommand'; import RedeemAtMaturityByPartitionRequest from '../request/bond/RedeemAtMaturityByPartitionRequest'; -import { - GetCouponHoldersRequest, - GetTotalCouponHoldersRequest, -} from '../request'; + 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 AddBeneficiaryRequest from '../request/bond/AddBeneficiaryRequest'; +import RemoveBeneficiaryRequest from '../request/bond/RemoveBeneficiaryRequest'; +import UpdateBeneficiaryDataRequest from '../request/bond/UpdateBeneficiaryDataRequest'; +import { UpdateBeneficiaryDataCommand } from '@command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand'; +import { RemoveBeneficiaryCommand } from '@command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand'; +import { AddBeneficiaryCommand } from '@command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand'; +import IsBeneficiaryRequest from '../request/bond/IsBeneficiaryRequest'; +import { GetBeneficiariesQuery } from '@query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery'; +import { GetBeneficiariesCountQuery } from '@query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery'; +import { GetBeneficiaryDataQuery } from '@query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery'; +import { IsBeneficiaryQuery } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery'; +import { + GetCouponHoldersRequest, + GetTotalCouponHoldersRequest, + GetBeneficiaryDataRequest, + GetBeneficiariesCountRequest, + GetBeneficiariesRequest, +} from '../request'; interface IBondInPort { create( @@ -270,6 +285,26 @@ interface IBondInPort { createTrexSuite( request: CreateTrexSuiteBondRequest, ): Promise<{ security: SecurityViewModel; transactionId: string }>; + + addBeneficiary( + request: AddBeneficiaryRequest, + ): Promise<{ payload: boolean; transactionId: string }>; + removeBeneficiary( + request: RemoveBeneficiaryRequest, + ): Promise<{ payload: boolean; transactionId: string }>; + updateBeneficiaryData( + request: UpdateBeneficiaryDataRequest, + ): Promise<{ payload: boolean; transactionId: string }>; + isBeneficiary(request: IsBeneficiaryRequest): Promise<{ payload: boolean }>; + getBeneficiaryData( + request: GetBeneficiaryDataRequest, + ): Promise<{ payload: string }>; + getBeneficiariesCount( + request: GetBeneficiariesCountRequest, + ): Promise<{ payload: number }>; + getBeneficiaries( + request: GetBeneficiariesRequest, + ): Promise<{ payload: string[] }>; } class BondInPort implements IBondInPort { @@ -335,6 +370,8 @@ class BondInPort implements IBondInPort { externalKycListsIds, req.complianceId, req.identityRegistryId, + req.beneficiariesIds, + req.beneficiariesData, ), ); @@ -589,6 +626,8 @@ class BondInPort implements IBondInPort { req.configId, req.configVersion, diamondOwnerAccount, + req.beneficiariesIds, + req.beneficiariesData, externalPauses, externalControlLists, externalKycLists, @@ -616,6 +655,91 @@ class BondInPort implements IBondInPort { transactionId: createResponse.transactionId, }; } + + @LogError + async updateBeneficiaryData( + request: UpdateBeneficiaryDataRequest, + ): Promise<{ payload: boolean; transactionId: string }> { + ValidatedRequest.handleValidation( + UpdateBeneficiaryDataRequest.name, + request, + ); + return await this.commandBus.execute( + new UpdateBeneficiaryDataCommand( + request.securityId, + request.beneficiaryId, + request.data, + ), + ); + } + + @LogError + async removeBeneficiary( + request: RemoveBeneficiaryRequest, + ): Promise<{ payload: boolean; transactionId: string }> { + ValidatedRequest.handleValidation(RemoveBeneficiaryRequest.name, request); + return await this.commandBus.execute( + new RemoveBeneficiaryCommand(request.securityId, request.beneficiaryId), + ); + } + + @LogError + async addBeneficiary( + request: AddBeneficiaryRequest, + ): Promise<{ payload: boolean; transactionId: string }> { + ValidatedRequest.handleValidation(AddBeneficiaryRequest.name, request); + return await this.commandBus.execute( + new AddBeneficiaryCommand( + request.securityId, + request.beneficiaryId, + request.data, + ), + ); + } + + @LogError + async getBeneficiaries( + request: GetBeneficiariesRequest, + ): Promise<{ payload: string[] }> { + ValidatedRequest.handleValidation(GetBeneficiariesRequest.name, request); + return await this.queryBus.execute( + new GetBeneficiariesQuery( + request.securityId, + request.pageIndex, + request.pageSize, + ), + ); + } + @LogError + async getBeneficiariesCount( + request: GetBeneficiariesCountRequest, + ): Promise<{ payload: number }> { + ValidatedRequest.handleValidation( + GetBeneficiariesCountRequest.name, + request, + ); + return await this.queryBus.execute( + new GetBeneficiariesCountQuery(request.securityId), + ); + } + @LogError + async getBeneficiaryData( + request: GetBeneficiaryDataRequest, + ): Promise<{ payload: string }> { + ValidatedRequest.handleValidation(GetBeneficiaryDataRequest.name, request); + return await this.queryBus.execute( + new GetBeneficiaryDataQuery(request.securityId, request.beneficiaryId), + ); + } + @LogError + async isBeneficiary( + request: IsBeneficiaryRequest, + ): Promise<{ payload: boolean }> { + ValidatedRequest.handleValidation(IsBeneficiaryRequest.name, request); + return await this.queryBus.execute( + new IsBeneficiaryQuery(request.securityId, request.beneficiaryId), + ); + } } const BondToken = new BondInPort(); 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 af9b22bf1..563602182 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 @@ -217,6 +217,12 @@ import { GetCouponHoldersRequest, GetTotalCouponHoldersRequest, CreateTrexSuiteBondRequest, + RemoveBeneficiaryRequest, + UpdateBeneficiaryDataRequest, + IsBeneficiaryRequest, + GetBeneficiariesCountRequest, + GetBeneficiaryDataRequest, + GetBeneficiariesRequest, } from '../request'; import { HederaIdPropsFixture, @@ -242,6 +248,13 @@ import { SetCouponRequestFixture, UpdateMaturityDateRequestFixture, CreateTrexSuiteBondRequestFixture, + AddBeneficiaryRequestFixture, + RemoveBeneficiaryRequestFixture, + UpdateBeneficiaryDataRequestFixture, + IsBeneficiaryRequestFixture, + GetBeneficiariesCountRequestFixture, + GetBeneficiaryDataRequestFixture, + GetBeneficiariesRequestFixture, } from '@test/fixtures/bond/BondFixture'; import { SecurityPropsFixture } from '@test/fixtures/shared/SecurityFixture'; import { Security } from '@domain/context/security/Security'; @@ -265,6 +278,14 @@ import { RedeemAtMaturityByPartitionCommand } from '@command/bond/redeemAtMaturi import { GetCouponHoldersQuery } from '@query/bond/coupons/getCouponHolders/GetCouponHoldersQuery'; import { GetTotalCouponHoldersQuery } from '@query/bond/coupons/getTotalCouponHolders/GetTotalCouponHoldersQuery'; import { CreateTrexSuiteBondCommand } from '@command/bond/createTrexSuite/CreateTrexSuiteBondCommand'; +import AddBeneficiaryRequest from '../request/bond/AddBeneficiaryRequest'; +import { AddBeneficiaryCommand } from '@command/security/beneficiaries/addBeneficiary/AddBeneficiaryCommand'; +import { RemoveBeneficiaryCommand } from '@command/security/beneficiaries/removeBeneficiary/RemoveBeneficiaryCommand'; +import { UpdateBeneficiaryDataCommand } from '@command/security/beneficiaries/updateBeneficiaryData/UpdateBeneficiaryDataCommand'; +import { IsBeneficiaryQuery } from '@query/security/beneficiary/isBeneficiary/IsBeneficiaryQuery'; +import { GetBeneficiariesCountQuery } from '@query/security/beneficiary/getBeneficiariesCount/GetBeneficiariesCountQuery'; +import { GetBeneficiaryDataQuery } from '@query/security/beneficiary/getBeneficiaryData/GetBeneficiaryDataQuery'; +import { GetBeneficiariesQuery } from '@query/security/beneficiary/getBeneficiaries/GetBeneficiariesQuery'; describe('Bond', () => { let commandBusMock: jest.Mocked; @@ -375,6 +396,8 @@ describe('Bond', () => { createBondRequest.externalKycListsIds, createBondRequest.complianceId, createBondRequest.identityRegistryId, + createBondRequest.beneficiariesIds, + createBondRequest.beneficiariesData, ), ); @@ -438,10 +461,23 @@ describe('Bond', () => { createBondRequest.externalKycListsIds, createBondRequest.complianceId, createBondRequest.identityRegistryId, + createBondRequest.beneficiariesIds, + createBondRequest.beneficiariesData, ), ); }); + it('should not throw error if beneficiaryData not has bytes', async () => { + createBondRequest = new CreateBondRequest( + CreateBondRequestFixture.create({ + beneficiariesData: ['', '0x1234'], + beneficiariesIds: ['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: '' }), @@ -1510,6 +1546,8 @@ describe('Bond', () => { createTrexSuiteBondRequest.configId, createTrexSuiteBondRequest.configVersion, createTrexSuiteBondRequest.diamondOwnerAccount, + createTrexSuiteBondRequest.beneficiariesIds, + createTrexSuiteBondRequest.beneficiariesData, createTrexSuiteBondRequest.externalPauses, createTrexSuiteBondRequest.externalControlLists, createTrexSuiteBondRequest.externalKycLists, @@ -1588,6 +1626,8 @@ describe('Bond', () => { createTrexSuiteBondRequest.configId, createTrexSuiteBondRequest.configVersion, createTrexSuiteBondRequest.diamondOwnerAccount, + createTrexSuiteBondRequest.beneficiariesIds, + createTrexSuiteBondRequest.beneficiariesData, createTrexSuiteBondRequest.externalPauses, createTrexSuiteBondRequest.externalControlLists, createTrexSuiteBondRequest.externalKycLists, @@ -1779,4 +1819,548 @@ describe('Bond', () => { ).rejects.toThrow(ValidationError); }); }); + + describe('AddBeneficiaryRequest', () => { + const addBeneficiaryRequest = new AddBeneficiaryRequest( + AddBeneficiaryRequestFixture.create(), + ); + it('should add beneficiary successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + commandBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.addBeneficiary(addBeneficiaryRequest); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'AddBeneficiaryRequest', + addBeneficiaryRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledTimes(1); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new AddBeneficiaryCommand( + addBeneficiaryRequest.securityId, + addBeneficiaryRequest.beneficiaryId, + addBeneficiaryRequest.data, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if command execution fails', async () => { + const error = new Error('Command execution failed'); + commandBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.addBeneficiary(addBeneficiaryRequest), + ).rejects.toThrow('Command execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'AddBeneficiaryRequest', + addBeneficiaryRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new AddBeneficiaryCommand( + addBeneficiaryRequest.securityId, + addBeneficiaryRequest.beneficiaryId, + addBeneficiaryRequest.data, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let addBeneficiaryRequest = new AddBeneficiaryRequest({ + ...AddBeneficiaryRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.addBeneficiary(addBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if data is invalid', async () => { + let addBeneficiaryRequest = new AddBeneficiaryRequest({ + ...AddBeneficiaryRequestFixture.create(), + data: 'invalid', + }); + + await expect( + BondToken.addBeneficiary(addBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if beneficiaryId is invalid', async () => { + let addBeneficiaryRequest = new AddBeneficiaryRequest({ + ...AddBeneficiaryRequestFixture.create(), + beneficiaryId: 'invalid', + }); + + await expect( + BondToken.addBeneficiary(addBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('RemoveBeneficiaryRequest', () => { + const removeBeneficiaryRequest = new RemoveBeneficiaryRequest( + RemoveBeneficiaryRequestFixture.create(), + ); + it('should remove beneficiary successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + commandBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.removeBeneficiary( + removeBeneficiaryRequest, + ); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'RemoveBeneficiaryRequest', + removeBeneficiaryRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledTimes(1); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new RemoveBeneficiaryCommand( + removeBeneficiaryRequest.securityId, + removeBeneficiaryRequest.beneficiaryId, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if command execution fails', async () => { + const error = new Error('Command execution failed'); + commandBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.removeBeneficiary(removeBeneficiaryRequest), + ).rejects.toThrow('Command execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'RemoveBeneficiaryRequest', + removeBeneficiaryRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new RemoveBeneficiaryCommand( + removeBeneficiaryRequest.securityId, + removeBeneficiaryRequest.beneficiaryId, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let removeBeneficiaryRequest = new RemoveBeneficiaryRequest({ + ...RemoveBeneficiaryRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.removeBeneficiary(removeBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if beneficiaryId is invalid', async () => { + let removeBeneficiaryRequest = new RemoveBeneficiaryRequest({ + ...RemoveBeneficiaryRequestFixture.create(), + beneficiaryId: 'invalid', + }); + + await expect( + BondToken.removeBeneficiary(removeBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('UpdateBeneficiaryDataRequest', () => { + const updateBeneficiaryDataRequest = new UpdateBeneficiaryDataRequest( + UpdateBeneficiaryDataRequestFixture.create(), + ); + it('should update beneficiary data successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + commandBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.updateBeneficiaryData( + updateBeneficiaryDataRequest, + ); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'UpdateBeneficiaryDataRequest', + updateBeneficiaryDataRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledTimes(1); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new UpdateBeneficiaryDataCommand( + updateBeneficiaryDataRequest.securityId, + updateBeneficiaryDataRequest.beneficiaryId, + updateBeneficiaryDataRequest.data, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if command execution fails', async () => { + const error = new Error('Command execution failed'); + commandBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.updateBeneficiaryData(updateBeneficiaryDataRequest), + ).rejects.toThrow('Command execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'UpdateBeneficiaryDataRequest', + updateBeneficiaryDataRequest, + ); + + expect(commandBusMock.execute).toHaveBeenCalledWith( + new UpdateBeneficiaryDataCommand( + updateBeneficiaryDataRequest.securityId, + updateBeneficiaryDataRequest.beneficiaryId, + updateBeneficiaryDataRequest.data, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let updateBeneficiaryDataRequest = new UpdateBeneficiaryDataRequest({ + ...UpdateBeneficiaryDataRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.updateBeneficiaryData(updateBeneficiaryDataRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if data is invalid', async () => { + let updateBeneficiaryDataRequest = new UpdateBeneficiaryDataRequest({ + ...UpdateBeneficiaryDataRequestFixture.create(), + data: 'invalid', + }); + + await expect( + BondToken.updateBeneficiaryData(updateBeneficiaryDataRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if beneficiaryId is invalid', async () => { + let updateBeneficiaryDataRequest = new UpdateBeneficiaryDataRequest({ + ...UpdateBeneficiaryDataRequestFixture.create(), + beneficiaryId: 'invalid', + }); + + await expect( + BondToken.updateBeneficiaryData(updateBeneficiaryDataRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('IsBeneficiaryRequest', () => { + const isBeneficiaryRequest = new IsBeneficiaryRequest( + IsBeneficiaryRequestFixture.create(), + ); + it('should get isBeneficiary successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + queryBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.isBeneficiary(isBeneficiaryRequest); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'IsBeneficiaryRequest', + isBeneficiaryRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledTimes(1); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new IsBeneficiaryQuery( + isBeneficiaryRequest.securityId, + isBeneficiaryRequest.beneficiaryId, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if query execution fails', async () => { + const error = new Error('Query execution failed'); + queryBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.isBeneficiary(isBeneficiaryRequest), + ).rejects.toThrow('Query execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'IsBeneficiaryRequest', + isBeneficiaryRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new IsBeneficiaryQuery( + isBeneficiaryRequest.securityId, + isBeneficiaryRequest.beneficiaryId, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let isBeneficiaryRequest = new IsBeneficiaryRequest({ + ...AddBeneficiaryRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.isBeneficiary(isBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if beneficiaryId is invalid', async () => { + let isBeneficiaryRequest = new IsBeneficiaryRequest({ + ...AddBeneficiaryRequestFixture.create(), + beneficiaryId: 'invalid', + }); + + await expect( + BondToken.isBeneficiary(isBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('GetBeneficiariesCountRequest', () => { + const getBeneficiariesCountRequest = new GetBeneficiariesCountRequest( + GetBeneficiariesCountRequestFixture.create(), + ); + it('should get beneficiaries count successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + queryBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.getBeneficiariesCount( + getBeneficiariesCountRequest, + ); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiariesCountRequest', + getBeneficiariesCountRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledTimes(1); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiariesCountQuery(getBeneficiariesCountRequest.securityId), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if query execution fails', async () => { + const error = new Error('Query execution failed'); + queryBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.getBeneficiariesCount(getBeneficiariesCountRequest), + ).rejects.toThrow('Query execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiariesCountRequest', + getBeneficiariesCountRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiariesCountQuery(getBeneficiariesCountRequest.securityId), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let getBeneficiariesCountRequest = new GetBeneficiariesCountRequest({ + ...AddBeneficiaryRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.getBeneficiariesCount(getBeneficiariesCountRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('GetBeneficiaryDataRequest', () => { + const getBeneficiaryDataRequest = new GetBeneficiaryDataRequest( + GetBeneficiaryDataRequestFixture.create(), + ); + it('should get beneficiary data successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + queryBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.getBeneficiaryData( + getBeneficiaryDataRequest, + ); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiaryDataRequest', + getBeneficiaryDataRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledTimes(1); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiaryDataQuery( + getBeneficiaryDataRequest.securityId, + getBeneficiaryDataRequest.beneficiaryId, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if query execution fails', async () => { + const error = new Error('Query execution failed'); + queryBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.getBeneficiaryData(getBeneficiaryDataRequest), + ).rejects.toThrow('Query execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiaryDataRequest', + getBeneficiaryDataRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiaryDataQuery( + getBeneficiaryDataRequest.securityId, + getBeneficiaryDataRequest.beneficiaryId, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let isBeneficiaryRequest = new GetBeneficiaryDataRequest({ + ...AddBeneficiaryRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.isBeneficiary(isBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if beneficiaryId is invalid', async () => { + let isBeneficiaryRequest = new GetBeneficiaryDataRequest({ + ...AddBeneficiaryRequestFixture.create(), + beneficiaryId: 'invalid', + }); + + await expect( + BondToken.isBeneficiary(isBeneficiaryRequest), + ).rejects.toThrow(ValidationError); + }); + }); + + describe('GetBeneficiariesRequest', () => { + const getBeneficiariesRequest = new GetBeneficiariesRequest( + GetBeneficiariesRequestFixture.create(), + ); + it('should get beneficiaries successfully', async () => { + const expectedResponse = { + payload: true, + transactionId: transactionId, + }; + + queryBusMock.execute.mockResolvedValue(expectedResponse); + + const result = await BondToken.getBeneficiaries(getBeneficiariesRequest); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiariesRequest', + getBeneficiariesRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledTimes(1); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiariesQuery( + getBeneficiariesRequest.securityId, + getBeneficiariesRequest.pageIndex, + getBeneficiariesRequest.pageSize, + ), + ); + + expect(result).toEqual(expectedResponse); + }); + + it('should throw an error if query execution fails', async () => { + const error = new Error('Query execution failed'); + queryBusMock.execute.mockRejectedValue(error); + + await expect( + BondToken.getBeneficiaries(getBeneficiariesRequest), + ).rejects.toThrow('Query execution failed'); + + expect(handleValidationSpy).toHaveBeenCalledWith( + 'GetBeneficiariesRequest', + getBeneficiariesRequest, + ); + + expect(queryBusMock.execute).toHaveBeenCalledWith( + new GetBeneficiariesQuery( + getBeneficiariesRequest.securityId, + getBeneficiariesRequest.pageIndex, + getBeneficiariesRequest.pageSize, + ), + ); + }); + + it('should throw error if securityId is invalid', async () => { + let getBeneficiariesRequest = new GetBeneficiariesRequest({ + ...GetBeneficiariesRequestFixture.create(), + securityId: 'invalid', + }); + + await expect( + BondToken.getBeneficiaries(getBeneficiariesRequest), + ).rejects.toThrow(ValidationError); + }); + + it('should throw error if page size is invalid', async () => { + let getBeneficiariesRequest = new GetBeneficiariesRequest({ + ...GetBeneficiariesRequestFixture.create(), + pageSize: -1, + }); + + await expect( + BondToken.getBeneficiaries(getBeneficiariesRequest), + ).rejects.toThrow(ValidationError); + }); + }); }); diff --git a/packages/ats/sdk/src/port/in/request/bond/AddBeneficiaryRequest.ts b/packages/ats/sdk/src/port/in/request/bond/AddBeneficiaryRequest.ts new file mode 100644 index 000000000..baabac608 --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/AddBeneficiaryRequest.ts @@ -0,0 +1,239 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; +import { OptionalField } from '@core/decorator/OptionalDecorator'; + +export default class AddBeneficiaryRequest extends ValidatedRequest { + securityId: string; + beneficiaryId: string; + @OptionalField() + data?: string; + + constructor({ + securityId, + beneficiaryId, + data, + }: { + securityId: string; + beneficiaryId: string; + data?: string; + }) { + super({ + beneficiaryId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + data: (val) => { + const validation = FormatValidation.checkBytesFormat(); + if (val == '') return; + const result = validation(val); + if (result) return result; + }, + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + this.beneficiaryId = beneficiaryId; + this.data = data; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/CreateBondRequest.ts b/packages/ats/sdk/src/port/in/request/bond/CreateBondRequest.ts index e86ad5e2c..406b6b50b 100644 --- a/packages/ats/sdk/src/port/in/request/bond/CreateBondRequest.ts +++ b/packages/ats/sdk/src/port/in/request/bond/CreateBondRequest.ts @@ -210,6 +210,7 @@ import FormatValidation from '../FormatValidation'; import { SecurityDate } from '@domain/context/shared/SecurityDate'; import { Factory } from '@domain/context/factory/Factories'; +import { InvalidValue } from '../error/InvalidValue'; export default class CreateBondRequest extends ValidatedRequest { name: string; @@ -261,6 +262,12 @@ export default class CreateBondRequest extends ValidatedRequest { @@ -385,6 +396,29 @@ export default class CreateBondRequest extends ValidatedRequest { + return FormatValidation.checkHederaIdOrEvmAddressArray( + val ?? [], + 'beneficiariesIds', + true, + ); + }, + + beneficiariesData: (val) => { + const validation = FormatValidation.checkBytesFormat(); + if (val?.length != this.beneficiariesIds?.length) { + return [ + new InvalidValue( + `The list of beneficiariesIds and beneficiariesData must have equal length.`, + ), + ]; + } + for (const data of val ?? []) { + if (data == '') continue; + const result = validation(data); + if (result) return result; + } + }, }); this.name = name; this.symbol = symbol; @@ -416,5 +450,7 @@ export default class CreateBondRequest extends ValidatedRequest { salt: string; @@ -259,6 +260,12 @@ export default class CreateTrexSuiteBondRequest extends ValidatedRequest { @@ -421,6 +432,28 @@ export default class CreateTrexSuiteBondRequest extends ValidatedRequest { + return FormatValidation.checkHederaIdOrEvmAddressArray( + val ?? [], + 'beneficiariesIds', + true, + ); + }, + beneficiariesData: (val) => { + const validation = FormatValidation.checkBytesFormat(); + if (val?.length != this.beneficiariesIds?.length) { + return [ + new InvalidValue( + `The list of beneficiariesIds and beneficiariesData must have equal length.`, + ), + ]; + } + for (const data of val ?? []) { + if (data == '') continue; + const result = validation(data); + if (result) return result; + } + }, }); this.salt = salt; @@ -465,5 +498,7 @@ export default class CreateTrexSuiteBondRequest extends ValidatedRequest { + securityId: string; + + constructor({ securityId }: { securityId: string }) { + super({ + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/GetBeneficiariesRequest.ts b/packages/ats/sdk/src/port/in/request/bond/GetBeneficiariesRequest.ts new file mode 100644 index 000000000..560168b05 --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/GetBeneficiariesRequest.ts @@ -0,0 +1,233 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; + +export default class GetBeneficiariesRequest extends ValidatedRequest { + securityId: string; + pageIndex: number; + pageSize: number; + + constructor({ + securityId, + pageIndex, + pageSize, + }: { + securityId: string; + pageIndex: number; + pageSize: number; + }) { + super({ + pageIndex: FormatValidation.checkNumber({ min: 0 }), + pageSize: FormatValidation.checkNumber({ min: 1 }), + + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + this.pageIndex = pageIndex; + this.pageSize = pageSize; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/GetBeneficiaryDataRequest.ts b/packages/ats/sdk/src/port/in/request/bond/GetBeneficiaryDataRequest.ts new file mode 100644 index 000000000..908afba5d --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/GetBeneficiaryDataRequest.ts @@ -0,0 +1,227 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; + +export default class GetBeneficiaryDataRequest extends ValidatedRequest { + securityId: string; + beneficiaryId: string; + + constructor({ + securityId, + beneficiaryId, + }: { + securityId: string; + beneficiaryId: string; + }) { + super({ + beneficiaryId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + this.beneficiaryId = beneficiaryId; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/IsBeneficiaryRequest.ts b/packages/ats/sdk/src/port/in/request/bond/IsBeneficiaryRequest.ts new file mode 100644 index 000000000..0162b219f --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/IsBeneficiaryRequest.ts @@ -0,0 +1,228 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; + +export default class IsBeneficiaryRequest extends ValidatedRequest { + securityId: string; + beneficiaryId: string; + + constructor({ + securityId, + beneficiaryId, + }: { + securityId: string; + beneficiaryId: string; + }) { + super({ + beneficiaryId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + this.beneficiaryId = beneficiaryId; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/RemoveBeneficiaryRequest.ts b/packages/ats/sdk/src/port/in/request/bond/RemoveBeneficiaryRequest.ts new file mode 100644 index 000000000..48fbdaab2 --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/RemoveBeneficiaryRequest.ts @@ -0,0 +1,228 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; + +export default class RemoveBeneficiaryRequest extends ValidatedRequest { + securityId: string; + beneficiaryId: string; + + constructor({ + securityId, + beneficiaryId, + }: { + securityId: string; + beneficiaryId: string; + }) { + super({ + beneficiaryId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + + this.securityId = securityId; + this.beneficiaryId = beneficiaryId; + } +} diff --git a/packages/ats/sdk/src/port/in/request/bond/UpdateBeneficiaryDataRequest.ts b/packages/ats/sdk/src/port/in/request/bond/UpdateBeneficiaryDataRequest.ts new file mode 100644 index 000000000..ca24a789a --- /dev/null +++ b/packages/ats/sdk/src/port/in/request/bond/UpdateBeneficiaryDataRequest.ts @@ -0,0 +1,237 @@ +/* + 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 ValidatedRequest from '@core/validation/ValidatedArgs'; +import FormatValidation from '../FormatValidation'; + +export default class UpdateBeneficiaryDataRequest extends ValidatedRequest { + securityId: string; + beneficiaryId: string; + data: string; + + constructor({ + securityId, + beneficiaryId, + data, + }: { + securityId: string; + beneficiaryId: string; + data: string; + }) { + super({ + beneficiaryId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + data: (val) => { + const validation = FormatValidation.checkBytesFormat(); + if (val == '') return; + const result = validation(val); + if (result) return result; + }, + securityId: FormatValidation.checkHederaIdFormatOrEvmAddress(), + }); + this.securityId = securityId; + this.beneficiaryId = beneficiaryId; + this.data = data; + } +} diff --git a/packages/ats/sdk/src/port/in/request/index.ts b/packages/ats/sdk/src/port/in/request/index.ts index b3389d70b..742e80bcd 100644 --- a/packages/ats/sdk/src/port/in/request/index.ts +++ b/packages/ats/sdk/src/port/in/request/index.ts @@ -392,6 +392,13 @@ import GetSecurityHoldersRequest from './security/GetSecurityHoldersRequest'; import GetTotalSecurityHoldersRequest from './security/GetTotalSecurityHoldersRequest'; import CreateTrexSuiteEquityRequest from './equity/CreateTrexSuiteEquityRequest'; import CreateTrexSuiteBondRequest from './bond/CreateTrexSuiteBondRequest'; +import AddBeneficiaryRequest from './bond/AddBeneficiaryRequest'; +import RemoveBeneficiaryRequest from './bond/RemoveBeneficiaryRequest'; +import UpdateBeneficiaryDataRequest from './bond/UpdateBeneficiaryDataRequest'; +import GetBeneficiaryDataRequest from './bond/GetBeneficiaryDataRequest'; +import GetBeneficiariesCountRequest from './bond/GetBeneficiariesCountRequest'; +import GetBeneficiariesRequest from './bond/GetBeneficiariesRequest'; +import IsBeneficiaryRequest from './bond/IsBeneficiaryRequest'; export { CreateEquityRequest, @@ -582,4 +589,11 @@ export { GetTotalSecurityHoldersRequest, CreateTrexSuiteBondRequest, CreateTrexSuiteEquityRequest, + AddBeneficiaryRequest, + RemoveBeneficiaryRequest, + UpdateBeneficiaryDataRequest, + IsBeneficiaryRequest, + GetBeneficiaryDataRequest, + GetBeneficiariesCountRequest, + GetBeneficiariesRequest, }; diff --git a/packages/ats/sdk/src/port/out/TransactionAdapter.ts b/packages/ats/sdk/src/port/out/TransactionAdapter.ts index 9e6100212..69b1f0ef0 100644 --- a/packages/ats/sdk/src/port/out/TransactionAdapter.ts +++ b/packages/ats/sdk/src/port/out/TransactionAdapter.ts @@ -280,6 +280,8 @@ interface ITransactionAdapter { externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], diamondOwnerAccount?: EvmAddress, + beneficiaries?: EvmAddress[], + beneficiariesData?: string[], factoryId?: ContractId | string, ): Promise; @@ -1047,6 +1049,26 @@ interface IAgent { ): Promise; } +interface IBeneficiaries { + addBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise; + removeBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + securityId?: ContractId | string, + ): Promise; + updateBeneficiaryData( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise; +} + export default abstract class TransactionAdapter implements WalletAdapter, @@ -1069,7 +1091,8 @@ export default abstract class TransactionAdapter IIdentityRegistryTransactionAdapter, IFreezeAdapter, IBatchAdapter, - IAgent + IAgent, + IBeneficiaries { abstract triggerPendingScheduledSnapshots( security: EvmAddress, @@ -1139,6 +1162,8 @@ export default abstract class TransactionAdapter externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], diamondOwnerAccount?: EvmAddress, + beneficiaries?: EvmAddress[], + beneficiariesData?: string[], factoryId?: ContractId | string, ): Promise; abstract grantRole( @@ -1858,6 +1883,8 @@ export default abstract class TransactionAdapter compliance: EvmAddress, identityRegistryAddress: EvmAddress, diamondOwnerAccount: EvmAddress, + beneficiaries?: EvmAddress[], + beneficiariesData?: string[], externalPauses?: EvmAddress[], externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], @@ -1890,4 +1917,22 @@ export default abstract class TransactionAdapter externalKycLists?: EvmAddress[], factoryId?: ContractId | string, ): Promise; + + abstract addBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise; + abstract removeBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + securityId?: ContractId | string, + ): Promise; + abstract updateBeneficiaryData( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise; } diff --git a/packages/ats/sdk/src/port/out/hs/HederaTransactionAdapter.ts b/packages/ats/sdk/src/port/out/hs/HederaTransactionAdapter.ts index ca38c112f..4104d5c0c 100644 --- a/packages/ats/sdk/src/port/out/hs/HederaTransactionAdapter.ts +++ b/packages/ats/sdk/src/port/out/hs/HederaTransactionAdapter.ts @@ -251,6 +251,7 @@ import { ERC3643OperationsFacet__factory, ERC3643BatchFacet__factory, TREXFactoryAts__factory, + BeneficiariesFacet__factory, } from '@hashgraph/asset-tokenization-contracts'; import { _PARTITION_ID_1, EVM_ZERO_ADDRESS, GAS } from '@core/Constants'; import TransactionAdapter from '../TransactionAdapter'; @@ -547,6 +548,8 @@ export abstract class HederaTransactionAdapter extends TransactionAdapter { externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], diamondOwnerAccount?: EvmAddress, + beneficiaries: EvmAddress[] = [], + beneficiariesData: string[] = [], factoryId?: ContractId | string, ): Promise { try { @@ -610,6 +613,8 @@ export abstract class HederaTransactionAdapter extends TransactionAdapter { const securityTokenToCreate = new FactoryBondToken( security, bondDetails, + beneficiaries.map((addr) => addr.toString()), + beneficiariesData.map((data) => (data == '' ? '0x' : data)), ); const additionalSecurityData: AdditionalSecurityData = { @@ -3181,6 +3186,8 @@ export abstract class HederaTransactionAdapter extends TransactionAdapter { compliance: EvmAddress, identityRegistryAddress: EvmAddress, diamondOwnerAccount: EvmAddress, + beneficiaries: EvmAddress[] = [], + beneficiariesData: string[] = [], externalPauses?: EvmAddress[], externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], @@ -3245,6 +3252,8 @@ export abstract class HederaTransactionAdapter extends TransactionAdapter { const securityTokenToCreate = new FactoryBondToken( securityData, bondDetailsData, + beneficiaries.map((b) => b.toString()), + beneficiariesData.map((data) => (data == '' ? '0x' : data)), ); const additionalSecurityData: AdditionalSecurityData = { @@ -3444,6 +3453,58 @@ export abstract class HederaTransactionAdapter extends TransactionAdapter { } } + addBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise { + LogService.logTrace( + `Adding beneficiary: ${beneficiary} to security: ${security}`, + ); + + return this.executeWithArgs( + new BeneficiariesFacet__factory().attach(security.toString()), + 'addBeneficiary', + securityId!, + GAS.ADD_BENEFICIARY, + [beneficiary.toString(), data], + ); + } + removeBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + securityId?: ContractId | string, + ): Promise { + LogService.logTrace( + `Removing beneficiary: ${beneficiary} from security: ${security}`, + ); + return this.executeWithArgs( + new BeneficiariesFacet__factory().attach(security.toString()), + 'removeBeneficiary', + securityId!, + GAS.REMOVE_BENEFICIARY, + [beneficiary.toString()], + ); + } + updateBeneficiaryData( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise { + LogService.logTrace( + `Updating beneficiary: ${beneficiary} data in security: ${security}`, + ); + return this.executeWithArgs( + new BeneficiariesFacet__factory().attach(security.toString()), + 'updateBeneficiaryData', + securityId!, + GAS.UPDATE_BENEFICIARY, + [beneficiary.toString(), data], + ); + } + // * Definition of the abstract methods abstract signAndSendTransaction( transaction: Transaction, diff --git a/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts b/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts index f5a16df0b..75426950a 100644 --- a/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts +++ b/packages/ats/sdk/src/port/out/rpc/RPCQueryAdapter.ts @@ -259,6 +259,7 @@ import { SsiManagementFacet__factory, ERC3643ReadFacet__factory, TREXFactoryAts__factory, + BeneficiariesFacet__factory, } from '@hashgraph/asset-tokenization-contracts'; import { ScheduledSnapshot } from '@domain/context/security/ScheduledSnapshot'; import { VotingRights } from '@domain/context/equity/VotingRights'; @@ -289,6 +290,7 @@ import { ClearingTransfer, } from '@domain/context/security/Clearing'; import { HoldDetails } from '@domain/context/security/Hold'; +import { start } from 'repl'; const LOCAL_JSON_RPC_RELAY_URL = 'http://127.0.0.1:7546/api'; @@ -2040,4 +2042,55 @@ export class RPCQueryAdapter { ).getToken(salt); return token; } + + async isBeneficiary( + address: EvmAddress, + beneficiary: EvmAddress, + ): Promise { + LogService.logTrace( + `Checking if the address ${beneficiary.toString()} is a beneficiary for the security: ${address.toString()}`, + ); + return await this.connect( + BeneficiariesFacet__factory, + address.toString(), + ).isBeneficiary(beneficiary.toString()); + } + + async getBeneficiaryData( + address: EvmAddress, + beneficiary: EvmAddress, + ): Promise { + LogService.logTrace( + `Getting beneficiary data for the address ${beneficiary.toString()} for the security: ${address.toString()}`, + ); + return await this.connect( + BeneficiariesFacet__factory, + address.toString(), + ).getBeneficiaryData(beneficiary.toString()); + } + + async getBeneficiariesCount(address: EvmAddress): Promise { + LogService.logTrace( + `Getting beneficiaries count for the security: ${address.toString()}`, + ); + return ( + await this.connect( + BeneficiariesFacet__factory, + address.toString(), + ).getBeneficiariesCount() + ).toNumber(); + } + async getBeneficiaries( + address: EvmAddress, + page: number, + pageLength: number, + ): Promise { + LogService.logTrace( + `Getting beneficiaries from ${page} to ${pageLength} for the security: ${address.toString()}`, + ); + return await this.connect( + BeneficiariesFacet__factory, + address.toString(), + ).getBeneficiaries(page, pageLength); + } } diff --git a/packages/ats/sdk/src/port/out/rpc/RPCTransactionAdapter.ts b/packages/ats/sdk/src/port/out/rpc/RPCTransactionAdapter.ts index 15e9954b2..57e07e79e 100644 --- a/packages/ats/sdk/src/port/out/rpc/RPCTransactionAdapter.ts +++ b/packages/ats/sdk/src/port/out/rpc/RPCTransactionAdapter.ts @@ -209,7 +209,7 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import TransactionResponse from '@domain/context/transaction/TransactionResponse'; import TransactionAdapter, { InitializationData } from '../TransactionAdapter'; -import { Signer } from 'ethers'; +import { BaseContract, ContractTransaction, Signer } from 'ethers'; import { singleton } from 'tsyringe'; import Account from '@domain/context/account/Account'; import { lazyInject } from '@core/decorator/LazyInjectDecorator'; @@ -278,6 +278,7 @@ import { TransferAndLockFacet__factory, ERC1410TokenHolderFacet__factory, TREXFactoryAts__factory, + BeneficiariesFacet__factory, } from '@hashgraph/asset-tokenization-contracts'; import { Resolvers } from '@domain/context/factory/Resolvers'; import EvmAddress from '@domain/context/contract/EvmAddress'; @@ -421,6 +422,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], diamondOwnerAccount?: EvmAddress, + beneficiaries: EvmAddress[] = [], + beneficiariesData: string[] = [], ): Promise { return this.createSecurity( securityInfo, @@ -439,6 +442,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { new FactoryBondToken( security, details.bondDetails, + beneficiaries.map((addr) => addr.toString()), + beneficiariesData.map((data) => (data == '' ? '0x' : data)), ), 'deployBond', GAS.CREATE_BOND_ST, @@ -3037,15 +3042,31 @@ export class RPCTransactionAdapter extends TransactionAdapter { ); } - private async executeTransaction( - factory: any, - method: string, - args: any[], + private async executeTransaction< + C extends BaseContract, + F extends { + [K in keyof C]: C[K] extends ( + ...args: any[] + ) => Promise + ? K + : never; + }[keyof C] & + string, + >( + factory: C, + method: F, + args: Parameters< + C[F] extends (...args: infer P) => any ? (...args: P) => any : never + >, gasLimit: number, eventName?: string, ): Promise { LogService.logTrace(`Executing ${method} with args:`, args); - const tx = await factory[method](...args, { gasLimit }); + + const fn = factory[method] as ( + ...args: any[] + ) => Promise; + const tx = await fn(...args, { gasLimit }); return RPCTransactionResponseAdapter.manageResponse( tx, this.networkService.environment, @@ -3134,6 +3155,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { compliance: EvmAddress, identityRegistryAddress: EvmAddress, diamondOwnerAccount: EvmAddress, + beneficiaries: EvmAddress[] = [], + beneficiariesData: string[] = [], externalPauses?: EvmAddress[], externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], @@ -3160,6 +3183,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { compliance, identityRegistryAddress, diamondOwnerAccount, + beneficiaries, + beneficiariesData, externalPauses, externalControlLists, externalKycLists, @@ -3213,6 +3238,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { compliance, identityRegistryAddress, diamondOwnerAccount, + [], + [], externalPauses, externalControlLists, externalKycLists, @@ -3233,9 +3260,7 @@ export class RPCTransactionAdapter extends TransactionAdapter { issuers: string[], issuerClaims: number[][], security: Security, - tokenDetails: - | { bondDetails: BondDetails } - | EquityDetails, + tokenDetails: { bondDetails: BondDetails } | EquityDetails, factory: EvmAddress, resolver: EvmAddress, configId: string, @@ -3243,6 +3268,8 @@ export class RPCTransactionAdapter extends TransactionAdapter { compliance: EvmAddress, identityRegistryAddress: EvmAddress, diamondOwnerAccount: EvmAddress, + beneficiariesId: EvmAddress[], + beneficiariesData: string[], externalPauses?: EvmAddress[], externalControlLists?: EvmAddress[], externalKycLists?: EvmAddress[], @@ -3269,16 +3296,20 @@ export class RPCTransactionAdapter extends TransactionAdapter { bondDetails: BondDetails; }; tokenData = { - securityData, + security: securityData, bondDetails: SecurityDataBuilder.buildBondDetails(details.bondDetails), - }; + beneficiaries: beneficiariesId.map((addr) => addr.toString()), + beneficiariesData: beneficiariesData.map((data) => + data == '' ? '0x' : data, + ), + } as FactoryBondToken; } else { tokenData = { - securityData, + security: securityData, equityDetails: SecurityDataBuilder.buildEquityDetails( tokenDetails as EquityDetails, ), - }; + } as FactoryEquityToken; } const factoryContract = TREXFactoryAts__factory.connect( @@ -3331,4 +3362,62 @@ export class RPCTransactionAdapter extends TransactionAdapter { ); } } + + addBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + securityId?: ContractId | string, + ): Promise { + LogService.logTrace( + `Adding beneficiary ${beneficiary.toString()} to security ${security.toString()}`, + ); + return this.executeTransaction( + BeneficiariesFacet__factory.connect( + security.toString(), + this.getSignerOrProvider(), + ), + 'addBeneficiary', + [beneficiary.toString(), data], + GAS.ADD_BENEFICIARY, + ); + } + + removeBeneficiary( + security: EvmAddress, + beneficiary: EvmAddress, + securityId?: ContractId | string, + ): Promise { + LogService.logTrace( + `Removing beneficiary ${beneficiary.toString()} from security ${security.toString()}`, + ); + return this.executeTransaction( + BeneficiariesFacet__factory.connect( + security.toString(), + this.getSignerOrProvider(), + ), + 'removeBeneficiary', + [beneficiary.toString()], + GAS.REMOVE_BENEFICIARY, + ); + } + + updateBeneficiaryData( + security: EvmAddress, + beneficiary: EvmAddress, + data: string, + ): Promise { + LogService.logTrace( + `Updating beneficiary ${beneficiary.toString()} for security ${security.toString()}`, + ); + return this.executeTransaction( + BeneficiariesFacet__factory.connect( + security.toString(), + this.getSignerOrProvider(), + ), + 'updateBeneficiaryData', + [beneficiary.toString(), data], + GAS.UPDATE_BENEFICIARY, + ); + } } diff --git a/packages/mass-payout/eslint.config.mjs b/packages/mass-payout/eslint.config.mjs index 44825c92a..5f8205d2e 100644 --- a/packages/mass-payout/eslint.config.mjs +++ b/packages/mass-payout/eslint.config.mjs @@ -21,4 +21,4 @@ const massPayoutConfig = baseConfig }, ]); -export default massPayoutConfig; \ No newline at end of file +export default massPayoutConfig; diff --git a/packages/mass-payout/prettier.config.mjs b/packages/mass-payout/prettier.config.mjs index 2c9631564..7fd011a9a 100644 --- a/packages/mass-payout/prettier.config.mjs +++ b/packages/mass-payout/prettier.config.mjs @@ -4,4 +4,4 @@ */ import baseConfig from '../../prettier.config.mjs'; -export default baseConfig; \ No newline at end of file +export default baseConfig;