diff --git a/package-lock.json b/package-lock.json index 23d382e97..3393f0ecd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8415,6 +8415,16 @@ "url": "https://opencollective.com/node-fetch" } }, +<<<<<<< HEAD + "node_modules/@onchain-id/solidity": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@onchain-id/solidity/-/solidity-2.2.1.tgz", + "integrity": "sha512-B54InT8yi89qlh9UVCARcfdQLVDP7Lef87B/Ww2Wn19oyEbPmlWho2EK1sgnrt/8Q0fGX/7y5rDnx3HPy28NTA==", + "dev": true, + "license": "ISC" + }, +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "node_modules/@openzeppelin/contracts": { "version": "4.9.6", "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.9.6.tgz", @@ -11311,6 +11321,16 @@ "@thomaschaplin/cusip-generator": "^1.0.1" } }, +<<<<<<< HEAD + "node_modules/@tokenysolutions/t-rex": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@tokenysolutions/t-rex/-/t-rex-4.1.6.tgz", + "integrity": "sha512-GNmVAC11cqwF6bmVCl0yhaVfPLBptF4K0vmepghTPbSogky1WG+38h7RR/p7909Si2JgswreeeLZZyBLN0KZrg==", + "dev": true, + "license": "SEE LICENSE IN LICENSE.md" + }, +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -21751,6 +21771,22 @@ "dev": true, "license": "MIT" }, +<<<<<<< HEAD + "node_modules/hardhat-dependency-compiler": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/hardhat-dependency-compiler/-/hardhat-dependency-compiler-1.2.1.tgz", + "integrity": "sha512-xG5iwbspTtxOEiP5UsPngEYQ1Hg+fjTjliapIjdTQmwGkCPofrsDhQDV2O/dopcYzcR68nTx2X8xTewYHgA2rQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.14.0" + }, + "peerDependencies": { + "hardhat": "^2.0.0" + } + }, +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "node_modules/hardhat-gas-reporter": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/hardhat-gas-reporter/-/hardhat-gas-reporter-1.0.10.tgz", @@ -37337,11 +37373,19 @@ "@hashgraph/sdk": "^2.62.0", "@nomicfoundation/hardhat-chai-matchers": "^1.0.6", "@nomicfoundation/hardhat-toolbox": "^2.0.2", +<<<<<<< HEAD + "@onchain-id/solidity": "^2.2.1", +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "@openzeppelin/contracts": "^4.9.6", "@openzeppelin/contracts-upgradeable": "^4.9.6", "@openzeppelin/hardhat-upgrades": "^1.22.1", "@terminal3/ecdsa_vc": "^0.1.19", "@thomaschaplin/isin-generator": "^1.0.3", +<<<<<<< HEAD + "@tokenysolutions/t-rex": "^4.1.6", +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "@typechain/ethers-v5": "^10.1.0", "@typechain/hardhat": "^6.1.2", "@types/jest": "^29.5.14", @@ -37351,6 +37395,10 @@ "hardhat": "^2.22.19", "hardhat-abi-exporter": "^2.11.0", "hardhat-contract-sizer": "^2.10.0", +<<<<<<< HEAD + "hardhat-dependency-compiler": "^1.2.1", +======= +>>>>>>> origin/refactor/BBND-1075-workspaces-migration "hardhat-gas-reporter": "^1.0.8", "rimraf": "^6.0.1", "solidity-coverage": "^0.8.14", diff --git a/package.json b/package.json index be23d85e8..aa0f15eea 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "setup": "npm run ats:setup && npm run mass-payout:setup", "lint": "npm run lint:js && npm run lint:sol", "lint:js": "eslint . --cache", - "lint:sol": "solhint 'packages/ats/contracts/contracts/**/*.sol' --config packages/ats/contracts/.solhint.json", + "lint:sol": "solhint 'packages/ats/contracts/contracts/**/*.sol' --config packages/ats/contracts/.solhint.json --ignore-path packages/ats/contracts/.solhintignore", "lint:fix": "eslint . --fix && npm run format", "format": "prettier --write '*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml}' 'packages/**/*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml,sol}' 'apps/**/*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml}' --cache", "format:check": "prettier --check '*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml}' 'packages/**/*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml,sol}' 'apps/**/*.{js,mjs,cjs,ts,tsx,mts,json,md,yml,yaml}' --cache", diff --git a/packages/ats/contracts/.gitignore b/packages/ats/contracts/.gitignore index 021789d0b..808a8c49c 100644 --- a/packages/ats/contracts/.gitignore +++ b/packages/ats/contracts/.gitignore @@ -29,6 +29,7 @@ coverage coverage.json gas-report.txt extracted-methods.txt +deployedContracts.json #Hardhat files cache diff --git a/packages/ats/contracts/Configuration.ts b/packages/ats/contracts/Configuration.ts index e0584d3ba..d7b100c65 100644 --- a/packages/ats/contracts/Configuration.ts +++ b/packages/ats/contracts/Configuration.ts @@ -272,8 +272,14 @@ export const CONTRACT_NAMES = [ 'FreezeFacet', 'ComplianceMock', 'IdentityRegistryMock', + 'TREXFactoryAts', ] as const export type ContractName = (typeof CONTRACT_NAMES)[number] +export const LIBRARY_NAMES = [ + 'TREXBondDeploymentLib', + 'TREXEquityDeploymentLib', +] +export type LibraryName = (typeof LIBRARY_NAMES)[number] export const CONTRACT_NAMES_WITH_PROXY = ['Factory', 'BusinessLogicResolver'] export const CONTRACT_FACTORY_NAMES = CONTRACT_NAMES.map( diff --git a/packages/ats/contracts/contracts/factory/ERC3643/TREXFactory.sol b/packages/ats/contracts/contracts/factory/ERC3643/TREXFactory.sol new file mode 100644 index 000000000..91873e714 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/TREXFactory.sol @@ -0,0 +1,417 @@ +/* + 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.17; + +// solhint-disable no-global-import +// solhint-disable no-empty-blocks +// solhint-disable private-vars-leading-underscore +import '@tokenysolutions/t-rex/contracts/factory/TREXFactory.sol'; +import '@openzeppelin/contracts/access/Ownable.sol'; +import {TRexIFactory, FactoryRegulationData} from './interfaces/IFactory.sol'; +import {TREXBondDeploymentLib} from './libraries/TREXBondDeploymentLib.sol'; +import {TREXEquityDeploymentLib} from './libraries/TREXEquityDeploymentLib.sol'; + +/// @author Tokeny Solutions +/// @notice Adapted from the T-REX official repository to deploy an ERC-3643-compatible ATS security token +/// @dev Uses tree-like structure with libraries as leaves instead of resolver proxy pattern for simplicity +// solhint-disable custom-errors +contract TREXFactoryAts is ITREXFactory, Ownable { + /// @notice TokenDetails with the ATS factory overlapping fields removed + /// @param owner Address of the owner of all contracts. The factory will append it to the provided RBACs if + /// the T_REX_OWNER_ROLE is not found. For a cheaper deployment, add the owner at the first position in the array + /// @param irs Identity registry storage address. Set it to ZERO address if you want to deploy a new storage. + /// If an address is provided, please ensure that the factory is set as owner of the contract + /// @param ONCHAINID ONCHAINID of the token + /// @param irAgents List of agents of the identity registry (can be set to an AgentManager contract) + /// @param tokenAgents List of agents of the token + /// @param complianceModules Modules to bind to the compliance, indexes are corresponding to the settings + /// callData indexes + /// If a module doesn't require settings, it can be added at the end of the array, at index > settings.length + /// @param complianceSettings Settings calls for compliance modules + struct TokenDetailsAts { + address owner; + address irs; + // solhint-disable-next-line var-name-mixedcase + address ONCHAINID; + address[] irAgents; + address[] tokenAgents; + address[] complianceModules; + bytes[] complianceSettings; + } + + /// @dev The address of the implementation authority contract used in the tokens deployed by the factory + address private implementationAuthority; + + /// @dev The address of the Identity Factory used to deploy token OIDs + address private idFactory; + + /// @dev Mapping containing info about the token contracts corresponding to salt already used for + /// CREATE2 deployments + mapping(string => address) public tokenDeployed; + + /// @dev The address of the ATS suite factory + address private atsFactory; + + /** + * @dev Constructor is setting the implementation authority and the Identity Factory of the TREX factory + * @dev The constructor has been adjusted to allow null addresses later set by the owner + */ + constructor( + address _implementationAuthority, + address _idFactory, + address _atsFactory + ) { + implementationAuthority = _implementationAuthority; + idFactory = _idFactory; + atsFactory = _atsFactory; + } + + /** + * @dev See {ITREXFactory-deployTREXSuite}. + * @dev Disabled + */ + function deployTREXSuite( + string memory _salt, + TokenDetails calldata _tokenDetails, + ClaimDetails calldata _claimDetails + ) external {} + + /** + * @dev See {ITREXFactory-deployTREXSuite}. + * @dev Original method adapted to deploy an ATS equity + */ + function deployTREXSuiteAtsEquity( + string memory _salt, + TokenDetailsAts calldata _tokenDetails, + ClaimDetails calldata _claimDetails, + TRexIFactory.EquityData calldata _equityData, + FactoryRegulationData calldata _factoryRegulationData + ) external { + TREXEquityDeploymentLib.deployTREXSuiteAtsEquity( + tokenDeployed, + implementationAuthority, + idFactory, + atsFactory, + _salt, + _tokenDetails, + _claimDetails, + _equityData, + _factoryRegulationData + ); + } + + /** + * @dev See {ITREXFactory-deployTREXSuite}. + * @dev Original method adapted to deploy an ATS bond + */ + function deployTREXSuiteAtsBond( + string memory _salt, + TokenDetailsAts calldata _tokenDetails, + ClaimDetails calldata _claimDetails, + TRexIFactory.BondData calldata _bondData, + FactoryRegulationData calldata _factoryRegulationData + ) external { + TREXBondDeploymentLib.deployTREXSuiteAtsBond( + tokenDeployed, + implementationAuthority, + idFactory, + atsFactory, + _salt, + _tokenDetails, + _claimDetails, + _bondData, + _factoryRegulationData + ); + } + + /** + * @inheritdoc ITREXFactory + */ + function recoverContractOwnership( + address _contract, + address _newOwner + ) external override onlyOwner { + (Ownable(_contract)).transferOwnership(_newOwner); + } + + /** + * @inheritdoc ITREXFactory + */ + function setImplementationAuthority( + address _implementationAuthority + ) external override onlyOwner { + require( + _implementationAuthority != address(0), + 'invalid argument - zero address' + ); + // should not be possible to set an implementation authority that is not complete + require( + (ITREXImplementationAuthority(_implementationAuthority)) + .getCTRImplementation() != + address(0) && + (ITREXImplementationAuthority(_implementationAuthority)) + .getIRImplementation() != + address(0) && + (ITREXImplementationAuthority(_implementationAuthority)) + .getIRSImplementation() != + address(0) && + (ITREXImplementationAuthority(_implementationAuthority)) + .getMCImplementation() != + address(0) && + (ITREXImplementationAuthority(_implementationAuthority)) + .getTIRImplementation() != + address(0), + 'invalid Implementation Authority' + ); + implementationAuthority = _implementationAuthority; + emit ImplementationAuthoritySet(_implementationAuthority); + } + + /** + * @inheritdoc ITREXFactory + */ + function setIdFactory(address _idFactory) external override onlyOwner { + require(_idFactory != address(0), 'invalid argument - zero address'); + idFactory = _idFactory; + emit IdFactorySet(_idFactory); + } + + /** + * @dev Sets the address of the ATS factory + */ + function setAtsFactory(address _atsFactory) external onlyOwner { + require(_atsFactory != address(0), 'invalid argument - zero address'); + atsFactory = _atsFactory; + } + + /** + * @inheritdoc ITREXFactory + */ + function getImplementationAuthority() + external + view + override + returns (address) + { + return implementationAuthority; + } + + /** + * @inheritdoc ITREXFactory + */ + function getIdFactory() external view override returns (address) { + return idFactory; + } + + /** + * @inheritdoc ITREXFactory + */ + function getToken( + string calldata _salt + ) external view override returns (address) { + return tokenDeployed[_salt]; + } +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IAccessControl.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IAccessControl.sol new file mode 100644 index 000000000..b854d3414 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IAccessControl.sol @@ -0,0 +1,362 @@ +/* + 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.17; + +interface TRexIAccessControl { + /** + * @dev Emitted when a role is granted to an account + * + * @param role The role to be granted + * @param account The account for which the role is to be granted + * @param operator The caller of the function that emitted the event + */ + event RoleGranted( + address indexed operator, + address indexed account, + bytes32 indexed role + ); + + /** + * @dev Emitted when a role is revoked from an account + * + * @param role The role to be revoked + * @param account The account for which the role is to be revoked + * @param operator The caller of the function that emitted the event + */ + event RoleRevoked( + address indexed operator, + address indexed account, + bytes32 indexed role + ); + + /** + * @dev Emitted when a role is renounced by an account + * + * @param role The role that was renounced + * @param account The account that renouced to the role + */ + event RoleRenounced(address indexed account, bytes32 indexed role); + + /** + * @dev Emitted when a set of roles are applied to an account + * + * @param roles The roles that was applied + * @param actives By each role, true if the role is granted, false if revoked + * @param account The account that renouced to the role + */ + event RolesApplied(bytes32[] roles, bool[] actives, address account); + + error AccountAssignedToRole(bytes32 role, address account); + error AccountNotAssignedToRole(bytes32 role, address account); + error RolesNotApplied(bytes32[] roles, bool[] actives, address account); + + /** + * @dev Grants a role + * + * @param _role The role id + * @param _account The account address + * @return success_ true or false + */ + function grantRole( + bytes32 _role, + address _account + ) external returns (bool success_); + + /** + * @dev Revokes a role + * + * @param _role The role id + * @param _account The account address + * @return success_ true or false + */ + function revokeRole( + bytes32 _role, + address _account + ) external returns (bool success_); + + /** + * @dev Renounces a role + * + * @param _role The role id + * @return success_ true or false + */ + function renounceRole(bytes32 _role) external returns (bool success_); + + /** + * @dev Apply roles to an account + * + * @param _roles The role id array + * @param _actives By each role, true if the role is granted, false if revoked + * @param _account The account address + * @return success_ true or false + */ + function applyRoles( + bytes32[] calldata _roles, + bool[] calldata _actives, + address _account + ) external returns (bool success_); + + /** + * @dev Returns the number of roles the account currently has + * + * @param _account The account address + * @return roleCount_ The number of roles + */ + function getRoleCountFor( + address _account + ) external view returns (uint256 roleCount_); + + /** + * @dev Returns an array of roles the account currently has + * + * @param _account The account address + * @param _pageIndex members to skip : _pageIndex * _pageLength + * @param _pageLength number of members to return + * @return roles_ The array containing the roles + */ + function getRolesFor( + address _account, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes32[] memory roles_); + + /** + * @dev Returns the number of members the role currently has + * + * @param _role The role id + * @return memberCount_ The number of members + */ + function getRoleMemberCount( + bytes32 _role + ) external view returns (uint256 memberCount_); + + /** + * @dev Returns an array of members the role currently has + * + * @param _role The role id + * @param _pageIndex members to skip : _pageIndex * _pageLength + * @param _pageLength number of members to return + * @return members_ The array containing the members addresses + */ + function getRoleMembers( + bytes32 _role, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory members_); + + /** + * @dev Checks if an account has a role + * + * @param _role The role id + * @param _account the account address + * @return bool true or false + */ + function hasRole( + bytes32 _role, + address _account + ) external view returns (bool); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBond.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBond.sol new file mode 100644 index 000000000..c0bbd56d5 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBond.sol @@ -0,0 +1,287 @@ +/* + 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: UNLICENSED +pragma solidity ^0.8.17; + +interface TRexIBond { + struct BondDetailsData { + bytes3 currency; + uint256 nominalValue; + uint256 startingDate; + uint256 maturityDate; + } + + struct CouponDetailsData { + uint256 couponFrequency; + uint256 couponRate; + uint256 firstCouponDate; + } + + struct Coupon { + uint256 recordDate; + uint256 executionDate; + uint256 rate; + } + + struct RegisteredCoupon { + Coupon coupon; + uint256 snapshotId; + } + + struct CouponFor { + uint256 tokenBalance; + uint256 rate; + uint256 recordDate; + uint256 executionDate; + uint8 decimals; + bool recordDateReached; + } + + function redeemAtMaturityByPartition( + address _tokenHolder, + bytes32 _partition, + uint256 _amount + ) external; + + function setCoupon( + Coupon calldata _newCoupon + ) external returns (bool success_, uint256 couponID_); + + function updateMaturityDate( + uint256 _maturityDate + ) external returns (bool success_); + + function getBondDetails() + external + view + returns (BondDetailsData memory bondDetailsData_); + + function getCouponDetails() + external + view + returns (CouponDetailsData memory couponDetails_); + + function getCoupon( + uint256 _couponID + ) external view returns (RegisteredCoupon memory registeredCoupon_); + + function getCouponFor( + uint256 _couponID, + address _account + ) external view returns (CouponFor memory couponFor_); + + function getCouponCount() external view returns (uint256 couponCount_); + + function getCouponHolders( + uint256 _couponID, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory holders_); + + function getTotalCouponHolders( + uint256 _couponID + ) external view returns (uint256); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBusinessLogicResolver.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBusinessLogicResolver.sol new file mode 100644 index 000000000..13b9b4c85 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IBusinessLogicResolver.sol @@ -0,0 +1,329 @@ +/* + 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.17; + +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +/// @title Contracts Repository +/// @notice This contract is used to register and resolve Business Logics (aka contracts) addresses using +/// a bytes32 as key. +/// +/// All registered Business Logics must have the same number of versions, so that they have a common "latest" +/// version and any previous version can be resolved for any existing Business Logic no matter when it was +/// added to the register. +/// The idea is that consumers should use Business Logics belonging to the same version since those are +/// considered fully compatible. +/// Registering a business logic (register = update its latest version or add it to the registry) will increase the +/// latest version for all Business Logics by 1. +interface TRexIBusinessLogicResolver { + enum VersionStatus { + NONE, + ACTIVATED, + DEACTIVATED + } + + /// @notice structure defining the input data type when registering or updating business logics + struct BusinessLogicRegistryData { + bytes32 businessLogicKey; + address businessLogicAddress; + } + + /// @notice structure defining the a given Version status + struct VersionData { + uint256 version; + VersionStatus status; + } + + struct BusinessLogicVersion { + VersionData versionData; + address businessLogicAddress; + } + + /// @notice Event emitted when Business Logic(s) are registered (updated or added). + /// @param businessLogics list of registered Business Logics. + /// @param newLatestVersion new latest version = previous latest version + 1. + event BusinessLogicsRegistered( + BusinessLogicRegistryData[] businessLogics, + uint256 newLatestVersion + ); + + // solhint-disable-next-line func-name-mixedcase + function initialize_BusinessLogicResolver() + external + returns (bool success_); + + /// @notice Update existing business logics addresses or add new business logics to the register. + /// the BusinessLogicsRegistered event must be emitted. + /// The latest "version" for all business logics is increased by 1. + /// @param _businessLogics list of business logics to be registered. + function registerBusinessLogics( + BusinessLogicRegistryData[] calldata _businessLogics + ) external; + + /// @notice Adds a list of selectors to the blacklist + /// @param _configurationId the configuration key to be checked. + /// @param _selectors list of selectors to be added to the blacklist + function addSelectorsToBlacklist( + bytes32 _configurationId, + bytes4[] calldata _selectors + ) external; + + /// @notice Removes a list of selectors from the blacklist + /// @param _configurationId the configuration key to be checked. + /// @param _selectors list of selectors to be removed from the blacklist + function removeSelectorsFromBlacklist( + bytes32 _configurationId, + bytes4[] calldata _selectors + ) external; + + /// @notice Returns the current status of a given version + function getVersionStatus( + uint256 _version + ) external view returns (VersionStatus status_); + + /// @notice Returns the current latest version for all business logics + function getLatestVersion() external view returns (uint256 latestVersion_); + + /// @notice Returns the business logic address for the latest version + /// @param _businessLogicKey key of the business logic. Business Logic must be active. + function resolveLatestBusinessLogic( + bytes32 _businessLogicKey + ) external view returns (address businessLogicAddress_); + + /// @notice Returns a specific business logic version address + /// @param _businessLogicKey key of the business logic. Business Logic must be active. + /// @param _version the version + function resolveBusinessLogicByVersion( + bytes32 _businessLogicKey, + uint256 _version + ) external view returns (address businessLogicAddress_); + + /// @notice Returns the count of currently active business logics + function getBusinessLogicCount() + external + view + returns (uint256 businessLogicCount_); + + /// @notice Returns a list of business logic keys + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return businessLogicKeys_ list of business logic keys + function getBusinessLogicKeys( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes32[] memory businessLogicKeys_); + + /// @notice Returns the list of selectors in the blacklist + /// @param _configurationId the configuration key to be checked. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return selectors_ List of the selectors in the blacklist + function getSelectorsBlacklist( + bytes32 _configurationId, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes4[] memory selectors_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondCutManager.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondCutManager.sol new file mode 100644 index 000000000..a6d5a95a7 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondCutManager.sol @@ -0,0 +1,433 @@ +/* + 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.17; + +import {TRexIDiamondLoupe as IDiamondLoupe} from './IDiamondLoupe.sol'; + +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +/// @title Resolver Proxy Manager +/// @notice This contract is used to manage configurations of resolverProxy's. +/// Each resolverProxy must have a resolverProxy configuration id. It could ask to the ResolverProxyCutManger by: +/// * Maintain the list of business logic that forms part of a resolverProxy configuration. +/// * Maintain and resolve the list of function selectors by each configuration knowing its business logic address. +/// * Maintain and resolve the list of interface ids by each configuration. +/// By each configurationId: +/// * latestVersion: number of versions registered. +/// * Version: Each version registered contains +/// * Version number. +/// * A list of facets +/// * facetId +/// * list of selectors +/// * list of interfaceIds +interface TRexIDiamondCutManager { + struct FacetConfiguration { + bytes32 id; + uint256 version; + } + + /// @notice emited when createConfiguration is executed + event DiamondConfigurationCreated( + bytes32 configurationId, + FacetConfiguration[] facetConfigurations, + uint256 version + ); + + /// @notice emited when createBatchConfiguration is executed + event DiamondBatchConfigurationCreated( + bytes32 configurationId, + FacetConfiguration[] facetConfigurations, + bool _isLastBatch, + uint256 version + ); + + /// @notice emited when cancelBatchConfiguration is executed + event DiamondBatchConfigurationCanceled(bytes32 configurationId); + + // @notice Not able to use bytes32(0) with configurationId + error DefaultValueForConfigurationIdNotPermitted(); + + /// @notice Not able to use a facetId unregistered + error FacetIdNotRegistered(bytes32 configurationId, bytes32 facetId); + + /// @notice Not able to duplicate facetId in list + error DuplicatedFacetInConfiguration(bytes32 facetId); + + /// @notice error that occurs when try to create a configuration and the configuration key doesn't exists + error ResolverProxyConfigurationNoRegistered( + bytes32 resolverProxyConfigurationId, + uint256 version + ); + + /// @notice error that occurs when try to add a selector and the selector is blacklisted + error SelectorBlacklisted(bytes4 selector); + + /// @notice Create a new configuration to the latest version of all facets. + /// @param _configurationId unused identifier to the configuration. + /// @param _facetConfigurations.id list of business logics to be registered. + /// @param _facetConfigurations.version list of versions of each _facetIds. + function createConfiguration( + bytes32 _configurationId, + FacetConfiguration[] calldata _facetConfigurations + ) external; + + /// @notice Create a new batch configuration to the latest version of all facets. + /// @param _configurationId unused identifier to the configuration. + /// @param _facetConfigurations.id list of business logics to be registered. + /// @param _facetConfigurations.version list of versions of each _facetIds. + /// @param _isLastBatch boolean to indicate if is the last batch iteration. + function createBatchConfiguration( + bytes32 _configurationId, + FacetConfiguration[] calldata _facetConfigurations, + bool _isLastBatch + ) external; + + /// @notice Cancel a current batch configuration. + /// @param _configurationId unused identifier to the configuration. + function cancelBatchConfiguration(bytes32 _configurationId) external; + + /// @notice check if a resolverProxy is registered. If not revert. + /// @param _configurationId the configuration key to be checked. + /// @param _version configured version in the resolverProxy. + function checkResolverProxyConfigurationRegistered( + bytes32 _configurationId, + uint256 _version + ) external; + + /// @notice Resolve the facet address knowing configuration, version and selector. + /// @param _configurationId configured key in the resolverProxy. + /// @param _version configured version in the resolverProxy. if is 0, ask for latest version. + /// @param _selector received in the call/tx to be resolver. + /// @return facetAddress_ with the resolver address of the facet. + /// If facet address cant been resolved, returns address(0). + function resolveResolverProxyCall( + bytes32 _configurationId, + uint256 _version, + bytes4 _selector + ) external view returns (address facetAddress_); + + /// @notice Resolve if an interfaceId is present in the resolverProxy configured version. + /// @param _configurationId configured key in the resolverProxy. + /// @param _version configured version in the resolverProxy. if is 0, ask for latest version. + /// @param _interfaceId received to be tested. + /// @return exists_ a true if the interfaceId is part of the resolverProxy configuration. + function resolveSupportsInterface( + bytes32 _configurationId, + uint256 _version, + bytes4 _interfaceId + ) external view returns (bool exists_); + + /// @notice if a resolverProxy is registered. + /// @param _configurationId the configuration key to be checked. + /// @param _version configured version in the resolverProxy. + function isResolverProxyConfigurationRegistered( + bytes32 _configurationId, + uint256 _version + ) external view returns (bool); + + /// @notice Returns the length of configuration keys + /// @return configurationsLength_ + function getConfigurationsLength() + external + view + returns (uint256 configurationsLength_); + + /// @notice Returns a list of configuration keys + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return configurationIds_ list of business logic keys + function getConfigurations( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes32[] memory configurationIds_); + + /// @notice Returns the latest version registered of a resolverProxy configuration. + /// @param _configurationId key to be obtained. + /// @return latestVersion_ latest version registered of a resolverProxy configuration. + function getLatestVersionByConfiguration( + bytes32 _configurationId + ) external view returns (uint256 latestVersion_); + + function getFacetsLengthByConfigurationIdAndVersion( + bytes32 _configurationId, + uint256 _version + ) external view returns (uint256 facetsLength_); + + function getFacetsByConfigurationIdAndVersion( + bytes32 _configurationId, + uint256 _version, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (IDiamondLoupe.Facet[] memory facets_); + + function getFacetSelectorsLengthByConfigurationIdVersionAndFacetId( + bytes32 _configurationId, + uint256 _version, + bytes32 _facetId + ) external view returns (uint256 facetSelectorsLength_); + + function getFacetSelectorsByConfigurationIdVersionAndFacetId( + bytes32 _configurationId, + uint256 _version, + bytes32 _facetId, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes4[] memory facetSelectors_); + + /// @notice Returns the list of facet keys. + /// @param _configurationId key to filter the facets. + /// @param _version the version to filter the facets. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facetIds_ List of the facet key by key and version + function getFacetIdsByConfigurationIdAndVersion( + bytes32 _configurationId, + uint256 _version, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes32[] memory facetIds_); + + /// @notice Returns the facet addresses con configuration + /// @param _configurationId key to filter the facets. + /// @param _version the version to filter the facets. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facetAddresses_ List of the facet addresses + function getFacetAddressesByConfigurationIdAndVersion( + bytes32 _configurationId, + uint256 _version, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory facetAddresses_); + + function getFacetIdByConfigurationIdVersionAndSelector( + bytes32 _configurationId, + uint256 _version, + bytes4 _selector + ) external view returns (bytes32 facetId_); + + /// @notice Returns the facet information. + /// @param _configurationId key to filter the facets. + /// @param _version the version to filter the facets. + /// @param _facetId the business logic key + /// @return facet_ the facet information + function getFacetByConfigurationIdVersionAndFacetId( + bytes32 _configurationId, + uint256 _version, + bytes32 _facetId + ) external view returns (IDiamondLoupe.Facet memory facet_); + + /// @notice Returns the facet address. + /// @param _configurationId key to filter the facets. + /// @param _version the version to filter the facets. + /// @param _facetId the business logic key + /// @return facetAddress_ the facet information + function getFacetAddressByConfigurationIdVersionAndFacetId( + bytes32 _configurationId, + uint256 _version, + bytes32 _facetId + ) external view returns (address facetAddress_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondLoupe.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondLoupe.sol new file mode 100644 index 000000000..d7419110e --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IDiamondLoupe.sol @@ -0,0 +1,322 @@ +/* + 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.17; +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +// A loupe is a small magnifying glass used to look at resolverProxys. +// These functions look at resolverProxys +/// #### Structs +/// ``` +/// struct Facet { +/// bytes32 facetId; +/// address facetAddress; +/// bytes4[] selectors; +/// } +///``` +// HACK: I think that Loupe and Cut should be only one contract. +interface TRexIDiamondLoupe { + struct Facet { + bytes32 id; + address addr; + bytes4[] selectors; + bytes4[] interfaceIds; + } + + /// @notice Gets all facet addresses and their four byte function selectors. + /// @return facets_ Facet + function getFacets() external view returns (Facet[] memory facets_); + + /// @notice Gets facet length. + /// @return facetsLength_ Facets length + function getFacetsLength() external view returns (uint256 facetsLength_); + + /// @notice Gets all facet addresses and their four byte function selectors. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facets_ Facet + function getFacetsByPage( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (Facet[] memory facets_); + + /// @notice Gets all the function selectors supported by a specific facet. + /// @param _facetId The facet key for the resolver. + /// @return facetSelectors_ + function getFacetSelectors( + bytes32 _facetId + ) external view returns (bytes4[] memory facetSelectors_); + + /// @notice Gets the function selectors length. + /// @param _facetId The facet key for the resolver. + /// @return facetSelectorsLength_ + function getFacetSelectorsLength( + bytes32 _facetId + ) external view returns (uint256 facetSelectorsLength_); + + /// @notice Gets all the function selectors supported by a specific facet. + /// @param _facetId The facet key for the resolver. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facetSelectors_ + function getFacetSelectorsByPage( + bytes32 _facetId, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes4[] memory facetSelectors_); + + /// @notice Get all the facet addresses used by a resolverProxy. + /// @return facetIds_ + function getFacetIds() external view returns (bytes32[] memory facetIds_); + + /// @notice Get all the facet addresses used by a resolverProxy. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facetIds_ + function getFacetIdsByPage( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (bytes32[] memory facetIds_); + + /// @notice Get all the facet addresses used by a resolverProxy. + /// @return facetAddresses_ + function getFacetAddresses() + external + view + returns (address[] memory facetAddresses_); + + /// @notice Get all the facet addresses used by a resolverProxy. + /// @param _pageIndex members to skip : _pageIndex * _pageLength + /// @param _pageLength number of members to return + /// @return facetAddresses_ + function getFacetAddressesByPage( + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory facetAddresses_); + + /// @notice Gets the facet key that supports the given selector. + /// @dev If facet is not found return address(0). + /// @param _selector The function selector. + /// @return facetId_ The facet key. + function getFacetIdBySelector( + bytes4 _selector + ) external view returns (bytes32 facetId_); + + /// @notice Get the information associated with an specific facet. + /// @dev If facet is not found return empty Facet struct. + /// @param _facetId The facet key for the resolver. + /// @return facet_ Facet data. + function getFacet( + bytes32 _facetId + ) external view returns (Facet memory facet_); + + /// @notice Gets the facet that supports the given selector. + /// @dev If facet is not found return address(0). + /// @param _selector The function selector. + /// @return facetAddress_ The facet address. + function getFacetAddress( + bytes4 _selector + ) external view returns (address facetAddress_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IERC20.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IERC20.sol new file mode 100644 index 000000000..645c530c0 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IERC20.sol @@ -0,0 +1,333 @@ +/* + 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 +// Contract copy-pasted form OZ and extended + +pragma solidity ^0.8.17; + +import {TRexIFactory as IFactory} from './IFactory.sol'; + +interface TRexIERC20 { + struct ERC20MetadataInfo { + string name; + string symbol; + string isin; + uint8 decimals; + } + + struct ERC20Metadata { + ERC20MetadataInfo info; + IFactory.SecurityType securityType; + } + + // Initialization function + // solhint-disable-next-line func-name-mixedcase + function initialize_ERC20(ERC20Metadata calldata erc1594Metadata) external; + + /** + * @dev Moves `amount` tokens from the caller's account to `to`. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transfer(address to, uint256 amount) external returns (bool); + + /** + * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * IMPORTANT: Beware that changing an allowance with this method brings the risk + * that someone may use both the old and the new allowance by unfortunate + * transaction ordering. One possible solution to mitigate this race + * condition is to first reduce the spender's allowance to 0 and set the + * desired value afterwards: + * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + * + * Emits an {Approval} event. + */ + function approve(address spender, uint256 amount) external returns (bool); + + /** + * @dev Moves `amount` tokens from `from` to `to` using the + * allowance mechanism. `amount` is then deducted from the caller's + * allowance. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transferFrom( + address from, + address to, + uint256 amount + ) external returns (bool); + + /** + * @dev Atomically increases the allowance granted to `spender` by the caller. + * + * This is an alternative to {approve} that can be used as a mitigation for + * problems described in {IERC20-approve}. + * + * Emits an {Approval} event indicating the updated allowance. + * + * Requirements: + * + * - `spender` cannot be the zero address. + */ + function increaseAllowance( + address spender, + uint256 addedValue + ) external returns (bool); + + /** + * @dev Atomically decreases the allowance granted to `spender` by the caller. + * + * This is an alternative to {approve} that can be used as a mitigation for + * problems described in {IERC20-approve}. + * + * Emits an {Approval} event indicating the updated allowance. + * + * Requirements: + * + * - `spender` cannot be the zero address. + * - `spender` must have allowance for the caller of at least + * `subtractedValue`. + */ + function decreaseAllowance( + address spender, + uint256 subtractedValue + ) external returns (bool); + + /** + * @dev Returns the remaining number of tokens that `spender` will be + * allowed to spend on behalf of `owner` through {transferFrom}. This is + * zero by default. + * + * This value changes when {approve} or {transferFrom} are called. + */ + function allowance( + address owner, + address spender + ) external view returns (uint256); + + function decimalsAdjusted() external view returns (uint8); + + function decimalsAdjustedAt( + uint256 _timestamp + ) external view returns (uint8); + + function name() external view returns (string memory); + + function symbol() external view returns (string memory); + + function decimals() external view returns (uint8); + + function decimalsAt(uint256 _timestamp) external view returns (uint8); + + function getERC20Metadata() external view returns (ERC20Metadata memory); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IEquity.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IEquity.sol new file mode 100644 index 000000000..903d31599 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IEquity.sol @@ -0,0 +1,343 @@ +/* + 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: UNLICENSED +pragma solidity ^0.8.17; + +interface TRexIEquity { + enum DividendType { + NONE, + PREFERRED, + COMMON + } + + struct EquityDetailsData { + bool votingRight; + bool informationRight; + bool liquidationRight; + bool subscriptionRight; + bool conversionRight; + bool redemptionRight; + bool putRight; + DividendType dividendRight; + bytes3 currency; + uint256 nominalValue; + } + + struct Voting { + uint256 recordDate; + bytes data; + } + + struct RegisteredVoting { + Voting voting; + uint256 snapshotId; + } + + struct Dividend { + uint256 recordDate; + uint256 executionDate; + uint256 amount; + } + + struct RegisteredDividend { + Dividend dividend; + uint256 snapshotId; + } + + struct DividendFor { + uint256 tokenBalance; + uint256 amount; + uint256 recordDate; + uint256 executionDate; + uint8 decimals; + bool recordDateReached; + } + + struct VotingFor { + uint256 tokenBalance; + uint256 recordDate; + bytes data; + uint8 decimals; + bool recordDateReached; + } + + struct ScheduledBalanceAdjustment { + uint256 executionDate; + uint256 factor; + uint8 decimals; + } + + function setDividends( + Dividend calldata _newDividend + ) external returns (bool success_, uint256 dividendID_); + + function setVoting( + Voting calldata _newVoting + ) external returns (bool success_, uint256 voteID_); + + function setScheduledBalanceAdjustment( + ScheduledBalanceAdjustment calldata _newBalanceAdjustment + ) external returns (bool success_, uint256 balanceAdjustmentID_); + + function getEquityDetails() + external + view + returns (EquityDetailsData memory equityDetailsData_); + + function getDividends( + uint256 _dividendID + ) external view returns (RegisteredDividend memory registeredDividend_); + + function getDividendsFor( + uint256 _dividendID, + address _account + ) external view returns (DividendFor memory dividendFor_); + + function getDividendsCount() external view returns (uint256 dividendCount_); + + function getDividendHolders( + uint256 _dividendID, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory holders_); + + function getTotalDividendHolders( + uint256 _dividendID + ) external view returns (uint256); + + function getVoting( + uint256 _voteID + ) external view returns (RegisteredVoting memory registeredVoting_); + + function getVotingFor( + uint256 _voteID, + address _account + ) external view returns (VotingFor memory votingFor_); + + function getVotingCount() external view returns (uint256 votingCount_); + + function getVotingHolders( + uint256 _voteID, + uint256 _pageIndex, + uint256 _pageLength + ) external view returns (address[] memory holders_); + + function getTotalVotingHolders( + uint256 _voteID + ) external view returns (uint256); + + function getScheduledBalanceAdjustment( + uint256 _balanceAdjustmentID + ) + external + view + returns (ScheduledBalanceAdjustment memory balanceAdjustment_); + + function getScheduledBalanceAdjustmentCount() + external + view + returns (uint256 balanceAdjustmentCount_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol new file mode 100644 index 000000000..2efbac16b --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IFactory.sol @@ -0,0 +1,296 @@ +/* + 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.17; +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +import {TRexIResolverProxy as IResolverProxy} from './IResolverProxy.sol'; +import { + TRexIBusinessLogicResolver as IBusinessLogicResolver +} from './IBusinessLogicResolver.sol'; +import {TRexIERC20 as IERC20} from './IERC20.sol'; +import {TRexIBond as IBond} from './IBond.sol'; +import {TRexIEquity as IEquity} from './IEquity.sol'; +import { + FactoryRegulationData, + RegulationData, + RegulationType, + RegulationSubType +} from './regulation.sol'; + +interface TRexIFactory { + enum SecurityType { + Bond, + Equity + } + + struct ResolverProxyConfiguration { + bytes32 key; + uint256 version; + } + + // TODO: Separete common data in new struct + struct SecurityData { + bool arePartitionsProtected; + bool isMultiPartition; + IBusinessLogicResolver resolver; + ResolverProxyConfiguration resolverProxyConfiguration; + IResolverProxy.Rbac[] rbacs; + bool isControllable; + bool isWhiteList; + uint256 maxSupply; + IERC20.ERC20MetadataInfo erc20MetadataInfo; + bool clearingActive; + bool internalKycActivated; + address[] externalPauses; + address[] externalControlLists; + address[] externalKycLists; + address compliance; + address identityRegistry; + } + + struct EquityData { + SecurityData security; + IEquity.EquityDetailsData equityDetails; + } + + struct BondData { + SecurityData security; + IBond.BondDetailsData bondDetails; + IBond.CouponDetailsData couponDetails; + } + + event EquityDeployed( + address indexed deployer, + address equityAddress, + EquityData equityData, + FactoryRegulationData regulationData + ); + + event BondDeployed( + address indexed deployer, + address bondAddress, + BondData bondData, + FactoryRegulationData regulationData + ); + + error EmptyResolver(IBusinessLogicResolver resolver); + error NoInitialAdmins(); + + function deployEquity( + EquityData calldata _equityData, + FactoryRegulationData calldata _factoryRegulationData + ) external returns (address equityAddress_); + + function deployBond( + BondData calldata _bondData, + FactoryRegulationData calldata _factoryRegulationData + ) external returns (address bondAddress_); + + function getAppliedRegulationData( + RegulationType _regulationType, + RegulationSubType _regulationSubType + ) external pure returns (RegulationData memory regulationData_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IResolverProxy.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IResolverProxy.sol new file mode 100644 index 000000000..3e07098b8 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IResolverProxy.sol @@ -0,0 +1,218 @@ +/* + 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.17; + +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +interface TRexIResolverProxy { + struct Rbac { + bytes32 role; + address[] members; + } + + // When no function exists for function called + error FunctionNotFound(bytes4 _functionSelector); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IStaticFunctionSelectors.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IStaticFunctionSelectors.sol new file mode 100644 index 000000000..0e49c13e8 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/IStaticFunctionSelectors.sol @@ -0,0 +1,231 @@ +/* + 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.17; + +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +interface TRexIStaticFunctionSelectors { + /// @notice Gets the static resolver key. + /// @return staticResolverKey_ Static resolver key + function getStaticResolverKey() + external + pure + returns (bytes32 staticResolverKey_); + + /// @notice Gets all function selectors of a facet. + /// @return staticFunctionSelectors_ Face functions selectors + function getStaticFunctionSelectors() + external + pure + returns (bytes4[] memory staticFunctionSelectors_); + + /// @notice Gets all interfaces ids of a facet. + /// @return staticInterfaceIds_ Face interface ids + function getStaticInterfaceIds() + external + pure + returns (bytes4[] memory staticInterfaceIds_); +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/regulation.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/regulation.sol new file mode 100644 index 000000000..0b0d5a140 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/regulation.sol @@ -0,0 +1,449 @@ +/* + 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.17; + +uint256 constant _REGS_DEAL_SIZE = 0; +AccreditedInvestors constant _REGS_ACCREDITED_INVESTORS = AccreditedInvestors + .ACCREDITATION_REQUIRED; +uint256 constant _REGS_MAX_NON_ACCREDITED_INVESTORS = 0; +ManualInvestorVerification constant _REGS_MANUAL_INVESTOR_VERIFICATION = ManualInvestorVerification + .VERIFICATION_INVESTORS_FINANCIAL_DOCUMENTS_REQUIRED; +InternationalInvestors constant _REGS_INTERNATIONAL_INVESTORS = InternationalInvestors + .ALLOWED; +ResaleHoldPeriod constant _REGS_RESALE_HOLD_PERIOD = ResaleHoldPeriod + .NOT_APPLICABLE; + +uint256 constant _REGD_506_B_DEAL_SIZE = 0; +AccreditedInvestors constant _REGD_506_B_ACCREDITED_INVESTORS = AccreditedInvestors + .ACCREDITATION_REQUIRED; +uint256 constant _REGD_506_B_MAX_NON_ACCREDITED_INVESTORS = 35; +ManualInvestorVerification constant _REGD_506_B_MANUAL_INVESTOR_VERIFICATION = ManualInvestorVerification + .VERIFICATION_INVESTORS_FINANCIAL_DOCUMENTS_REQUIRED; +InternationalInvestors constant _REGD_506_B_INTERNATIONAL_INVESTORS = InternationalInvestors + .NOT_ALLOWED; +ResaleHoldPeriod constant _REGD_506_B_RESALE_HOLD_PERIOD = ResaleHoldPeriod + .APPLICABLE_FROM_6_MOTHS_TO_1_YEAR; + +uint256 constant _REGD_506_C_DEAL_SIZE = 0; +AccreditedInvestors constant _REGD_506_C_ACCREDITED_INVESTORS = AccreditedInvestors + .ACCREDITATION_REQUIRED; +uint256 constant _REGD_506_C_MAX_NON_ACCREDITED_INVESTORS = 0; +ManualInvestorVerification constant _REGD_506_C_MANUAL_INVESTOR_VERIFICATION = ManualInvestorVerification + .VERIFICATION_INVESTORS_FINANCIAL_DOCUMENTS_REQUIRED; +InternationalInvestors constant _REGD_506_C_INTERNATIONAL_INVESTORS = InternationalInvestors + .NOT_ALLOWED; +ResaleHoldPeriod constant _REGD_506_C_RESALE_HOLD_PERIOD = ResaleHoldPeriod + .APPLICABLE_FROM_6_MOTHS_TO_1_YEAR; + +enum RegulationType { + NONE, + REG_S, + REG_D +} + +enum RegulationSubType { + NONE, + REG_D_506_B, + REG_D_506_C +} + +enum AccreditedInvestors { + NONE, + ACCREDITATION_REQUIRED +} + +enum ManualInvestorVerification { + NOTHING_TO_VERIFY, + VERIFICATION_INVESTORS_FINANCIAL_DOCUMENTS_REQUIRED +} + +enum InternationalInvestors { + NOT_ALLOWED, + ALLOWED +} + +enum ResaleHoldPeriod { + NOT_APPLICABLE, + APPLICABLE_FROM_6_MOTHS_TO_1_YEAR +} + +struct AdditionalSecurityData { + bool countriesControlListType; + string listOfCountries; + string info; +} + +struct FactoryRegulationData { + RegulationType regulationType; + RegulationSubType regulationSubType; + AdditionalSecurityData additionalSecurityData; +} + +struct RegulationData { + RegulationType regulationType; + RegulationSubType regulationSubType; + uint256 dealSize; + AccreditedInvestors accreditedInvestors; + uint256 maxNonAccreditedInvestors; + ManualInvestorVerification manualInvestorVerification; + InternationalInvestors internationalInvestors; + ResaleHoldPeriod resaleHoldPeriod; +} + +error RegulationTypeAndSubTypeForbidden( + RegulationType regulationType, + RegulationSubType regulationSubType +); + +function buildRegulationData( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (RegulationData memory regulationData_) { + regulationData_ = RegulationData({ + regulationType: _regulationType, + regulationSubType: _regulationSubType, + dealSize: buildDealSize(_regulationType, _regulationSubType), + accreditedInvestors: buildAccreditedInvestors( + _regulationType, + _regulationSubType + ), + maxNonAccreditedInvestors: buildMaxNonAccreditedInvestors( + _regulationType, + _regulationSubType + ), + manualInvestorVerification: buildManualInvestorVerification( + _regulationType, + _regulationSubType + ), + internationalInvestors: buildInternationalInvestors( + _regulationType, + _regulationSubType + ), + resaleHoldPeriod: buildResaleHoldPeriod( + _regulationType, + _regulationSubType + ) + }); +} + +function buildDealSize( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (uint256 dealSize_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_DEAL_SIZE; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_DEAL_SIZE; + } + dealSize_ = _REGD_506_C_DEAL_SIZE; +} + +function buildAccreditedInvestors( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (AccreditedInvestors accreditedInvestors_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_ACCREDITED_INVESTORS; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_ACCREDITED_INVESTORS; + } + accreditedInvestors_ = _REGD_506_C_ACCREDITED_INVESTORS; +} + +function buildMaxNonAccreditedInvestors( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (uint256 maxNonAccreditedInvestors_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_MAX_NON_ACCREDITED_INVESTORS; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_MAX_NON_ACCREDITED_INVESTORS; + } + maxNonAccreditedInvestors_ = _REGD_506_C_MAX_NON_ACCREDITED_INVESTORS; +} + +function buildManualInvestorVerification( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (ManualInvestorVerification manualInvestorVerification_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_MANUAL_INVESTOR_VERIFICATION; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_MANUAL_INVESTOR_VERIFICATION; + } + manualInvestorVerification_ = _REGD_506_C_MANUAL_INVESTOR_VERIFICATION; +} + +function buildInternationalInvestors( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (InternationalInvestors internationalInvestors_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_INTERNATIONAL_INVESTORS; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_INTERNATIONAL_INVESTORS; + } + internationalInvestors_ = _REGD_506_C_INTERNATIONAL_INVESTORS; +} + +function buildResaleHoldPeriod( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (ResaleHoldPeriod resaleHoldPeriod_) { + if (_regulationType == RegulationType.REG_S) { + return _REGS_RESALE_HOLD_PERIOD; + } + if (_regulationSubType == RegulationSubType.REG_D_506_B) { + return _REGD_506_B_RESALE_HOLD_PERIOD; + } + resaleHoldPeriod_ = _REGD_506_C_RESALE_HOLD_PERIOD; +} + +function checkRegulationTypeAndSubType( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure { + if (isValidTypeAndSubType(_regulationType, _regulationSubType)) { + return; + } + revert RegulationTypeAndSubTypeForbidden( + _regulationType, + _regulationSubType + ); +} + +function isValidTypeAndSubType( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (bool isValid_) { + isValid_ = + isValidTypeAndSubTypeForRegS(_regulationType, _regulationSubType) || + isValidTypeAndSubTypeForRegD(_regulationType, _regulationSubType); +} + +function isValidTypeAndSubTypeForRegS( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (bool isValid_) { + isValid_ = + _regulationType == RegulationType.REG_S && + _regulationSubType == RegulationSubType.NONE; +} + +function isValidTypeAndSubTypeForRegD( + RegulationType _regulationType, + RegulationSubType _regulationSubType +) pure returns (bool isValid_) { + isValid_ = + _regulationType == RegulationType.REG_D && + _regulationSubType != RegulationSubType.NONE; +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/interfaces/roles.sol b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/roles.sol new file mode 100644 index 000000000..905142068 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/interfaces/roles.sol @@ -0,0 +1,286 @@ +/* + 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.17; +// SPDX-License-Identifier: BSD-3-Clause-Attribution + +// solhint-disable max-line-length + +bytes32 constant _DEFAULT_ADMIN_ROLE = 0x00; + +// keccak256('security.token.standard.role.controlList'); +bytes32 constant _CONTROL_LIST_ROLE = 0xca537e1c88c9f52dc5692c96c482841c3bea25aafc5f3bfe96f645b5f800cac3; + +// keccak256('security.token.standard.role.corporateAction'); +bytes32 constant _CORPORATE_ACTION_ROLE = 0x8a139eeb747b9809192ae3de1b88acfd2568c15241a5c4f85db0443a536d77d6; + +// keccak256('security.token.standard.role.issuer'); +bytes32 constant _ISSUER_ROLE = 0x4be32e8849414d19186807008dabd451c1d87dae5f8e22f32f5ce94d486da842; + +// keccak256('security.token.standard.role.documenter'); +bytes32 constant _DOCUMENTER_ROLE = 0x83ace103a76d3729b4ba1350ad27522bbcda9a1a589d1e5091f443e76abccf41; + +// keccak256('security.token.standard.role.controller'); +bytes32 constant _CONTROLLER_ROLE = 0xa72964c08512ad29f46841ce735cff038789243c2b506a89163cc99f76d06c0f; + +// keccak256('security.token.standard.role.pauser'); +bytes32 constant _PAUSER_ROLE = 0x6f65556918c1422809d0d567462eafeb371be30159d74b38ac958dc58864faeb; + +// keccak256('security.token.standard.role.cap'); +bytes32 constant _CAP_ROLE = 0xb60cac52541732a1020ce6841bc7449e99ed73090af03b50911c75d631476571; + +// keccak256('security.token.standard.role.snapshot'); +bytes32 constant _SNAPSHOT_ROLE = 0x3fbb44760c0954eea3f6cb9f1f210568f5ae959dcbbef66e72f749dbaa7cc2da; + +// keccak256('security.token.standard.role.locker'); +bytes32 constant _LOCKER_ROLE = 0xd8aa8c6f92fe8ac3f3c0f88216e25f7c08b3a6c374b4452a04d200c29786ce88; + +// keccak256('security.token.standard.role.bondManager'); +bytes32 constant _BOND_MANAGER_ROLE = 0x8e99f55d84328dd46dd7790df91f368b44ea448d246199c88b97896b3f83f65d; + +// keccak256('security.token.standard.protected.partitions'); +bytes32 constant _PROTECTED_PARTITIONS_ROLE = 0x8e359333991af626d1f6087d9bc57221ef1207a053860aaa78b7609c2c8f96b6; + +// keccak256('security.token.standard.protected.partitions.participant'); +bytes32 constant _PROTECTED_PARTITIONS_PARTICIPANT_ROLE = 0xdaba153046c65d49da6a7597abc24374aa681e3eee7004426ca6185b3927a3f5; + +// keccak256('security.token.standard.role.wildcard'); +bytes32 constant _WILD_CARD_ROLE = 0x96658f163b67573bbf1e3f9e9330b199b3ac2f6ec0139ea95f622e20a5df2f46; + +// keccak256('security.token.standard.role.ssi.manager'); +bytes32 constant _SSI_MANAGER_ROLE = 0x0995a089e16ba792fdf9ec5a4235cba5445a9fb250d6e96224c586678b81ebd0; + +// keccak256('security.token.standard.role.kyc'); +bytes32 constant _KYC_ROLE = 0x6fbd421e041603fa367357d79ffc3b2f9fd37a6fc4eec661aa5537a9ae75f93d; + +// keccak256('security.token.standard.role.clearing'); +bytes32 constant _CLEARING_ROLE = 0x2292383e7bb988fb281e5195ab88da11e62fec74cf43e8685cff613d6b906450; + +// keccak256('security.token.standard.role.clearing.validator'); +bytes32 constant _CLEARING_VALIDATOR_ROLE = 0x7b688898673e16c47810f5da9ce1262a3d7d022dfe27c8ff9305371cd435c619; + +// keccak256('security.token.standard.role.pause.manager'); +bytes32 constant _PAUSE_MANAGER_ROLE = 0xbc36fbd776e95c4811506a63b650c876b4159cb152d827a5f717968b67c69b84; + +// keccak256('security.token.standard.role.controllist.manager'); +bytes32 constant _CONTROL_LIST_MANAGER_ROLE = 0x0e625647b832ec7d4146c12550c31c065b71e0a698095568fd8320dd2aa72e75; + +// keccak256('security.token.standard.role.kyc.manager'); +bytes32 constant _KYC_MANAGER_ROLE = 0x8ebae577938c1afa7fb3dc7b06459c79c86ffd2ac9805b6da92ee4cbbf080449; + +// keccak256('security.token.standard.role.internal.kyc.manager'); +bytes32 constant _INTERNAL_KYC_MANAGER_ROLE = 0x3916c5c9e68488134c2ee70660332559707c133d0a295a25971da4085441522e; + +// keccak256('security.token.standard.role.freeze.manager'); +bytes32 constant _FREEZE_MANAGER_ROLE = 0xd0e5294c1fc630933e135c5b668c5d577576754d33964d700bbbcdbfd7e1361b; + +// keccak256('security.token.standard.role.agent'); +bytes32 constant _AGENT_ROLE = 0xc4aed0454da9bde6defa5baf93bb49d4690626fc243d138104e12d1def783ea6; + +// keccak256('security.token.standard.role.trex.owner'); +bytes32 constant _TREX_OWNER_ROLE = 0x03ce2fdc316501dd97f5219e6ad908a3238f1e90f910aa17b627f801a6aafab7; + +// keccak256('security.token.standard.role.maturity.redeemer'); +bytes32 constant _MATURITY_REDEEMER_ROLE = 0xa0d696902e9ed231892dc96649f0c62b808a1cb9dd1269e78e0adc1cc4b8358c; diff --git a/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXBondDeploymentLib.sol b/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXBondDeploymentLib.sol new file mode 100644 index 000000000..987d835b3 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXBondDeploymentLib.sol @@ -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. + +*/ + +pragma solidity ^0.8.17; + +// solhint-disable no-global-import +import '@tokenysolutions/t-rex/contracts/factory/TREXFactory.sol'; +import {TRexIFactory, FactoryRegulationData} from '../interfaces/IFactory.sol'; +import '@onchain-id/solidity/contracts/factory/IIdFactory.sol'; +import {TREXFactoryAts} from '../TREXFactory.sol'; +import {SecurityDeploymentLib} from './core/SecurityDeploymentLib.sol'; +import {TREXBaseDeploymentLib} from './core/TREXBaseDeploymentLib.sol'; + +library TREXBondDeploymentLib { + function deployTREXSuiteAtsBond( + mapping(string => address) storage _tokenDeployed, + address _implementationAuthority, + address _idFactory, + address _atsFactory, + string memory _salt, + TREXFactoryAts.TokenDetailsAts calldata _tokenDetails, + ITREXFactory.ClaimDetails calldata _claimDetails, + TRexIFactory.BondData calldata _bondData, + FactoryRegulationData calldata _factoryRegulationData + ) external { + IToken token = SecurityDeploymentLib.deployBond( + _atsFactory, + _tokenDetails.owner, + _bondData, + _factoryRegulationData + ); + TREXBaseDeploymentLib.deployTREXSuite( + _tokenDeployed, + _implementationAuthority, + _idFactory, + _salt, + _tokenDetails, + _claimDetails, + token, + _bondData.security.identityRegistry, + _bondData.security.compliance + ); + } +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXEquityDeploymentLib.sol b/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXEquityDeploymentLib.sol new file mode 100644 index 000000000..ba808d8cc --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/libraries/TREXEquityDeploymentLib.sol @@ -0,0 +1,247 @@ +/* + 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.17; + +// solhint-disable no-global-import +import '@tokenysolutions/t-rex/contracts/factory/TREXFactory.sol'; +import '@openzeppelin/contracts/access/Ownable.sol'; +import {TRexIFactory, FactoryRegulationData} from '../interfaces/IFactory.sol'; +import '@onchain-id/solidity/contracts/factory/IIdFactory.sol'; +import {TREXFactoryAts} from '../TREXFactory.sol'; +import {SecurityDeploymentLib} from './core/SecurityDeploymentLib.sol'; +import {TREXBaseDeploymentLib} from './core/TREXBaseDeploymentLib.sol'; + +library TREXEquityDeploymentLib { + function deployTREXSuiteAtsEquity( + mapping(string => address) storage _tokenDeployed, + address _implementationAuthority, + address _idFactory, + address _atsFactory, + string memory _salt, + TREXFactoryAts.TokenDetailsAts calldata _tokenDetails, + ITREXFactory.ClaimDetails calldata _claimDetails, + TRexIFactory.EquityData calldata _equityData, + FactoryRegulationData calldata _factoryRegulationData + ) external { + IToken token = SecurityDeploymentLib.deployEquity( + _atsFactory, + _tokenDetails.owner, + _equityData, + _factoryRegulationData + ); + TREXBaseDeploymentLib.deployTREXSuite( + _tokenDeployed, + _implementationAuthority, + _idFactory, + _salt, + _tokenDetails, + _claimDetails, + token, + _equityData.security.identityRegistry, + _equityData.security.compliance + ); + } +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/SecurityDeploymentLib.sol b/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/SecurityDeploymentLib.sol new file mode 100644 index 000000000..80ba824a6 --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/SecurityDeploymentLib.sol @@ -0,0 +1,329 @@ +/* + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +// SPDX-License-Identifier: Apache-2.0 +pragma solidity ^0.8.17; + +// solhint-disable no-global-import +import '@tokenysolutions/t-rex/contracts/factory/TREXFactory.sol'; +import { + TRexIFactory, + FactoryRegulationData, + IResolverProxy +} from '../../interfaces/IFactory.sol'; +import { + _TREX_OWNER_ROLE, + _DEFAULT_ADMIN_ROLE +} from '../../interfaces/roles.sol'; + +library SecurityDeploymentLib { + function deployEquity( + address _atsFactory, + address _tRexOwner, + TRexIFactory.EquityData memory _equityData, + FactoryRegulationData memory _factoryRegulationData + ) internal returns (IToken token_) { + _equityData.security.rbacs = _prepareRbacs( + _equityData.security.rbacs, + _tRexOwner + ); + token_ = IToken( + TRexIFactory(_atsFactory).deployEquity( + _equityData, + _factoryRegulationData + ) + ); + } + + function deployBond( + address _atsFactory, + address _tRexOwner, + TRexIFactory.BondData memory _bondData, + FactoryRegulationData memory _factoryRegulationData + ) internal returns (IToken token_) { + _bondData.security.rbacs = _prepareRbacs( + _bondData.security.rbacs, + _tRexOwner + ); + + token_ = IToken( + TRexIFactory(_atsFactory).deployBond( + _bondData, + _factoryRegulationData + ) + ); + } + + /** + * @dev Prepares RBAC array by adding T_REX_OWNER_ROLE to address(this) + * @dev Checks if tRexOwner was already provided in the RBACs, if not, it is added + */ + function _prepareRbacs( + IResolverProxy.Rbac[] memory _rbacs, + address _tRexOwner + ) private view returns (IResolverProxy.Rbac[] memory) { + bool ownerMatch; + uint256 length = _rbacs.length; + + // Check if owner was already assigned the role + for (uint256 i = 0; i < length; ) { + if ( + _rbacs[i].role == _TREX_OWNER_ROLE && + _rbacs[i].members.length > 0 + ) { + for (uint256 j = 0; j < _rbacs[i].members.length; ) { + if (_tRexOwner == _rbacs[i].members[j]) { + ownerMatch = true; + break; + } + unchecked { + ++j; + } + } + } + if (ownerMatch) break; + unchecked { + ++i; + } + } + + // Resize array + IResolverProxy.Rbac[] memory newRbacs = new IResolverProxy.Rbac[]( + length + 2 + ); + + for (uint256 i = 0; i < length; ) { + newRbacs[i] = _rbacs[i]; + unchecked { + ++i; + } + } + + address[] memory membersArr; + if (!ownerMatch) { + membersArr = new address[](2); + membersArr[0] = address(this); + membersArr[1] = _tRexOwner; + } else { + membersArr = new address[](1); + membersArr[0] = address(this); + } + + newRbacs[length] = IResolverProxy.Rbac({ + role: _TREX_OWNER_ROLE, + members: membersArr + }); + + membersArr = new address[](1); + membersArr[0] = address(this); + + newRbacs[length + 1] = IResolverProxy.Rbac({ + role: _DEFAULT_ADMIN_ROLE, + members: membersArr + }); + + return newRbacs; + } +} diff --git a/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/TREXBaseDeploymentLib.sol b/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/TREXBaseDeploymentLib.sol new file mode 100644 index 000000000..a83b4d7dc --- /dev/null +++ b/packages/ats/contracts/contracts/factory/ERC3643/libraries/core/TREXBaseDeploymentLib.sol @@ -0,0 +1,475 @@ +/* + 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.17; + +// solhint-disable no-global-import +import '@tokenysolutions/t-rex/contracts/factory/TREXFactory.sol'; +import {TRexIAccessControl} from '../../interfaces/IAccessControl.sol'; +import '@onchain-id/solidity/contracts/factory/IIdFactory.sol'; +import {TREXFactoryAts} from '../../TREXFactory.sol'; +import { + _TREX_OWNER_ROLE, + _DEFAULT_ADMIN_ROLE +} from '../../interfaces/roles.sol'; + +// solhint-disable custom-errors +library TREXBaseDeploymentLib { + /// @dev Copied from ITREXFactory + event TREXSuiteDeployed( + address indexed _token, + address _ir, + address _irs, + address _tir, + address _ctr, + address _mc, + string indexed _salt + ); + /// @dev Copied from ITREXFactory + event Deployed(address indexed _addr); + + function deployTREXSuite( + mapping(string => address) storage _tokenDeployed, + address _implementationAuthority, + address _idFactory, + string memory _salt, + TREXFactoryAts.TokenDetailsAts memory _tokenDetails, + ITREXFactory.ClaimDetails memory _claimDetails, + IToken _token, + address _identityRegistry, + address _compliance + ) internal { + require(_tokenDeployed[_salt] == address(0), 'token already deployed'); + require( + (_claimDetails.issuers).length == + (_claimDetails.issuerClaims).length, + 'claim pattern not valid' + ); + require( + (_claimDetails.issuers).length <= 5, + 'max 5 claim issuers at deployment' + ); + require( + (_claimDetails.claimTopics).length <= 5, + 'max 5 claim topics at deployment' + ); + require( + (_tokenDetails.irAgents).length <= 5 && + (_tokenDetails.tokenAgents).length <= 5, + 'max 5 agents at deployment' + ); + require( + (_tokenDetails.complianceModules).length <= 30, + 'max 30 module actions at deployment' + ); + require( + (_tokenDetails.complianceModules).length >= + (_tokenDetails.complianceSettings).length, + 'invalid compliance pattern' + ); + + IModularCompliance mc; + uint256 transferOwnership; // Bit 0 tracks MC and bit 1 IR + if (_compliance == address(0)) { + mc = IModularCompliance(_deployMC(_salt, _implementationAuthority)); + _token.setCompliance(address(mc)); + mc.bindToken(address(_token)); + transferOwnership = 1; + } else { + mc = IModularCompliance(_compliance); + } + IIdentityRegistryStorage irs; + ITrustedIssuersRegistry tir; + IClaimTopicsRegistry ctr; + if (_identityRegistry == address(0)) { + tir = ITrustedIssuersRegistry( + _deployTIR(_salt, _implementationAuthority) + ); + ctr = IClaimTopicsRegistry( + _deployCTR(_salt, _implementationAuthority) + ); + if (_tokenDetails.irs == address(0)) { + irs = IIdentityRegistryStorage( + _deployIRS(_salt, _implementationAuthority) + ); + } else { + irs = IIdentityRegistryStorage(_tokenDetails.irs); + } + + _identityRegistry = _deployIR( + _salt, + _implementationAuthority, + address(tir), + address(ctr), + address(irs) + ); + irs.bindIdentityRegistry(_identityRegistry); + _token.setIdentityRegistry(_identityRegistry); + transferOwnership |= 1 << 1; + } else { + tir = ITrustedIssuersRegistry( + IIdentityRegistry(_identityRegistry).issuersRegistry() + ); + ctr = IClaimTopicsRegistry( + IIdentityRegistry(_identityRegistry).topicsRegistry() + ); + irs = IIdentityRegistryStorage( + IIdentityRegistry(_identityRegistry).identityStorage() + ); + } + address _tokenID = _tokenDetails.ONCHAINID; + if (_tokenID == address(0)) { + _tokenID = IIdFactory(_idFactory).createTokenIdentity( + address(_token), + _tokenDetails.owner, + _salt + ); + } + _token.setOnchainID(_tokenID); + for (uint256 i = 0; i < (_claimDetails.claimTopics).length; i++) { + ctr.addClaimTopic(_claimDetails.claimTopics[i]); + } + for (uint256 i = 0; i < (_claimDetails.issuers).length; i++) { + tir.addTrustedIssuer( + IClaimIssuer((_claimDetails).issuers[i]), + _claimDetails.issuerClaims[i] + ); + } + AgentRole(_identityRegistry).addAgent(address(_token)); + for (uint256 i = 0; i < (_tokenDetails.irAgents).length; i++) { + AgentRole(_identityRegistry).addAgent(_tokenDetails.irAgents[i]); + } + for (uint256 i = 0; i < (_tokenDetails.tokenAgents).length; i++) { + AgentRole(address(_token)).addAgent(_tokenDetails.tokenAgents[i]); + } + for (uint256 i = 0; i < (_tokenDetails.complianceModules).length; i++) { + if (!mc.isModuleBound(_tokenDetails.complianceModules[i])) { + mc.addModule(_tokenDetails.complianceModules[i]); + } + if (i < (_tokenDetails.complianceSettings).length) { + mc.callModuleFunction( + _tokenDetails.complianceSettings[i], + _tokenDetails.complianceModules[i] + ); + } + } + _tokenDeployed[_salt] = address(_token); + // Equivalent to transfer ownership of the token to the new owner + TRexIAccessControl(address(_token)).renounceRole(_TREX_OWNER_ROLE); + TRexIAccessControl(address(_token)).renounceRole(_DEFAULT_ADMIN_ROLE); + (Ownable(_identityRegistry)).transferOwnership(_tokenDetails.owner); + (Ownable(address(tir))).transferOwnership(_tokenDetails.owner); + (Ownable(address(ctr))).transferOwnership(_tokenDetails.owner); + (Ownable(address(mc))).transferOwnership(_tokenDetails.owner); + (Ownable(address(irs))).transferOwnership(_tokenDetails.owner); + + emit TREXSuiteDeployed( + address(_token), + _identityRegistry, + address(irs), + address(tir), + address(ctr), + address(mc), + _salt + ); + } + + /** + * + * @notice Deploy function with create2 opcode call + * @notice Returns the address of the contract created + */ + function _deploy( + string memory salt, + bytes memory bytecode + ) private returns (address) { + bytes32 saltBytes = bytes32(keccak256(abi.encodePacked(salt))); + address addr; + // solhint-disable-next-line no-inline-assembly + assembly { + let encoded_data := add(0x20, bytecode) // load initialization code. + let encoded_size := mload(bytecode) // load init code's length. + addr := create2(0, encoded_data, encoded_size, saltBytes) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr); + return addr; + } + + /** + * @dev Function used to deploy a trusted issuers registry using CREATE2 + */ + function _deployTIR( + string memory _salt, + address implementationAuthority_ + ) private returns (address) { + bytes memory _code = type(TrustedIssuersRegistryProxy).creationCode; + bytes memory _constructData = abi.encode(implementationAuthority_); + bytes memory bytecode = abi.encodePacked(_code, _constructData); + return _deploy(_salt, bytecode); + } + + /** + * @dev Function used to deploy a claim topics registry using CREATE2 + */ + function _deployCTR( + string memory _salt, + address implementationAuthority_ + ) private returns (address) { + bytes memory _code = type(ClaimTopicsRegistryProxy).creationCode; + bytes memory _constructData = abi.encode(implementationAuthority_); + bytes memory bytecode = abi.encodePacked(_code, _constructData); + return _deploy(_salt, bytecode); + } + + /** + * @dev Function used to deploy modular compliance contract using CREATE2 + */ + function _deployMC( + string memory _salt, + address implementationAuthority_ + ) private returns (address) { + bytes memory _code = type(ModularComplianceProxy).creationCode; + bytes memory _constructData = abi.encode(implementationAuthority_); + bytes memory bytecode = abi.encodePacked(_code, _constructData); + return _deploy(_salt, bytecode); + } + + /** + * @dev Function used to deploy an identity registry storage using CREATE2 + */ + function _deployIRS( + string memory _salt, + address implementationAuthority_ + ) private returns (address) { + bytes memory _code = type(IdentityRegistryStorageProxy).creationCode; + bytes memory _constructData = abi.encode(implementationAuthority_); + bytes memory bytecode = abi.encodePacked(_code, _constructData); + return _deploy(_salt, bytecode); + } + + /** + * @dev Function used to deploy an identity registry using CREATE2 + */ + function _deployIR( + string memory _salt, + address implementationAuthority_, + address _trustedIssuersRegistry, + address _claimTopicsRegistry, + address _identityStorage + ) private returns (address) { + bytes memory _code = type(IdentityRegistryProxy).creationCode; + bytes memory _constructData = abi.encode( + implementationAuthority_, + _trustedIssuersRegistry, + _claimTopicsRegistry, + _identityStorage + ); + bytes memory bytecode = abi.encodePacked(_code, _constructData); + return _deploy(_salt, bytecode); + } +} diff --git a/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol b/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol index bb981edb6..8cb9d7558 100644 --- a/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol +++ b/packages/ats/contracts/contracts/interfaces/factory/IFactory.sol @@ -208,7 +208,7 @@ pragma solidity 0.8.18; import {IResolverProxy} from '../resolver/resolverProxy/IResolverProxy.sol'; import {IBusinessLogicResolver} from '../resolver/IBusinessLogicResolver.sol'; -import {ERC20} from '../../layer_1/ERC1400/ERC20/ERC20.sol'; +import {IERC20} from '../../layer_1/interfaces/ERC1400/IERC20.sol'; import {IBond} from '../../layer_2/interfaces/bond/IBond.sol'; import {IEquity} from '../../layer_2/interfaces/equity/IEquity.sol'; import { @@ -239,7 +239,7 @@ interface IFactory { bool isControllable; bool isWhiteList; uint256 maxSupply; - ERC20.ERC20MetadataInfo erc20MetadataInfo; + IERC20.ERC20MetadataInfo erc20MetadataInfo; bool clearingActive; bool internalKycActivated; address[] externalPauses; diff --git a/packages/ats/contracts/hardhat.config.ts b/packages/ats/contracts/hardhat.config.ts index 93f2994dd..f924ace8e 100644 --- a/packages/ats/contracts/hardhat.config.ts +++ b/packages/ats/contracts/hardhat.config.ts @@ -212,17 +212,32 @@ import 'hardhat-contract-sizer' import 'hardhat-gas-reporter' import Configuration from '@configuration' import '@tasks' +import 'hardhat-dependency-compiler' const config: HardhatUserConfig = { solidity: { - version: '0.8.18', - settings: { - optimizer: { - enabled: true, - runs: 100, + compilers: [ + { + version: '0.8.17', + settings: { + optimizer: { + enabled: true, + runs: 100, + }, + evmVersion: 'london', + }, }, - evmVersion: 'london', - }, + { + version: '0.8.18', + settings: { + optimizer: { + enabled: true, + runs: 100, + }, + evmVersion: 'london', + }, + }, + ], }, paths: { sources: './contracts', @@ -276,6 +291,24 @@ const config: HardhatUserConfig = { mocha: { timeout: 3_000_000, }, + dependencyCompiler: { + paths: [ + '@tokenysolutions/t-rex/contracts/registry/implementation/ClaimTopicsRegistry.sol', + '@tokenysolutions/t-rex/contracts/registry/implementation/IdentityRegistry.sol', + '@tokenysolutions/t-rex/contracts/registry/implementation/IdentityRegistryStorage.sol', + '@tokenysolutions/t-rex/contracts/registry/implementation/TrustedIssuersRegistry.sol', + '@tokenysolutions/t-rex/contracts/compliance/modular/ModularCompliance.sol', + '@tokenysolutions/t-rex/contracts/proxy/authority/TREXImplementationAuthority.sol', + '@tokenysolutions/t-rex/contracts/proxy/TrustedIssuersRegistryProxy.sol', + '@tokenysolutions/t-rex/contracts/proxy/ClaimTopicsRegistryProxy.sol', + '@tokenysolutions/t-rex/contracts/proxy/IdentityRegistryProxy.sol', + '@tokenysolutions/t-rex/contracts/proxy/IdentityRegistryStorageProxy.sol', + '@tokenysolutions/t-rex/contracts/proxy/ModularComplianceProxy.sol', + '@tokenysolutions/t-rex/contracts/compliance/legacy/DefaultCompliance.sol', + '@onchain-id/solidity/contracts/Identity.sol', + '@onchain-id/solidity/contracts/ClaimIssuer.sol', + ], + }, } export default config diff --git a/packages/ats/contracts/package.json b/packages/ats/contracts/package.json index 827dca592..5f4658dca 100644 --- a/packages/ats/contracts/package.json +++ b/packages/ats/contracts/package.json @@ -45,6 +45,7 @@ "test:demo": "npx hardhat test test/demo/Demo.test.ts", "test:demo:hedera": "npx hardhat test test/demo/Demo.test.Hedera.ts", "test:factory": "npx hardhat test test/unitTests/factory/factory.test.ts", + "test:trexFactory": "npx hardhat test test/unitTests/factory/trex/factory.test.ts", "test:resolver": "npx hardhat test test/unitTests/resolver/BusinessLogicResolver.test.ts", "size": "npx hardhat size-contracts", "keccak256": "npx hardhat keccak256", @@ -62,11 +63,13 @@ "@hashgraph/sdk": "^2.62.0", "@nomicfoundation/hardhat-chai-matchers": "^1.0.6", "@nomicfoundation/hardhat-toolbox": "^2.0.2", + "@onchain-id/solidity": "^2.2.1", "@openzeppelin/contracts": "^4.9.6", "@openzeppelin/contracts-upgradeable": "^4.9.6", "@openzeppelin/hardhat-upgrades": "^1.22.1", "@terminal3/ecdsa_vc": "^0.1.19", "@thomaschaplin/isin-generator": "^1.0.3", + "@tokenysolutions/t-rex": "^4.1.6", "@typechain/ethers-v5": "^10.1.0", "@typechain/hardhat": "^6.1.2", "@types/jest": "^29.5.14", @@ -76,6 +79,7 @@ "hardhat": "^2.22.19", "hardhat-abi-exporter": "^2.11.0", "hardhat-contract-sizer": "^2.10.0", + "hardhat-dependency-compiler": "^1.2.1", "hardhat-gas-reporter": "^1.0.8", "rimraf": "^6.0.1", "solidity-coverage": "^0.8.14", diff --git a/packages/ats/contracts/scripts/commands/DeployContractWithLibraryCommand.ts b/packages/ats/contracts/scripts/commands/DeployContractWithLibraryCommand.ts new file mode 100644 index 000000000..6a4fdbda8 --- /dev/null +++ b/packages/ats/contracts/scripts/commands/DeployContractWithLibraryCommand.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 { Signer } from 'ethers' +import { ContractName, LibraryName } from '@configuration' + +interface DeployContractWithLibraryCommandParams { + name: ContractName + signer: Signer + libraries: LibraryName[] + args?: Array +} + +export default class DeployContractWithLibraryCommand { + public readonly name: ContractName + public readonly signer: Signer + public readonly libraries: LibraryName[] + public readonly args: Array = [] + + constructor({ + name, + signer, + args = [], + libraries, + }: DeployContractWithLibraryCommandParams) { + this.name = name + this.signer = signer + this.args = args + this.libraries = libraries + } +} diff --git a/packages/ats/contracts/scripts/deploy.ts b/packages/ats/contracts/scripts/deploy.ts index a0d404d7a..1187ce5bf 100644 --- a/packages/ats/contracts/scripts/deploy.ts +++ b/packages/ats/contracts/scripts/deploy.ts @@ -319,6 +319,7 @@ import { CreateConfigurationsForDeployedContractsResult, } from '@scripts' import Environment from './Environment' +import DeployContractWithLibraryCommand from './commands/DeployContractWithLibraryCommand' export let environment = Environment.empty() @@ -1436,3 +1437,97 @@ export async function deployContract({ receipt: await receipt, }) } + +/** + * Deploys a smart contract with its required libraries and optionally its proxy and proxy admin. + * + * @param {DeployContractWithLibrariesCommand} params - The deployment parameters. + * @param {ContractName} params.name - The name of the contract to deploy. + * @param {Signer} params.signer - The signer to use for the deployment. + * @param {Array} params.args - The arguments to pass to the contract constructor. + * @param {LibraryName[]} params.libraries - Array of library names to deploy and link. + * @returns {Promise} A promise that resolves to the deployment result. + * + * @example + * const result = await deployContractWithLibraries({ + * name: 'TREXFactoryAts', + * signer: mySigner, + * args: [arg1, arg2, arg3], + * libraries: ['SecurityDeployment'] + * }); + */ +export async function deployContractWithLibraries({ + name, + signer, + args, + libraries, +}: DeployContractWithLibraryCommand): Promise { + console.log(`Deploying ${name} with libraries. please wait...`) + + const libraryAddresses: Record = {} + + for (const libraryName of libraries) { + console.log(`Deploying library ${libraryName}. please wait...`) + + const libraryFactory = await ethers.getContractFactory( + libraryName, + signer + ) + const library = await libraryFactory.deploy() + await library.deployTransaction.wait() + + libraryAddresses[libraryName] = library.address + console.log(`Library ${libraryName} deployed at ${library.address}`) + } + + const contractFactory = await ethers.getContractFactory(name, { + signer, + libraries: libraryAddresses, + }) + const contract = await contractFactory.deploy(...args) + const receipt = contract.deployTransaction.wait() + + console.log(`${name} deployed at ${contract.address}`) + + if (Configuration.contracts[name].deployType !== 'proxy') { + return new DeployContractResult({ + name, + contract, + address: contract.address, + receipt: await receipt, + }) + } + + console.log(`Deploying ${name} Proxy Admin. please wait...`) + + const { address: proxyAdminAddress } = await deployContract( + new DeployContractCommand({ + name: 'ProxyAdmin', + signer, + args: [], + }) + ) + + console.log(`${name} Proxy Admin deployed at ${proxyAdminAddress}`) + + console.log(`Deploying ${name} Proxy. please wait...`) + + const { address: proxyAddress } = await deployContract( + new DeployContractCommand({ + name: 'TransparentUpgradeableProxy', + signer, + args: [contract.address, proxyAdminAddress, '0x'], + }) + ) + + console.log(`${name} Proxy deployed at ${proxyAddress}`) + + return new DeployContractResult({ + name, + address: contract.address, + contract, + proxyAddress, + proxyAdminAddress, + receipt: await receipt, + }) +} diff --git a/packages/ats/contracts/scripts/index.ts b/packages/ats/contracts/scripts/index.ts index 83e2fc02f..57854a770 100644 --- a/packages/ats/contracts/scripts/index.ts +++ b/packages/ats/contracts/scripts/index.ts @@ -217,6 +217,7 @@ export { } from './commands/base/BaseAtsContractListCommand' export { default as ErrorMessageCommand } from './commands/ErrorMessageCommand' export { default as DeployContractCommand } from './commands/DeployContractCommand' +export { default as DeployContractWithLibraryCommand } from './commands/DeployContractWithLibraryCommand' export { default as DeployAtsContractsCommand } from './commands/DeployAtsContractsCommand' export { default as DeployAtsFullInfrastructureCommand } from './commands/DeployAtsFullInfrastructureCommand' export { default as DeployContractWithFactoryCommand } from './commands/DeployContractWithFactoryCommand' diff --git a/packages/ats/contracts/tasks/Arguments.ts b/packages/ats/contracts/tasks/Arguments.ts index 11ac228c9..34b0c8f8c 100644 --- a/packages/ats/contracts/tasks/Arguments.ts +++ b/packages/ats/contracts/tasks/Arguments.ts @@ -240,6 +240,11 @@ export interface DeployAllArgs extends WithSigner { fileName: string } +export interface DeployTrexFactoryArgs extends WithSigner { + atsFactory?: string + resolver?: string +} + // * Transparent Upgradeable Proxy export interface GetProxyAdminConfigArgs { proxyAdmin: string diff --git a/packages/ats/contracts/tasks/compile.ts b/packages/ats/contracts/tasks/compile.ts new file mode 100644 index 000000000..8d70c826a --- /dev/null +++ b/packages/ats/contracts/tasks/compile.ts @@ -0,0 +1,209 @@ +import { TASK_COMPILE } from 'hardhat/builtin-tasks/task-names' +import { task } from 'hardhat/config' +import fs from 'fs' +import { sync as globSync } from 'glob' +import { Artifact } from 'hardhat/types' +import path from 'path' +import { exec } from 'child_process' + +task( + TASK_COMPILE, + "Replace 'interface' with 'interfaces' in TypeChain generated files to avoid compilation errors", + async function (taskArguments, hre, runSuper) { + await runSuper(taskArguments) + + await hre.run('erc3643-clone-interfaces') + const PATTERN = `${hre.config.typechain.outDir}/**/*.ts` + patchTypeChainFiles(PATTERN) + } +) + +function patchTypeChainFiles(pattern: string) { + const files = globSync(pattern, { nodir: true }) + files.forEach((file) => { + let text = fs.readFileSync(file, 'utf8') + const orig = text + text = text.replace( + /\b(import\s+type\s+\*\s+as\s+)interface(\s+from\s+['"]\.\/interface['"])/g, + '$1interfaces$2' + ) + text = text.replace( + /\b(export\s+type\s+\{\s*)interface(\s*\})/g, + '$1interfaces$2' + ) + text = text.replace( + /\b(export\s+\*\s+as\s+)interface(\s+from\s+['"]\.\/interface['"])/g, + '$1interfaces$2' + ) + if (text !== orig) { + fs.writeFileSync(file, text, 'utf8') + console.log(`Patched ${file}`) + } + }) +} + +task('erc3643-clone-interfaces', async (_, hre) => { + interface DataSustitution { + original: string + removeImports?: boolean + changePragma?: boolean + removeHierarchy?: boolean + } + const targetDir = hre.config.paths.sources + '/factory/ERC3643/interfaces' + const interfacesToClone: DataSustitution[] = [ + { original: 'IAccessControl' }, + { original: 'IBond' }, + { + original: 'IBusinessLogicResolver', + }, + { + original: 'IDiamondCutManager', + removeImports: false, + }, + { + original: 'IDiamondLoupe', + }, + { original: 'IEquity' }, + { original: 'IFactory', removeImports: false }, + { original: 'IResolverProxy' }, + { original: 'IStaticFunctionSelectors' }, + { + original: 'contracts/layer_1/interfaces/ERC1400/IERC20.sol:IERC20', + removeImports: false, + }, + ] + + const normalized = interfacesToClone.map((i) => ({ + original: i.original, + removeImports: i.removeImports ?? true, + changePragma: i.changePragma ?? true, + removeHierarchy: i.removeHierarchy ?? true, + })) + + const constants = [ + { src: 'layer_3/constants/regulation', dst: 'regulation' }, + { src: 'layer_1/constants/roles', dst: 'roles' }, + ] + + function rewriteImports(source: string): string { + // 1. Eliminar cualquier import a ficheros *StorageWrapper.sol + source = source.replace( + /^\s*import\s+[^;]*StorageWrapper\.sol['"];\s*$/gm, + '' + ) + + // 2. Reescribir el resto de imports + return source.replace( + /import\s*\{([^}]+)\}\s*from\s*['"](.+\/)?([^/]+)\.sol['"];/gm, + (_match, names, _path, filePath) => { + const fileNoExt = filePath.replace(/\.sol$/, '') + + const rewritten = names + .split(',') + .map((n: string) => n.trim()) + .filter((n: string) => n.length > 0) + .map((n: string) => { + const isConstant = constants.some((c) => + filePath.includes(c.src.split('/').pop() || c) + ) + return isConstant ? n : `TRex${n} as ${n}` + }) + .join(', ') + + return `import {${rewritten}} from './${fileNoExt}.sol';` + } + ) + } + + await Promise.all( + normalized.map(async (i) => { + const originalArtifact = await hre.artifacts.readArtifact( + i.original + ) + let erc3643Artifact: Artifact | undefined + try { + const parts = i.original.split(':') + erc3643Artifact = await hre.artifacts.readArtifact( + 'TRex' + parts[parts.length - 1] + ) + } catch { + console.log( + `Contract ${i.original} in ERC3643/interfaces not found, will be generated` + ) + } + + const shouldGenerate = + !erc3643Artifact || + JSON.stringify(originalArtifact.abi) !== + JSON.stringify(erc3643Artifact.abi) + + if (!shouldGenerate) { + console.log( + `Did not generate ${i.original} because an up-to-date version already exists` + ) + return + } + + let source = fs.readFileSync(originalArtifact.sourceName, 'utf8') + + if (i.removeImports) { + source = source.replace(/^\s*import\s+[^;]+;\s*$/gm, '') + } else { + source = rewriteImports(source) + } + + if (i.changePragma) { + source = source.replace( + /^pragma solidity\s+[^;]+;/m, + 'pragma solidity ^0.8.17;' + ) + } + + // Renombrar interface/contract y eliminar herencia en un solo paso + source = source.replace( + new RegExp( + `(contract|interface)\\s+${originalArtifact.contractName}\\b(\\s+is[^\\{]+)?`, + 'm' + ), + `$1 TRex${originalArtifact.contractName}` + ) + + const targetPath = `${targetDir}/${originalArtifact.contractName}.sol` + fs.writeFileSync(targetPath, source, 'utf8') + console.log(`Generated: ${targetPath}`) + }) + ) + + for (const c of constants) { + const src = path.join(hre.config.paths.sources, `${c.src}.sol`) + const dst = path.join(targetDir, `${c.dst}.sol`) + + if (fs.existsSync(src)) { + let content = fs.readFileSync(src, 'utf8') + + content = content.replace( + /^pragma solidity\s+[^;]+;/m, + 'pragma solidity ^0.8.17;' + ) + + fs.writeFileSync(dst, content, 'utf8') + console.log(`Copied constant with updated pragma: ${dst}`) + } else { + console.warn(`Not found: ${src}`) + } + } + await new Promise((resolve, reject) => { + exec( + 'npx prettier --write ./contracts/factory/ERC3643/interfaces', + (error, stdout, stderr) => { + if (error) { + console.error(`Error ejecutando prettier: ${error.message}`) + return reject(error) + } + if (stderr) console.error(stderr) + // console.log(stdout) + resolve() + } + ) + }) +}) diff --git a/packages/ats/contracts/tasks/deploy.ts b/packages/ats/contracts/tasks/deploy.ts index b673c4b50..c53e393a8 100644 --- a/packages/ats/contracts/tasks/deploy.ts +++ b/packages/ats/contracts/tasks/deploy.ts @@ -205,7 +205,12 @@ import { task, types } from 'hardhat/config' import { CONTRACT_NAMES, ContractName, Network } from '@configuration' -import { DeployAllArgs, DeployArgs, GetSignerResult } from './Arguments' +import { + DeployAllArgs, + DeployArgs, + DeployTrexFactoryArgs, + GetSignerResult, +} from './Arguments' import * as fs from 'fs' task( @@ -474,3 +479,55 @@ task('deploy', 'Deploy new contract') `Implementation: ${address} (${contractId}) for ${contractName}` ) }) + +task('deployTrexFactory', 'Deploys ATS adapted TREX factory') + .addOptionalParam( + 'atsFactory', + 'Address of the ATS factory', + undefined, + types.string + ) + .addOptionalParam( + 'privateKey', + 'The private key of the account in raw hexadecimal format', + undefined, + types.string + ) + .addOptionalParam( + 'signerAddress', + 'The address of the signer to select from the Hardhat signers array', + undefined, + types.string + ) + .addOptionalParam( + 'signerPosition', + 'The index of the signer in the Hardhat signers array', + undefined, + types.int + ) + .setAction(async (args: DeployTrexFactoryArgs, hre) => { + const { + deployContractWithLibraries, + DeployContractWithLibraryCommand, + ADDRESS_ZERO, + } = await import('@scripts') + + const { signer }: GetSignerResult = await hre.run('getSigner', { + privateKey: args.privateKey, + signerAddress: args.signerAddress, + signerPosition: args.signerPosition, + }) + + await deployContractWithLibraries( + new DeployContractWithLibraryCommand({ + name: `TREXFactoryAts`, + signer, + args: [ + ADDRESS_ZERO, // implementationAuthority + ADDRESS_ZERO, // idFactory + args.atsFactory ?? ADDRESS_ZERO, + ], + libraries: ['TREXBondDeploymentLib', 'TREXEquityDeploymentLib'], + }) + ) + }) diff --git a/packages/ats/contracts/tasks/index.ts b/packages/ats/contracts/tasks/index.ts index f390bfb2c..bbd19cdec 100644 --- a/packages/ats/contracts/tasks/index.ts +++ b/packages/ats/contracts/tasks/index.ts @@ -218,3 +218,5 @@ export * from './transparentUpgradeableProxy' // * Business Logic Resolver export * from './businessLogicResolver' + +export * from './compile' diff --git a/packages/ats/contracts/test/unitTests/factory/trex/factory.test.ts b/packages/ats/contracts/test/unitTests/factory/trex/factory.test.ts new file mode 100644 index 000000000..125374ab9 --- /dev/null +++ b/packages/ats/contracts/test/unitTests/factory/trex/factory.test.ts @@ -0,0 +1,1980 @@ +/* + 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 { expect } from 'chai' +import { ethers } from 'hardhat' +import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers' +import { isinGenerator } from '@thomaschaplin/isin-generator' +import { + BusinessLogicResolver, + TREXFactoryAts, + ITREXFactory, + ERC3643, + AccessControl, + ERC20, + Factory, +} from '@typechain' +import { + ADDRESS_ZERO, + deployAtsFullInfrastructure, + DeployAtsFullInfrastructureCommand, + Rbac, + setEquityData, + setBondData, + DividendType, + setFactoryRegulationData, + RegulationType, + RegulationSubType, + DEFAULT_ADMIN_ROLE, + deployContractWithLibraries, + DeployContractWithLibraryCommand, + TREX_OWNER_ROLE, + dateToUnixTimestamp, +} from '@scripts' +import { deployFullSuiteFixture } from './fixtures/deploy-full-suite.fixture' +import { loadFixture } from '@nomicfoundation/hardhat-network-helpers' + +describe('TREX Factory Tests', () => { + let deployer: SignerWithAddress + + const init_rbacs: Rbac[] = [] + + const name = 'ATS-TREX-Token' + const symbol = 'ATS-TREX' + const decimals = 6 + const isin = isinGenerator() + const isWhitelist = false + const isControllable = true + const isMultiPartition = false + const arePartitionsProtected = false + const clearingActive = true + const internalKycActivated = false + + const votingRight = true + const informationRight = false + const liquidationRight = true + const subscriptionRight = false + const conversionRight = true + const redemptionRight = false + const putRight = true + const dividendRight = DividendType.PREFERRED + const numberOfShares = BigInt(2000) + + const currency = '0x455552' + const numberOfUnits = BigInt(1000) + const nominalValue = 100 + const startingDate = dateToUnixTimestamp(`2030-01-01T00:00:00Z`) + const maturityDate = dateToUnixTimestamp(`2031-01-01T00:00:00Z`) + const couponFrequency = 0 + const couponRate = 0 + const firstCouponDate = 0 + + const regulationType = RegulationType.REG_D + const regulationSubType = RegulationSubType.REG_D_506_B + const countriesControlListType = true + const listOfCountries = 'ES,FR,CH' + const info = 'info' + + let businessLogicResolver: BusinessLogicResolver + let factoryAts: TREXFactoryAts + const tokenDetails: ITREXFactory.TokenDetailsStruct = + {} as ITREXFactory.TokenDetailsStruct + const claimDetails: ITREXFactory.ClaimDetailsStruct = + {} as ITREXFactory.ClaimDetailsStruct + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let trexDeployment: any + + let erc3643Facet: ERC3643 + let accessControlFacet: AccessControl + let erc20Facet: ERC20 + let factory: Factory + + async function setFacets(diamond: string) { + erc3643Facet = await ethers.getContractAt('ERC3643', diamond) + + accessControlFacet = await ethers.getContractAt( + 'AccessControl', + diamond + ) + + erc20Facet = await ethers.getContractAt('ERC20', diamond) + } + + before(async () => { + // mute | mock console.log + console.log = () => {} + + deployer = (await ethers.getSigners())[0] + + const { ...deployedContracts } = await deployAtsFullInfrastructure( + await DeployAtsFullInfrastructureCommand.newInstance({ + signer: deployer, + useDeployed: false, + useEnvironment: false, + timeTravelEnabled: true, + }) + ) + + businessLogicResolver = deployedContracts.businessLogicResolver.contract + factory = await ethers.getContractAt( + 'Factory', + deployedContracts.factory.address + ) + }) + + beforeEach(async () => { + trexDeployment = await loadFixture(deployFullSuiteFixture) + + factoryAts = ( + await deployContractWithLibraries( + new DeployContractWithLibraryCommand({ + name: `TREXFactoryAts`, + signer: deployer, + args: [ + trexDeployment.authorities.trexImplementationAuthority + .address, + trexDeployment.factories.identityFactory.address, + factory.address, + ], + libraries: [ + 'TREXBondDeploymentLib', + 'TREXEquityDeploymentLib', + ], + }) + ) + ).contract as TREXFactoryAts + + await trexDeployment.factories.identityFactory + .connect(deployer) + .addTokenFactory(factoryAts.address) + + tokenDetails.name = name + tokenDetails.symbol = symbol + tokenDetails.decimals = decimals + tokenDetails.ONCHAINID = ADDRESS_ZERO + tokenDetails.owner = deployer.address + tokenDetails.irAgents = [deployer.address] + tokenDetails.irs = ADDRESS_ZERO + tokenDetails.tokenAgents = [deployer.address] + tokenDetails.complianceModules = [] + tokenDetails.complianceSettings = [] + + claimDetails.claimTopics = [] + claimDetails.issuerClaims = [] + claimDetails.issuers = [] + }) + + describe('Equity tests', () => { + it('GIVEN a consumed salt WHEN reusing it THEN transaction reverts with token already deployed', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + await factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('token already deployed') + }) + + it('GIVEN an invalid claim pattern THEN transaction reverts with claim pattern not valid', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.issuers = [await ethers.Wallet.createRandom().address] + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('claim pattern not valid') + }) + + it('GIVEN max claim issuers exceeded THEN transaction reverts with max 5 claim issuers at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.issuers = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + claimDetails.issuerClaims = Array.from({ length: 6 }, () => [ + Math.floor(Math.random() * 10), + ]) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 5 claim issuers at deployment') + }) + + it('GIVEN max claim topics exceeded THEN transaction reverts with max 5 claim topics at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.claimTopics = Array.from({ length: 6 }, () => + Math.floor(Math.random() * 10) + ) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 5 claim topics at deployment') + }) + + it('GIVEN max ir agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.irAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max token agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.tokenAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max token agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.tokenAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max modules actions exceeded THEN transaction reverts with max 30 module actions at deployment', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.complianceModules = Array.from( + { length: 31 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('max 30 module actions at deployment') + }) + + it('GIVEN an invalid compliance pattern exceeded THEN transaction reverts with invalid compliance pattern', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.complianceSettings = [ + ethers.Wallet.createRandom().address, + ] + + await expect( + factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + ).to.revertedWith('invalid compliance pattern') + }) + + it('GIVEN an equity with custom values THEN security is deployed successfully', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + const tx = await factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + + const receipt = await tx.wait() + const event = receipt.events?.find( + (e) => e.event === 'TREXSuiteDeployed' + ) + + expect(event).to.exist + const [_token, _ir, _irs, _tir, _ctr, _mc, _salt] = event!.args! + + await setFacets(_token) + + expect(await erc20Facet.name()).to.equal(name) + expect(await erc20Facet.symbol()).to.equal(symbol) + expect(await erc20Facet.decimals()).to.equal(decimals) + + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + tokenDetails.owner + ) + ).to.be.true + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + factoryAts.address + ) + ).to.be.false + expect( + await accessControlFacet.hasRole( + DEFAULT_ADMIN_ROLE, + factoryAts.address + ) + ).to.be.false + + expect(_token).to.equal( + await factoryAts.tokenDeployed('salt-equity') + ) + expect(_salt.hash).to.equal( + ethers.utils.keccak256(ethers.utils.toUtf8Bytes('salt-equity')) + ) + + expect(ethers.utils.isAddress(_ir)).to.be.true + expect(_ir).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_irs)).to.be.true + expect(_irs).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_tir)).to.be.true + expect(_tir).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_ctr)).to.be.true + expect(_ctr).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_mc)).to.be.true + expect(_mc).to.not.equal(ADDRESS_ZERO) + + expect(await erc3643Facet.onchainID()).to.not.equal(ADDRESS_ZERO) + expect(await erc3643Facet.identityRegistry()).to.equal(_ir) + expect(await erc3643Facet.compliance()).to.equal(_mc) + for (const agent of tokenDetails.tokenAgents) { + expect(await erc3643Facet.isAgent(agent)).to.be.true + } + + const irContract = await ethers.getContractAt( + 'IdentityRegistry', + _ir + ) + expect(await irContract.owner()).to.equal(tokenDetails.owner) + for (const agent of tokenDetails.irAgents) { + expect(await irContract.isAgent(agent)).to.be.true + } + + const complianceContract = await ethers.getContractAt( + 'ModularCompliance', + _mc + ) + expect(await complianceContract.owner()).to.equal( + tokenDetails.owner + ) + expect(await complianceContract.getModules()).to.deep.equal( + tokenDetails.complianceModules + ) + expect(await complianceContract.getTokenBound()).to.deep.equal( + _token + ) + + const tirContract = await ethers.getContractAt( + 'TrustedIssuersRegistry', + _tir + ) + expect(await tirContract.owner()).to.equal(tokenDetails.owner) + expect(await tirContract.getTrustedIssuers()).to.deep.equal( + claimDetails.issuers + ) + + const ctrContract = await ethers.getContractAt( + 'ClaimTopicsRegistry', + _ctr + ) + expect(await ctrContract.owner()).to.equal(tokenDetails.owner) + expect(await ctrContract.getClaimTopics()).to.deep.equal( + claimDetails.claimTopics + ) + }) + + it('GIVEN an equity with IR and MC THEN security is deployed successfully', async () => { + const equityData = await setEquityData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + votingRight, + informationRight, + liquidationRight, + subscriptionRight, + conversionRight, + redemptionRight, + putRight, + dividendRight, + currency, + numberOfShares, + nominalValue, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + compliance: trexDeployment.suite.defaultCompliance.address, + identityRegistry: trexDeployment.suite.identityRegistry.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + regulationType, + regulationSubType, + countriesControlListType, + listOfCountries, + info + ) + + // Transfer ownership before deploying + await trexDeployment.suite.defaultCompliance.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.identityRegistry.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.identityRegistryStorage.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.claimTopicsRegistry.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.trustedIssuersRegistry.transferOwnership( + factoryAts.address + ) + + const tirContract = await ethers.getContractAt( + 'TrustedIssuersRegistry', + trexDeployment.suite.trustedIssuersRegistry.address + ) + const trustedIssuers = await tirContract.getTrustedIssuers() + const ctrContract = await ethers.getContractAt( + 'ClaimTopicsRegistry', + trexDeployment.suite.claimTopicsRegistry.address + ) + const claimTopics = await ctrContract.getClaimTopics() + + const tx = await factoryAts + .connect(deployer) + .deployTREXSuiteAtsEquity( + 'salt-equity', + tokenDetails, + claimDetails, + equityData, + factoryRegulationData + ) + + const receipt = await tx.wait() + const event = receipt.events?.find( + (e) => e.event === 'TREXSuiteDeployed' + ) + + expect(event).to.exist + const [_token, _ir, _irs, _tir, _ctr, _mc, _salt] = event!.args! + + await setFacets(_token) + + expect(await erc20Facet.name()).to.equal(name) + expect(await erc20Facet.symbol()).to.equal(symbol) + expect(await erc20Facet.decimals()).to.equal(decimals) + expect(await erc3643Facet.identityRegistry()).to.equal( + trexDeployment.suite.identityRegistry.address + ) + expect(await erc3643Facet.compliance()).to.equal( + trexDeployment.suite.defaultCompliance.address + ) + + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + tokenDetails.owner + ) + ).to.be.true + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + factoryAts.address + ) + ).to.be.false + expect( + await accessControlFacet.hasRole( + DEFAULT_ADMIN_ROLE, + factoryAts.address + ) + ).to.be.false + + expect(_token).to.equal( + await factoryAts.tokenDeployed('salt-equity') + ) + expect(_salt.hash).to.equal( + ethers.utils.keccak256(ethers.utils.toUtf8Bytes('salt-equity')) + ) + + expect(ethers.utils.isAddress(_ir)).to.be.true + expect(_ir).to.equal(trexDeployment.suite.identityRegistry.address) + expect(ethers.utils.isAddress(_irs)).to.be.true + expect(_irs).to.equal( + trexDeployment.suite.identityRegistryStorage.address + ) + expect(ethers.utils.isAddress(_tir)).to.be.true + expect(_tir).to.equal( + trexDeployment.suite.trustedIssuersRegistry.address + ) + expect(ethers.utils.isAddress(_ctr)).to.be.true + expect(_ctr).to.equal( + trexDeployment.suite.claimTopicsRegistry.address + ) + expect(ethers.utils.isAddress(_mc)).to.be.true + expect(_mc).to.equal(trexDeployment.suite.defaultCompliance.address) + + expect(await erc3643Facet.onchainID()).to.not.equal(ADDRESS_ZERO) + expect(await erc3643Facet.identityRegistry()).to.equal(_ir) + expect(await erc3643Facet.compliance()).to.equal(_mc) + for (const agent of tokenDetails.tokenAgents) { + expect(await erc3643Facet.isAgent(agent)).to.be.true + } + + const irContract = await ethers.getContractAt( + 'IdentityRegistry', + _ir + ) + expect(await irContract.owner()).to.equal(tokenDetails.owner) + for (const agent of tokenDetails.irAgents) { + expect(await irContract.isAgent(agent)).to.be.true + } + + const complianceContract = await ethers.getContractAt( + 'ModularCompliance', + _mc + ) + expect(await complianceContract.owner()).to.equal( + tokenDetails.owner + ) + // // Default compliance does not include getModules and getTokenBound + // expect(await complianceContract.getModules()).to.deep.equal( + // tokenDetails.complianceModules + // ) + // expect(await complianceContract.getTokenBound()).to.deep.equal( + // _token + // ) + + expect(await tirContract.owner()).to.equal(tokenDetails.owner) + expect(await tirContract.getTrustedIssuers()).to.deep.equal([ + ...trustedIssuers, + ...claimDetails.issuers, + ]) + + expect(await ctrContract.owner()).to.equal(tokenDetails.owner) + expect(await ctrContract.getClaimTopics()).to.deep.equal([ + ...claimTopics, + ...claimDetails.claimTopics, + ]) + + const irsContract = await ethers.getContractAt( + 'IdentityRegistryStorage', + _irs + ) + expect(await irsContract.owner()).to.equal(tokenDetails.owner) + }) + }) + + describe('Bond tests', () => { + it('GIVEN a consumed salt WHEN reusing it THEN transaction reverts with token already deployed', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + await factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('token already deployed') + }) + + it('GIVEN an invalid claim pattern THEN transaction reverts with claim pattern not valid', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.issuers = [await ethers.Wallet.createRandom().address] + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('claim pattern not valid') + }) + + it('GIVEN max claim issuers exceeded THEN transaction reverts with max 5 claim issuers at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.issuers = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + claimDetails.issuerClaims = Array.from({ length: 6 }, () => [ + Math.floor(Math.random() * 10), + ]) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 5 claim issuers at deployment') + }) + + it('GIVEN max claim topics exceeded THEN transaction reverts with max 5 claim topics at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + claimDetails.claimTopics = Array.from({ length: 6 }, () => + Math.floor(Math.random() * 10) + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 5 claim topics at deployment') + }) + + it('GIVEN max ir agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.irAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max token agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.tokenAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max token agents exceeded THEN transaction reverts with max 5 agents at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.tokenAgents = Array.from( + { length: 6 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 5 agents at deployment') + }) + + it('GIVEN max modules actions exceeded THEN transaction reverts with max 30 module actions at deployment', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.complianceModules = Array.from( + { length: 31 }, + () => ethers.Wallet.createRandom().address + ) + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('max 30 module actions at deployment') + }) + + it('GIVEN an invalid compliance pattern exceeded THEN transaction reverts with invalid compliance pattern', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + tokenDetails.complianceSettings = [ + ethers.Wallet.createRandom().address, + ] + + await expect( + factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + ).to.revertedWith('invalid compliance pattern') + }) + + it('GIVEN a bond without IR and MC THEN security is deployed successfully', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + const tx = await factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + + const receipt = await tx.wait() + const event = receipt.events?.find( + (e) => e.event === 'TREXSuiteDeployed' + ) + + expect(event).to.exist + const [_token, _ir, _irs, _tir, _ctr, _mc, _salt] = event!.args! + + await setFacets(_token) + + expect(await erc20Facet.name()).to.equal(name) + expect(await erc20Facet.symbol()).to.equal(symbol) + expect(await erc20Facet.decimals()).to.equal(decimals) + + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + tokenDetails.owner + ) + ).to.be.true + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + factoryAts.address + ) + ).to.be.false + expect( + await accessControlFacet.hasRole( + DEFAULT_ADMIN_ROLE, + factoryAts.address + ) + ).to.be.false + + expect(_token).to.equal(await factoryAts.tokenDeployed('salt-bond')) + expect(_salt.hash).to.equal( + ethers.utils.keccak256(ethers.utils.toUtf8Bytes('salt-bond')) + ) + + expect(ethers.utils.isAddress(_ir)).to.be.true + expect(_ir).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_irs)).to.be.true + expect(_irs).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_tir)).to.be.true + expect(_tir).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_ctr)).to.be.true + expect(_ctr).to.not.equal(ADDRESS_ZERO) + expect(ethers.utils.isAddress(_mc)).to.be.true + expect(_mc).to.not.equal(ADDRESS_ZERO) + + expect(await erc3643Facet.onchainID()).to.not.equal(ADDRESS_ZERO) + expect(await erc3643Facet.identityRegistry()).to.equal(_ir) + expect(await erc3643Facet.compliance()).to.equal(_mc) + for (const agent of tokenDetails.tokenAgents) { + expect(await erc3643Facet.isAgent(agent)).to.be.true + } + + const irContract = await ethers.getContractAt( + 'IdentityRegistry', + _ir + ) + expect(await irContract.owner()).to.equal(tokenDetails.owner) + for (const agent of tokenDetails.irAgents) { + expect(await irContract.isAgent(agent)).to.be.true + } + + const complianceContract = await ethers.getContractAt( + 'ModularCompliance', + _mc + ) + expect(await complianceContract.owner()).to.equal( + tokenDetails.owner + ) + expect(await complianceContract.getModules()).to.deep.equal( + tokenDetails.complianceModules + ) + expect(await complianceContract.getTokenBound()).to.deep.equal( + _token + ) + + const tirContract = await ethers.getContractAt( + 'TrustedIssuersRegistry', + _tir + ) + expect(await tirContract.owner()).to.equal(tokenDetails.owner) + expect(await tirContract.getTrustedIssuers()).to.deep.equal( + claimDetails.issuers + ) + + const ctrContract = await ethers.getContractAt( + 'ClaimTopicsRegistry', + _ctr + ) + expect(await ctrContract.owner()).to.equal(tokenDetails.owner) + expect(await ctrContract.getClaimTopics()).to.deep.equal( + claimDetails.claimTopics + ) + }) + + it('GIVEN a bond with IR and MC THEN security is deployed successfully', async () => { + const bondData = await setBondData({ + adminAccount: deployer.address, + isWhiteList: isWhitelist, + isControllable, + arePartitionsProtected, + clearingActive, + internalKycActivated, + isMultiPartition, + name, + symbol, + decimals, + isin, + currency, + numberOfUnits, + nominalValue, + startingDate, + maturityDate, + couponFrequency, + couponRate, + firstCouponDate, + init_rbacs, + addAdmin: true, + businessLogicResolver: businessLogicResolver.address, + compliance: trexDeployment.suite.defaultCompliance.address, + identityRegistry: trexDeployment.suite.identityRegistry.address, + }) + + const factoryRegulationData = await setFactoryRegulationData( + RegulationType.REG_S, + RegulationSubType.NONE, + countriesControlListType, + listOfCountries, + info + ) + + // Transfer ownership before deploying + await trexDeployment.suite.defaultCompliance.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.identityRegistry.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.identityRegistryStorage.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.claimTopicsRegistry.transferOwnership( + factoryAts.address + ) + await trexDeployment.suite.trustedIssuersRegistry.transferOwnership( + factoryAts.address + ) + + const tirContract = await ethers.getContractAt( + 'TrustedIssuersRegistry', + trexDeployment.suite.trustedIssuersRegistry.address + ) + const trustedIssuers = await tirContract.getTrustedIssuers() + const ctrContract = await ethers.getContractAt( + 'ClaimTopicsRegistry', + trexDeployment.suite.claimTopicsRegistry.address + ) + const claimTopics = await ctrContract.getClaimTopics() + + const tx = await factoryAts.deployTREXSuiteAtsBond( + 'salt-bond', + tokenDetails, + claimDetails, + bondData, + factoryRegulationData + ) + + const receipt = await tx.wait() + const event = receipt.events?.find( + (e) => e.event === 'TREXSuiteDeployed' + ) + + expect(event).to.exist + const [_token, _ir, _irs, _tir, _ctr, _mc, _salt] = event!.args! + + await setFacets(_token) + + expect(await erc20Facet.name()).to.equal(name) + expect(await erc20Facet.symbol()).to.equal(symbol) + expect(await erc20Facet.decimals()).to.equal(decimals) + expect(await erc3643Facet.identityRegistry()).to.equal( + trexDeployment.suite.identityRegistry.address + ) + expect(await erc3643Facet.compliance()).to.equal( + trexDeployment.suite.defaultCompliance.address + ) + + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + tokenDetails.owner + ) + ).to.be.true + expect( + await accessControlFacet.hasRole( + TREX_OWNER_ROLE, + factoryAts.address + ) + ).to.be.false + expect( + await accessControlFacet.hasRole( + DEFAULT_ADMIN_ROLE, + factoryAts.address + ) + ).to.be.false + + expect(_token).to.equal(await factoryAts.tokenDeployed('salt-bond')) + expect(_salt.hash).to.equal( + ethers.utils.keccak256(ethers.utils.toUtf8Bytes('salt-bond')) + ) + + expect(ethers.utils.isAddress(_ir)).to.be.true + expect(_ir).to.equal(trexDeployment.suite.identityRegistry.address) + expect(ethers.utils.isAddress(_irs)).to.be.true + expect(_irs).to.equal( + trexDeployment.suite.identityRegistryStorage.address + ) + expect(ethers.utils.isAddress(_tir)).to.be.true + expect(_tir).to.equal( + trexDeployment.suite.trustedIssuersRegistry.address + ) + expect(ethers.utils.isAddress(_ctr)).to.be.true + expect(_ctr).to.equal( + trexDeployment.suite.claimTopicsRegistry.address + ) + expect(ethers.utils.isAddress(_mc)).to.be.true + expect(_mc).to.equal(trexDeployment.suite.defaultCompliance.address) + + expect(await erc3643Facet.onchainID()).to.not.equal(ADDRESS_ZERO) + expect(await erc3643Facet.identityRegistry()).to.equal(_ir) + expect(await erc3643Facet.compliance()).to.equal(_mc) + for (const agent of tokenDetails.tokenAgents) { + expect(await erc3643Facet.isAgent(agent)).to.be.true + } + + const irContract = await ethers.getContractAt( + 'IdentityRegistry', + _ir + ) + expect(await irContract.owner()).to.equal(tokenDetails.owner) + for (const agent of tokenDetails.irAgents) { + expect(await irContract.isAgent(agent)).to.be.true + } + + const complianceContract = await ethers.getContractAt( + 'ModularCompliance', + _mc + ) + expect(await complianceContract.owner()).to.equal( + tokenDetails.owner + ) + // // Default compliance does not include getModules and getTokenBound + // expect(await complianceContract.getModules()).to.deep.equal( + // tokenDetails.complianceModules + // ) + // expect(await complianceContract.getTokenBound()).to.deep.equal( + // _token + // ) + + expect(await tirContract.owner()).to.equal(tokenDetails.owner) + expect(await tirContract.getTrustedIssuers()).to.deep.equal([ + ...trustedIssuers, + ...claimDetails.issuers, + ]) + + expect(await ctrContract.owner()).to.equal(tokenDetails.owner) + expect(await ctrContract.getClaimTopics()).to.deep.equal([ + ...claimTopics, + ...claimDetails.claimTopics, + ]) + + const irsContract = await ethers.getContractAt( + 'IdentityRegistryStorage', + _irs + ) + expect(await irsContract.owner()).to.equal(tokenDetails.owner) + }) + }) +}) diff --git a/packages/ats/contracts/test/unitTests/factory/trex/fixtures/deploy-full-suite.fixture.ts b/packages/ats/contracts/test/unitTests/factory/trex/fixtures/deploy-full-suite.fixture.ts new file mode 100644 index 000000000..60a25963a --- /dev/null +++ b/packages/ats/contracts/test/unitTests/factory/trex/fixtures/deploy-full-suite.fixture.ts @@ -0,0 +1,367 @@ +import { Contract, Signer } from 'ethers' +import { ethers } from 'hardhat' +import OnchainID from '@onchain-id/solidity' +import { loadFixture } from '@nomicfoundation/hardhat-network-helpers' + +export async function deployIdentityProxy( + implementationAuthority: Contract['address'], + managementKey: string, + signer: Signer +) { + const identity = await new ethers.ContractFactory( + OnchainID.contracts.IdentityProxy.abi, + OnchainID.contracts.IdentityProxy.bytecode, + signer + ).deploy(implementationAuthority, managementKey) + + return ethers.getContractAt('Identity', identity.address, signer) +} + +export async function deployFullSuiteFixture() { + const [ + deployer, + tokenIssuer, + tokenAgent, + tokenAdmin, + claimIssuer, + aliceWallet, + bobWallet, + charlieWallet, + davidWallet, + anotherWallet, + ] = await ethers.getSigners() + const claimIssuerSigningKey = ethers.Wallet.createRandom() + const aliceActionKey = ethers.Wallet.createRandom() + + // Deploy implementations + const claimTopicsRegistryImplementation = await ethers.deployContract( + 'ClaimTopicsRegistry', + deployer + ) + const trustedIssuersRegistryImplementation = await ethers.deployContract( + 'TrustedIssuersRegistry', + deployer + ) + const identityRegistryStorageImplementation = await ethers.deployContract( + 'IdentityRegistryStorage', + deployer + ) + const identityRegistryImplementation = await ethers.deployContract( + 'IdentityRegistry', + deployer + ) + const modularComplianceImplementation = await ethers.deployContract( + 'ModularCompliance', + deployer + ) + const identityImplementation = await new ethers.ContractFactory( + OnchainID.contracts.Identity.abi, + OnchainID.contracts.Identity.bytecode, + deployer + ).deploy(deployer.address, true) + + const identityImplementationAuthority = await new ethers.ContractFactory( + OnchainID.contracts.ImplementationAuthority.abi, + OnchainID.contracts.ImplementationAuthority.bytecode, + deployer + ).deploy(identityImplementation.address) + + const identityFactory = await new ethers.ContractFactory( + OnchainID.contracts.Factory.abi, + OnchainID.contracts.Factory.bytecode, + deployer + ).deploy(identityImplementationAuthority.address) + + const trexImplementationAuthority = await ethers.deployContract( + 'TREXImplementationAuthority', + [true, ethers.constants.AddressZero, ethers.constants.AddressZero], + deployer + ) + const versionStruct = { + major: 4, + minor: 0, + patch: 0, + } + const contractsStruct = { + tokenImplementation: ethers.Wallet.createRandom().address, + ctrImplementation: claimTopicsRegistryImplementation.address, + irImplementation: identityRegistryImplementation.address, + irsImplementation: identityRegistryStorageImplementation.address, + tirImplementation: trustedIssuersRegistryImplementation.address, + mcImplementation: modularComplianceImplementation.address, + } + + await trexImplementationAuthority + .connect(deployer) + .addAndUseTREXVersion(versionStruct, contractsStruct) + + const trexFactory = await ethers.deployContract( + 'TREXFactory', + [trexImplementationAuthority.address, identityFactory.address], + deployer + ) + await identityFactory.connect(deployer).addTokenFactory(trexFactory.address) + + const claimTopicsRegistry = await ethers + .deployContract( + 'ClaimTopicsRegistryProxy', + [trexImplementationAuthority.address], + deployer + ) + .then(async (proxy) => + ethers.getContractAt('ClaimTopicsRegistry', proxy.address) + ) + + const trustedIssuersRegistry = await ethers + .deployContract( + 'TrustedIssuersRegistryProxy', + [trexImplementationAuthority.address], + deployer + ) + .then(async (proxy) => + ethers.getContractAt('TrustedIssuersRegistry', proxy.address) + ) + + const identityRegistryStorage = await ethers + .deployContract( + 'IdentityRegistryStorageProxy', + [trexImplementationAuthority.address], + deployer + ) + .then(async (proxy) => + ethers.getContractAt('IdentityRegistryStorage', proxy.address) + ) + + const defaultCompliance = await ethers.deployContract( + 'DefaultCompliance', + deployer + ) + + const identityRegistry = await ethers + .deployContract( + 'IdentityRegistryProxy', + [ + trexImplementationAuthority.address, + trustedIssuersRegistry.address, + claimTopicsRegistry.address, + identityRegistryStorage.address, + ], + deployer + ) + .then(async (proxy) => + ethers.getContractAt('IdentityRegistry', proxy.address) + ) + + const tokenOID = await deployIdentityProxy( + identityImplementationAuthority.address, + tokenIssuer.address, + deployer + ) + + await identityRegistryStorage + .connect(deployer) + .bindIdentityRegistry(identityRegistry.address) + + const claimTopics = [ethers.utils.id('CLAIM_TOPIC')] + await claimTopicsRegistry.connect(deployer).addClaimTopic(claimTopics[0]) + + const claimIssuerContract = await ethers.deployContract( + 'ClaimIssuer', + [claimIssuer.address], + claimIssuer + ) + await claimIssuerContract + .connect(claimIssuer) + .addKey( + ethers.utils.keccak256( + ethers.utils.defaultAbiCoder.encode( + ['address'], + [claimIssuerSigningKey.address] + ) + ), + 3, + 1 + ) + + await trustedIssuersRegistry + .connect(deployer) + .addTrustedIssuer(claimIssuerContract.address, claimTopics) + + const aliceIdentity = await deployIdentityProxy( + identityImplementationAuthority.address, + aliceWallet.address, + deployer + ) + await aliceIdentity + .connect(aliceWallet) + .addKey( + ethers.utils.keccak256( + ethers.utils.defaultAbiCoder.encode( + ['address'], + [aliceActionKey.address] + ) + ), + 2, + 1 + ) + const bobIdentity = await deployIdentityProxy( + identityImplementationAuthority.address, + bobWallet.address, + deployer + ) + const charlieIdentity = await deployIdentityProxy( + identityImplementationAuthority.address, + charlieWallet.address, + deployer + ) + + await identityRegistry.connect(deployer).addAgent(tokenAgent.address) + + await identityRegistry + .connect(tokenAgent) + .batchRegisterIdentity( + [aliceWallet.address, bobWallet.address], + [aliceIdentity.address, bobIdentity.address], + [42, 666] + ) + + const claimForAlice = { + data: ethers.utils.hexlify( + ethers.utils.toUtf8Bytes('Some claim public data.') + ), + issuer: claimIssuerContract.address, + topic: claimTopics[0], + scheme: 1, + identity: aliceIdentity.address, + signature: '', + } + claimForAlice.signature = await claimIssuerSigningKey.signMessage( + ethers.utils.arrayify( + ethers.utils.keccak256( + ethers.utils.defaultAbiCoder.encode( + ['address', 'uint256', 'bytes'], + [ + claimForAlice.identity, + claimForAlice.topic, + claimForAlice.data, + ] + ) + ) + ) + ) + + await aliceIdentity + .connect(aliceWallet) + .addClaim( + claimForAlice.topic, + claimForAlice.scheme, + claimForAlice.issuer, + claimForAlice.signature, + claimForAlice.data, + '' + ) + + const claimForBob = { + data: ethers.utils.hexlify( + ethers.utils.toUtf8Bytes('Some claim public data.') + ), + issuer: claimIssuerContract.address, + topic: claimTopics[0], + scheme: 1, + identity: bobIdentity.address, + signature: '', + } + claimForBob.signature = await claimIssuerSigningKey.signMessage( + ethers.utils.arrayify( + ethers.utils.keccak256( + ethers.utils.defaultAbiCoder.encode( + ['address', 'uint256', 'bytes'], + [claimForBob.identity, claimForBob.topic, claimForBob.data] + ) + ) + ) + ) + + await bobIdentity + .connect(bobWallet) + .addClaim( + claimForBob.topic, + claimForBob.scheme, + claimForBob.issuer, + claimForBob.signature, + claimForBob.data, + '' + ) + + return { + accounts: { + deployer, + tokenIssuer, + tokenAgent, + tokenAdmin, + claimIssuer, + claimIssuerSigningKey, + aliceActionKey, + aliceWallet, + bobWallet, + charlieWallet, + davidWallet, + anotherWallet, + }, + identities: { + aliceIdentity, + bobIdentity, + charlieIdentity, + }, + suite: { + claimIssuerContract, + claimTopicsRegistry, + trustedIssuersRegistry, + identityRegistryStorage, + defaultCompliance, + identityRegistry, + tokenOID, + }, + authorities: { + trexImplementationAuthority, + identityImplementationAuthority, + }, + factories: { + trexFactory, + identityFactory, + }, + implementations: { + identityImplementation, + claimTopicsRegistryImplementation, + trustedIssuersRegistryImplementation, + identityRegistryStorageImplementation, + identityRegistryImplementation, + modularComplianceImplementation, + }, + } +} + +export async function deploySuiteWithModularCompliancesFixture() { + const context = await loadFixture(deployFullSuiteFixture) + + const complianceProxy = await ethers.deployContract( + 'ModularComplianceProxy', + [context.authorities.trexImplementationAuthority.address] + ) + const compliance = await ethers.getContractAt( + 'ModularCompliance', + complianceProxy.address + ) + + const complianceBeta = await ethers.deployContract('ModularCompliance') + await complianceBeta.init() + + return { + ...context, + suite: { + ...context.suite, + compliance, + complianceBeta, + }, + } +} diff --git a/packages/ats/contracts/test/unitTests/layer_1/ERC1400/ERC1410/erc1410.test.ts b/packages/ats/contracts/test/unitTests/layer_1/ERC1400/ERC1410/erc1410.test.ts index 436971aca..6048c202e 100644 --- a/packages/ats/contracts/test/unitTests/layer_1/ERC1400/ERC1410/erc1410.test.ts +++ b/packages/ats/contracts/test/unitTests/layer_1/ERC1400/ERC1410/erc1410.test.ts @@ -223,12 +223,12 @@ import { ERC1644, AdjustBalances, Cap, - IERC20, IFactory, BusinessLogicResolver, IClearing, ISnapshots, } from '@typechain' +import { IERC20 } from '@typechain/contracts/layer_1/interfaces/ERC1400/IERC20' import { ADJUSTMENT_BALANCE_ROLE, CAP_ROLE, diff --git a/packages/ats/contracts/tsconfig.json b/packages/ats/contracts/tsconfig.json index e1b60a9a4..16bf44b8a 100644 --- a/packages/ats/contracts/tsconfig.json +++ b/packages/ats/contracts/tsconfig.json @@ -15,6 +15,7 @@ "paths": { "@configuration": ["./Configuration"], "@typechain": ["./typechain-types/*", "./typechain-types/index.ts"], + "@typechain/contracts/*": ["./typechain-types/contracts/*"], "@scripts": ["./scripts/index"], "@tasks": ["./tasks/index.ts"], "@test": ["./test/index.ts"]