@t-rex-network/t-rex 5.0.0-beta2 → 5.0.0-beta3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/NOTICE.md +78 -0
  2. package/README.md +19 -22
  3. package/contracts/{roles/AgentRole.sol → ERC-3643/ERC3643ErrorsLib.sol} +60 -33
  4. package/contracts/ERC-3643/IERC3643.sol +61 -5
  5. package/contracts/ERC-3643/IERC3643ClaimTopicsRegistry.sol +11 -2
  6. package/contracts/ERC-3643/IERC3643Compliance.sol +21 -8
  7. package/contracts/ERC-3643/IERC3643IdentityRegistry.sol +33 -0
  8. package/contracts/ERC-3643/IERC3643IdentityRegistryStorage.sol +62 -7
  9. package/contracts/ERC-3643/IERC3643TrustedIssuersRegistry.sol +29 -12
  10. package/contracts/ERC-3643/base/ERC3643ClaimTopicsRegistry.sol +140 -0
  11. package/contracts/ERC-3643/base/ERC3643Compliance.sol +223 -0
  12. package/contracts/ERC-3643/base/ERC3643IdentityRegistry.sol +382 -0
  13. package/contracts/ERC-3643/base/ERC3643IdentityRegistryStorage.sol +290 -0
  14. package/contracts/ERC-3643/base/ERC3643Token.sol +601 -0
  15. package/contracts/ERC-3643/base/ERC3643TrustedIssuersRegistry.sol +237 -0
  16. package/contracts/compliance/modular/ComplianceLedger.sol +175 -0
  17. package/contracts/compliance/modular/ComplianceLedgerLib.sol +120 -0
  18. package/contracts/compliance/modular/IComplianceLedger.sol +104 -0
  19. package/contracts/compliance/modular/IModularCompliance.sol +119 -28
  20. package/contracts/compliance/modular/ITransferValidation.sol +308 -0
  21. package/contracts/compliance/modular/ModularCompliance.sol +399 -240
  22. package/contracts/compliance/modular/ModuleSetLib.sol +182 -0
  23. package/contracts/compliance/modular/MovementKindLib.sol +97 -0
  24. package/contracts/compliance/modular/TransferContextLib.sol +140 -0
  25. package/contracts/compliance/modular/TransferValidation.sol +822 -0
  26. package/contracts/compliance/modular/TransferValidationLib.sol +183 -0
  27. package/contracts/compliance/modular/modules/AbstractModuleUpgradeable.sol +87 -56
  28. package/contracts/compliance/modular/modules/IModule.sol +142 -58
  29. package/contracts/compliance/modular/modules/MaxBalancePerIdentityModule.sol +175 -0
  30. package/contracts/compliance/modular/modules/ModuleProxy.sol +24 -24
  31. package/contracts/compliance/modular/modules/SpenderVerificationModule.sol +149 -0
  32. package/contracts/compliance/modular/modules/SpenderWhitelistModule.sol +215 -0
  33. package/contracts/factory/ITREXFactory.sol +94 -44
  34. package/contracts/factory/TREXFactory.sol +408 -201
  35. package/contracts/interop/ISettlementHandler.sol +101 -0
  36. package/contracts/interop/ITREXMessaging.sol +166 -0
  37. package/contracts/{proxy/ModularComplianceProxy.sol → interop/ITrustedGatewayRegistry.sol} +48 -43
  38. package/contracts/interop/TREXMessaging.sol +189 -0
  39. package/contracts/interop/TREXMessagingLib.sol +425 -0
  40. package/contracts/{proxy/TrustedIssuersRegistryProxy.sol → interop/TrustedGatewayRegistry.sol} +46 -37
  41. package/contracts/libraries/AccessManagerSetupLib.sol +484 -0
  42. package/contracts/libraries/ErrorsLib.sol +172 -65
  43. package/contracts/libraries/EventsLib.sol +168 -66
  44. package/contracts/libraries/MessageTypesLib.sol +259 -0
  45. package/contracts/libraries/RolesLib.sol +146 -0
  46. package/contracts/{roles/Roles.sol → libraries/VersionLib.sol} +46 -49
  47. package/contracts/libraries/WalletKeyLib.sol +156 -0
  48. package/contracts/proxy/beacon/ITREXImplementationAuthority.sol +157 -0
  49. package/contracts/proxy/beacon/TREXImplementationAuthority.sol +188 -0
  50. package/contracts/registry/implementation/IdentityRegistryStorage.sol +215 -163
  51. package/contracts/registry/implementation/TREXRegistry.sol +475 -0
  52. package/contracts/registry/interface/IIdentityRegistryStorage.sol +30 -25
  53. package/contracts/registry/interface/ITREXRegistry.sol +180 -0
  54. package/contracts/token/IToken.sol +210 -49
  55. package/contracts/token/Token.sol +411 -476
  56. package/contracts/token/TokenDelegationLib.sol +339 -0
  57. package/contracts/token/TokenGuardsLib.sol +123 -0
  58. package/contracts/token/TokenLedgerLib.sol +316 -0
  59. package/contracts/token/TokenRecoveryLib.sol +130 -0
  60. package/contracts/{roles/AgentRoleUpgradeable.sol → utils/AccessManagedOwnable.sol} +31 -31
  61. package/contracts/{proxy/IdentityRegistryStorageProxy.sol → utils/AccessManagedOwnableBase.sol} +56 -34
  62. package/contracts/utils/AccessManagedOwnableUpgradeable.sol +116 -0
  63. package/contracts/utils/IUtilityChecker.sol +32 -26
  64. package/contracts/{roles/AbstractAgentRole.sol → utils/TREXAccessManager.sol} +54 -57
  65. package/contracts/utils/UtilityChecker.sol +175 -52
  66. package/contracts/utils/UtilityCheckerProxy.sol +24 -24
  67. package/contracts/{proxy/interface/IProxy.sol → vendor/IERC173.sol} +15 -28
  68. package/out/AbstractModuleUpgradeable.sol/AbstractModuleUpgradeable.json +1 -1
  69. package/out/AbstractSigner.sol/AbstractSigner.json +1 -0
  70. package/out/AccessManaged.sol/AccessManaged.json +1 -0
  71. package/out/AccessManagedOwnable.sol/AccessManagedOwnable.json +1 -0
  72. package/out/AccessManagedOwnableBase.sol/AccessManagedOwnableBase.json +1 -0
  73. package/out/AccessManagedOwnableUpgradeable.sol/AccessManagedOwnableUpgradeable.json +1 -0
  74. package/out/AccessManagedUpgradeable.sol/AccessManagedUpgradeable.json +1 -0
  75. package/out/AccessManager.sol/AccessManager.json +1 -0
  76. package/out/AccessManagerHelper.sol/AccessManagerHelper.json +1 -0
  77. package/out/AccessManagerSetupLib.sol/AccessManagerSetupLib.json +1 -0
  78. package/out/AccessManagerUpgradeable.sol/AccessManagerUpgradeable.json +1 -0
  79. package/out/Account.sol/Account.json +1 -0
  80. package/out/Address.sol/Address.json +1 -1
  81. package/out/Arrays.sol/Arrays.json +1 -1
  82. package/out/AuthorityUtils.sol/AuthorityUtils.json +1 -0
  83. package/out/Base.sol/CommonBase.json +1 -1
  84. package/out/Base.sol/ScriptBase.json +1 -1
  85. package/out/Base.sol/TestBase.json +1 -1
  86. package/out/Base64.sol/Base64.json +1 -0
  87. package/out/BeaconProxy.sol/BeaconProxy.json +1 -0
  88. package/out/BeaconProxyDeployer.sol/BeaconProxyDeployer.json +1 -0
  89. package/out/Bytes.sol/Bytes.json +1 -1
  90. package/out/Calldata.sol/Calldata.json +1 -0
  91. package/out/CapabilityModules.sol/AllTypesModule.json +1 -0
  92. package/out/CapabilityModules.sol/CappedRecipientModule.json +1 -0
  93. package/out/CapabilityModules.sol/DelegatedCapRuleModule.json +1 -0
  94. package/out/CapabilityModules.sol/DuplicateTypeModule.json +1 -0
  95. package/out/CapabilityModules.sol/LockedSenderModule.json +1 -0
  96. package/out/CapabilityModules.sol/NoTypeModule.json +1 -0
  97. package/out/CapabilityModules.sol/RecordingModule.json +1 -0
  98. package/out/CapabilityModules.sol/RuleAndMintTrackerModule.json +1 -0
  99. package/out/CapabilityModules.sol/RuleAndTrackerModule.json +1 -0
  100. package/out/CapabilityModules.sol/RuleOnlyModule.json +1 -0
  101. package/out/CapabilityModules.sol/SpenderOnlyModule.json +1 -0
  102. package/out/CapabilityModules.sol/TrackerOnlyModule.json +1 -0
  103. package/out/CapabilityModules.sol/UndeclaredRuleModule.json +1 -0
  104. package/out/CapabilityModules.sol/WritingRuleModule.json +1 -0
  105. package/out/ClaimIssuerAlwaysReverts.sol/ClaimIssuerAlwaysReverts.json +1 -0
  106. package/out/ClaimIssuerTrick.sol/ClaimIssuerTrick.json +1 -1
  107. package/out/Comparators.sol/Comparators.json +1 -1
  108. package/out/ComplianceLedger.sol/ComplianceLedger.json +1 -0
  109. package/out/ComplianceLedgerLib.sol/ComplianceLedgerLib.json +1 -0
  110. package/out/Context.sol/Context.json +1 -1
  111. package/out/ContextUpgradeable.sol/ContextUpgradeable.json +1 -1
  112. package/out/Countries.sol/Countries.json +1 -1
  113. package/out/Create2.sol/Create2.json +1 -1
  114. package/out/Create3.sol/Create3.json +1 -1
  115. package/out/DeployComplianceModules.s.sol/DeployComplianceModules.json +1 -0
  116. package/out/DeployComplianceModules.s.sol/ITokenCompliance.json +1 -0
  117. package/out/DeployUtilityChecker.s.sol/DeployUtilityChecker.json +1 -0
  118. package/out/ECDSA.sol/ECDSA.json +1 -1
  119. package/out/EIP712.sol/EIP712.json +1 -1
  120. package/out/EIP712Upgradeable.sol/EIP712Upgradeable.json +1 -1
  121. package/out/ERC165.sol/ERC165.json +1 -0
  122. package/out/ERC165Checker.sol/ERC165Checker.json +1 -0
  123. package/out/ERC165Upgradeable.sol/ERC165Upgradeable.json +1 -0
  124. package/out/ERC1967Proxy.sol/ERC1967Proxy.json +1 -1
  125. package/out/ERC1967Utils.sol/ERC1967Utils.json +1 -1
  126. package/out/ERC20.sol/ERC20.json +1 -1
  127. package/out/ERC20Pausable.sol/ERC20Pausable.json +1 -1
  128. package/out/ERC20PermitUpgradeable.sol/ERC20PermitUpgradeable.json +1 -1
  129. package/out/ERC20Upgradeable.sol/ERC20Upgradeable.json +1 -1
  130. package/out/ERC3643ClaimTopicsRegistry.sol/ERC3643ClaimTopicsRegistry.json +1 -0
  131. package/out/ERC3643Compliance.sol/ERC3643Compliance.json +1 -0
  132. package/out/ERC3643ErrorsLib.sol/ERC3643ErrorsLib.json +1 -0
  133. package/out/ERC3643IdentityRegistry.sol/ERC3643IdentityRegistry.json +1 -0
  134. package/out/ERC3643IdentityRegistryStorage.sol/ERC3643IdentityRegistryStorage.json +1 -0
  135. package/out/ERC3643Token.sol/ERC3643Token.json +1 -0
  136. package/out/ERC3643TrustedIssuersRegistry.sol/ERC3643TrustedIssuersRegistry.json +1 -0
  137. package/out/ERC4337Utils.sol/ERC4337Utils.json +1 -0
  138. package/out/ERC4337Utils.sol/IEntryPointExtra.json +1 -0
  139. package/out/ERC734Validator.sol/ERC734Validator.json +1 -0
  140. package/out/ERC7579Validator.sol/ERC7579Validator.json +1 -0
  141. package/out/ERC7786GatewayMock.sol/ERC7786GatewayMock.json +1 -0
  142. package/out/ERC7786Recipient.sol/ERC7786Recipient.json +1 -0
  143. package/out/ERC7913WebAuthnVerifier.sol/ERC7913WebAuthnVerifier.json +1 -0
  144. package/out/EnumerableSet.sol/EnumerableSet.json +1 -1
  145. package/out/Errors.sol/Errors.json +1 -1
  146. package/out/ErrorsLib.sol/ErrorsLib.json +1 -1
  147. package/out/EventsLib.sol/EventsLib.json +1 -1
  148. package/out/Hashes.sol/Hashes.json +1 -0
  149. package/out/HostileModules.sol/RevertEverywhereModule.json +1 -0
  150. package/out/HostileModules.sol/UnbindRevertingModule.json +1 -0
  151. package/out/IAccessManaged.sol/IAccessManaged.json +1 -0
  152. package/out/IAccessManager.sol/IAccessManager.json +1 -0
  153. package/out/IAuthority.sol/IAuthority.json +1 -0
  154. package/out/IBeacon.sol/IBeacon.json +1 -1
  155. package/out/IClaimIssuer.sol/IClaimIssuer.json +1 -1
  156. package/out/IComplianceLedger.sol/IComplianceLedger.json +1 -0
  157. package/out/IERC1271.sol/IERC1271.json +1 -0
  158. package/out/IERC165.sol/IERC165.json +1 -1
  159. package/out/IERC173.sol/IERC173.json +1 -1
  160. package/out/IERC1967.sol/IERC1967.json +1 -1
  161. package/out/IERC20.sol/IERC20.json +1 -1
  162. package/out/IERC20Metadata.sol/IERC20Metadata.json +1 -1
  163. package/out/IERC20Permit.sol/IERC20Permit.json +1 -1
  164. package/out/IERC3643.sol/IERC3643.json +1 -1
  165. package/out/IERC3643ClaimTopicsRegistry.sol/IERC3643ClaimTopicsRegistry.json +1 -1
  166. package/out/IERC3643Compliance.sol/IERC3643Compliance.json +1 -1
  167. package/out/IERC3643IdentityRegistry.sol/IERC3643IdentityRegistry.json +1 -1
  168. package/out/IERC3643IdentityRegistryStorage.sol/IERC3643IdentityRegistryStorage.json +1 -1
  169. package/out/IERC3643TrustedIssuersRegistry.sol/IERC3643TrustedIssuersRegistry.json +1 -1
  170. package/out/IERC4337.sol/IAccount.json +1 -0
  171. package/out/IERC4337.sol/IAccountExecute.json +1 -0
  172. package/out/IERC4337.sol/IAggregator.json +1 -0
  173. package/out/IERC4337.sol/IEntryPoint.json +1 -0
  174. package/out/IERC4337.sol/IEntryPointNonces.json +1 -0
  175. package/out/IERC4337.sol/IEntryPointStake.json +1 -0
  176. package/out/IERC4337.sol/IPaymaster.json +1 -0
  177. package/out/IERC5267.sol/IERC5267.json +1 -1
  178. package/out/IERC734.sol/IERC734.json +1 -1
  179. package/out/IERC735.sol/IERC735.json +1 -1
  180. package/out/IERC7913.sol/IERC7913SignatureVerifier.json +1 -0
  181. package/out/IIdentity.sol/IIdentity.json +1 -1
  182. package/out/IIdentityFactory.sol/IIdentityFactory.json +1 -0
  183. package/out/IIdentityRegistryStorage.sol/IIdentityRegistryStorage.json +1 -1
  184. package/out/IKeyExecutor.sol/IKeyExecutor.json +1 -0
  185. package/out/IModularCompliance.sol/IModularCompliance.json +1 -1
  186. package/out/IModule.sol/IModule.json +1 -1
  187. package/out/IMulticall3.sol/IMulticall3.json +1 -1
  188. package/out/IReputationRegistry.sol/IReputationRegistry.json +1 -0
  189. package/out/ISettlementHandler.sol/ISettlementHandler.json +1 -0
  190. package/out/ITREXFactory.sol/ITREXFactory.json +1 -1
  191. package/out/ITREXImplementationAuthority.sol/ITREXImplementationAuthority.json +1 -1
  192. package/out/ITREXMessaging.sol/ITREXMessaging.json +1 -0
  193. package/out/ITREXRegistry.sol/ITREXRegistry.json +1 -0
  194. package/out/IToken.sol/IToken.json +1 -1
  195. package/out/ITransferValidation.sol/ITransferValidation.json +1 -0
  196. package/out/ITrustedGatewayRegistry.sol/ITrustedGatewayRegistry.json +1 -0
  197. package/out/IUtilityChecker.sol/IUtilityChecker.json +1 -1
  198. package/out/Identity.sol/Identity.json +1 -1
  199. package/out/IdentityFactory.sol/IdentityFactory.json +1 -0
  200. package/out/IdentityModulesHelper.sol/IdentityModulesHelper.json +1 -0
  201. package/out/IdentityRegistryStorage.sol/IdentityRegistryStorage.json +1 -1
  202. package/out/IdentityTypes.sol/IdentityTypes.json +1 -0
  203. package/out/Initializable.sol/Initializable.json +1 -1
  204. package/out/InteropSuiteTest.sol/InteropSuiteTest.json +1 -0
  205. package/out/KeyApprovalModule.sol/IIdentityAccount.json +1 -0
  206. package/out/KeyApprovalModule.sol/KeyApprovalModule.json +1 -0
  207. package/out/KeyManager.sol/KeyManager.json +1 -0
  208. package/out/KeyPurposes.sol/KeyPurposes.json +1 -1
  209. package/out/KeyTypes.sol/KeyTypes.json +1 -1
  210. package/out/LowLevelCall.sol/LowLevelCall.json +1 -1
  211. package/out/Math.sol/Math.json +1 -1
  212. package/out/MaxBalancePerIdentityModule.sol/MaxBalancePerIdentityModule.json +1 -0
  213. package/out/MessageHashUtils.sol/MessageHashUtils.json +1 -1
  214. package/out/MessageTypesLib.sol/MessageTypesLib.json +1 -0
  215. package/out/MockTREXAccessManagerV2.sol/MockTREXAccessManagerV2.json +1 -0
  216. package/out/MockTokenV2.sol/MockTokenV2.json +1 -0
  217. package/out/Mocks.sol/ClaimTopicsRegistryMock.json +1 -0
  218. package/out/Mocks.sol/ComplianceMock.json +1 -0
  219. package/out/Mocks.sol/IdentityRegistryMock.json +1 -0
  220. package/out/Mocks.sol/IdentityRegistryStorageMock.json +1 -0
  221. package/out/Mocks.sol/TokenMock.json +1 -0
  222. package/out/Mocks.sol/TrustedIssuersRegistryMock.json +1 -0
  223. package/out/ModularCompliance.sol/ModularCompliance.json +1 -1
  224. package/out/ModuleNotPnP.sol/ModuleNotPnP.json +1 -1
  225. package/out/ModuleProxy.sol/ModuleProxy.json +1 -1
  226. package/out/ModuleSetLib.sol/ModuleSetLib.json +1 -0
  227. package/out/MovementKindLib.sol/MovementKindLib.json +1 -0
  228. package/out/Multicall.sol/Multicall.json +1 -0
  229. package/out/MulticallUpgradeable.sol/MulticallUpgradeable.json +1 -1
  230. package/out/Nonces.sol/Nonces.json +1 -1
  231. package/out/NoncesUpgradeable.sol/NoncesUpgradeable.json +1 -1
  232. package/out/Ownable.sol/Ownable.json +1 -1
  233. package/out/OwnableUpgradeable.sol/OwnableUpgradeable.json +1 -1
  234. package/out/P256.sol/P256.json +1 -0
  235. package/out/Packing.sol/Packing.json +1 -0
  236. package/out/Panic.sol/Panic.json +1 -1
  237. package/out/Pausable.sol/Pausable.json +1 -1
  238. package/out/PausableUpgradeable.sol/PausableUpgradeable.json +1 -1
  239. package/out/Proxy.sol/Proxy.json +1 -1
  240. package/out/ReentrancyGuardTransient.sol/ReentrancyGuardTransient.json +1 -0
  241. package/out/ReentrantModule.sol/ReentrantModule.json +1 -0
  242. package/out/ReputationRegistry.sol/ReputationRegistry.json +1 -0
  243. package/out/RolesLib.sol/RolesLib.json +1 -0
  244. package/out/SafeCalldataBatch.sol/SafeCalldataBatch.json +1 -0
  245. package/out/SafeCast.sol/SafeCast.json +1 -1
  246. package/out/SatelliteLiteMock.sol/SatelliteLiteMock.json +1 -0
  247. package/out/Script.sol/Script.json +1 -0
  248. package/out/ShortStrings.sol/ShortStrings.json +1 -1
  249. package/out/SignatureChecker.sol/SignatureChecker.json +1 -0
  250. package/out/SignedMath.sol/SignedMath.json +1 -1
  251. package/out/SlotDerivation.sol/SlotDerivation.json +1 -1
  252. package/out/SmartAccount.sol/SmartAccount.json +1 -0
  253. package/out/SpenderVerificationModule.sol/SpenderVerificationModule.json +1 -0
  254. package/out/SpenderWhitelistModule.sol/SpenderWhitelistModule.json +1 -0
  255. package/out/StdAssertions.sol/StdAssertions.json +1 -1
  256. package/out/StdChains.sol/StdChains.json +1 -1
  257. package/out/StdCheats.sol/StdCheats.json +1 -1
  258. package/out/StdCheats.sol/StdCheatsSafe.json +1 -1
  259. package/out/StdConstants.sol/StdConstants.json +1 -1
  260. package/out/StdError.sol/stdError.json +1 -1
  261. package/out/StdInvariant.sol/StdInvariant.json +1 -1
  262. package/out/StdJson.sol/stdJson.json +1 -1
  263. package/out/StdMath.sol/stdMath.json +1 -1
  264. package/out/StdStorage.sol/stdStorage.json +1 -1
  265. package/out/StdStorage.sol/stdStorageSafe.json +1 -1
  266. package/out/StdStyle.sol/StdStyle.json +1 -1
  267. package/out/StdToml.sol/stdToml.json +1 -1
  268. package/out/StdUtils.sol/StdUtils.json +1 -1
  269. package/out/StorageSlot.sol/StorageSlot.json +1 -1
  270. package/out/Strings.sol/Strings.json +1 -1
  271. package/out/Structs.sol/Structs.json +1 -1
  272. package/out/TREXAccessManager.sol/TREXAccessManager.json +1 -0
  273. package/out/TREXFactory.sol/TREXFactory.json +1 -1
  274. package/out/TREXImplementationAuthority.sol/TREXImplementationAuthority.json +1 -1
  275. package/out/TREXMessaging.sol/TREXMessaging.json +1 -0
  276. package/out/TREXMessagingLib.sol/TREXMessagingLib.json +1 -0
  277. package/out/TREXRegistry.sol/TREXRegistry.json +1 -0
  278. package/out/TestERC20.sol/TestERC20.json +1 -1
  279. package/out/TestModule.sol/TestModule.json +1 -1
  280. package/out/TestTREXFactory.sol/TestTREXFactory.json +1 -1
  281. package/out/Time.sol/Time.json +1 -0
  282. package/out/Token.sol/Token.json +1 -1
  283. package/out/TokenDelegationLib.sol/TokenDelegationLib.json +1 -0
  284. package/out/TokenGuardsLib.sol/TokenGuardsLib.json +1 -0
  285. package/out/TokenHandler.sol/TokenHandler.json +1 -0
  286. package/out/TokenLedgerHarness.sol/TokenLedgerHarness.json +1 -0
  287. package/out/TokenLedgerLib.sol/TokenLedgerLib.json +1 -0
  288. package/out/TokenRecoveryLib.sol/TokenRecoveryLib.json +1 -0
  289. package/out/TokenReservationStub.sol/TokenReservationStub.json +1 -0
  290. package/out/TransferContextLib.sol/TransferContextLib.json +1 -0
  291. package/out/TransferValidation.sol/TransferValidation.json +1 -0
  292. package/out/TransferValidationHarness.sol/TransferValidationHarness.json +1 -0
  293. package/out/TransferValidationLib.sol/TransferValidationLib.json +1 -0
  294. package/out/TransientSlot.sol/TransientSlot.json +1 -0
  295. package/out/TrustedGatewayRegistry.sol/TrustedGatewayRegistry.json +1 -0
  296. package/out/UUPSUpgradeable.sol/UUPSUpgradeable.json +1 -1
  297. package/out/UpgradeableBeacon.sol/UpgradeableBeacon.json +1 -0
  298. package/out/UtilityChecker.sol/UtilityChecker.json +1 -1
  299. package/out/UtilityCheckerProxy.sol/UtilityCheckerProxy.json +1 -1
  300. package/out/Utils.sol/Utils.json +1 -1
  301. package/out/VersionLib.sol/VersionLib.json +1 -0
  302. package/out/Vm.sol/Vm.json +1 -1
  303. package/out/Vm.sol/VmSafe.json +1 -1
  304. package/out/WalletKeyLib.sol/WalletKeyLib.json +1 -0
  305. package/out/WebAuthn.sol/WebAuthn.json +1 -0
  306. package/out/console.sol/console.json +1 -1
  307. package/out/draft-AccountERC7579Upgradeable.sol/AccountERC7579Upgradeable.json +1 -0
  308. package/out/draft-ERC7579Utils.sol/ERC7579Utils.json +1 -0
  309. package/out/draft-IERC1822.sol/IERC1822Proxiable.json +1 -1
  310. package/out/draft-IERC6093.sol/IERC1155Errors.json +1 -1
  311. package/out/draft-IERC6093.sol/IERC20Errors.json +1 -1
  312. package/out/draft-IERC6093.sol/IERC721Errors.json +1 -1
  313. package/out/draft-IERC7579.sol/IERC7579AccountConfig.json +1 -0
  314. package/out/draft-IERC7579.sol/IERC7579Execution.json +1 -0
  315. package/out/draft-IERC7579.sol/IERC7579Hook.json +1 -0
  316. package/out/draft-IERC7579.sol/IERC7579Module.json +1 -0
  317. package/out/draft-IERC7579.sol/IERC7579ModuleConfig.json +1 -0
  318. package/out/draft-IERC7579.sol/IERC7579Validator.json +1 -0
  319. package/out/draft-IERC7786.sol/IERC7786GatewaySource.json +1 -0
  320. package/out/draft-IERC7786.sol/IERC7786Recipient.json +1 -0
  321. package/out/draft-InteroperableAddress.sol/InteroperableAddress.json +1 -0
  322. package/out/libraries/Errors.sol/Errors.json +1 -1
  323. package/out/safeconsole.sol/safeconsole.json +1 -1
  324. package/package.json +11 -7
  325. package/contracts/ERC-3643/ERC3643EventsLib.sol +0 -150
  326. package/contracts/factory/ITREXGateway.sol +0 -234
  327. package/contracts/factory/TREXGateway.sol +0 -274
  328. package/contracts/proxy/AbstractProxy.sol +0 -146
  329. package/contracts/proxy/ClaimTopicsRegistryProxy.sol +0 -83
  330. package/contracts/proxy/IdentityRegistryProxy.sol +0 -95
  331. package/contracts/proxy/TokenProxy.sol +0 -97
  332. package/contracts/proxy/authority/IAFactory.sol +0 -122
  333. package/contracts/proxy/authority/IIAFactory.sol +0 -87
  334. package/contracts/proxy/authority/ITREXImplementationAuthority.sol +0 -239
  335. package/contracts/proxy/authority/TREXImplementationAuthority.sol +0 -350
  336. package/contracts/registry/implementation/ClaimTopicsRegistry.sol +0 -152
  337. package/contracts/registry/implementation/IdentityRegistry.sol +0 -352
  338. package/contracts/registry/implementation/TrustedIssuersRegistry.sol +0 -272
  339. package/contracts/registry/interface/IClaimTopicsRegistry.sol +0 -70
  340. package/contracts/registry/interface/IIdentityRegistry.sol +0 -102
  341. package/contracts/registry/interface/ITrustedIssuersRegistry.sol +0 -70
  342. package/contracts/roles/IERC173.sol +0 -21
  343. package/contracts/token/TokenStructs.sol +0 -74
  344. package/contracts/utils/InterfaceIdCalculator.sol +0 -223
  345. package/contracts/vendor/openzeppelin/Create3.sol +0 -143
  346. package/out/AbstractAgentRole.sol/AbstractAgentRole.json +0 -1
  347. package/out/AbstractProxy.sol/AbstractProxy.json +0 -1
  348. package/out/AgentRole.sol/AgentRole.json +0 -1
  349. package/out/AgentRoleUpgradeable.sol/AgentRoleUpgradeable.json +0 -1
  350. package/out/ClaimIssuer.sol/ClaimIssuer.json +0 -1
  351. package/out/ClaimTopicsRegistry.sol/ClaimTopicsRegistry.json +0 -1
  352. package/out/ClaimTopicsRegistryProxy.sol/ClaimTopicsRegistryProxy.json +0 -1
  353. package/out/ERC2771Context.sol/ERC2771Context.json +0 -1
  354. package/out/ERC2771ContextUpgradeable.sol/ERC2771ContextUpgradeable.json +0 -1
  355. package/out/ERC2771Forwarder.sol/ERC2771Forwarder.json +0 -1
  356. package/out/ERC3643EventsLib.sol/ERC3643EventsLib.json +0 -1
  357. package/out/IAFactory.sol/IAFactory.json +0 -1
  358. package/out/IClaimTopicsRegistry.sol/IClaimTopicsRegistry.json +0 -1
  359. package/out/IERC1363.sol/IERC1363.json +0 -1
  360. package/out/IIAFactory.sol/IIAFactory.json +0 -1
  361. package/out/IIdFactory.sol/IIdFactory.json +0 -1
  362. package/out/IIdentityRegistry.sol/IIdentityRegistry.json +0 -1
  363. package/out/IImplementationAuthority.sol/IImplementationAuthority.json +0 -1
  364. package/out/IProxy.sol/IProxy.json +0 -1
  365. package/out/ITREXGateway.sol/ITREXGateway.json +0 -1
  366. package/out/ITrustedIssuersRegistry.sol/ITrustedIssuersRegistry.json +0 -1
  367. package/out/IdFactory.sol/IdFactory.json +0 -1
  368. package/out/IdentityProxy.sol/IdentityProxy.json +0 -1
  369. package/out/IdentityRegistry.sol/IdentityRegistry.json +0 -1
  370. package/out/IdentityRegistryProxy.sol/IdentityRegistryProxy.json +0 -1
  371. package/out/IdentityRegistryStorageProxy.sol/IdentityRegistryStorageProxy.json +0 -1
  372. package/out/ImplementationAuthority.sol/ImplementationAuthority.json +0 -1
  373. package/out/InterfaceIdCalculator.sol/InterfaceIdCalculator.json +0 -1
  374. package/out/ModularComplianceProxy.sol/ModularComplianceProxy.json +0 -1
  375. package/out/Ownable2Step.sol/Ownable2Step.json +0 -1
  376. package/out/Ownable2StepUpgradeable.sol/Ownable2StepUpgradeable.json +0 -1
  377. package/out/Roles.sol/Roles.json +0 -1
  378. package/out/SafeERC20.sol/SafeERC20.json +0 -1
  379. package/out/Storage.sol/Storage.json +0 -1
  380. package/out/TREXGateway.sol/TREXGateway.json +0 -1
  381. package/out/TestAgentRole.sol/TestAgentRole.json +0 -1
  382. package/out/TestAgentRoleUpgradeable.sol/TestAgentRoleUpgradeable.json +0 -1
  383. package/out/TokenProxy.sol/TokenProxy.json +0 -1
  384. package/out/TrustedIssuersRegistry.sol/TrustedIssuersRegistry.json +0 -1
  385. package/out/TrustedIssuersRegistryProxy.sol/TrustedIssuersRegistryProxy.json +0 -1
  386. package/out/Version.sol/Version.json +0 -1
@@ -37,628 +37,563 @@
37
37
  // :#%%=
38
38
  //
39
39
 
40
- /**
41
- * NOTICE
42
- *
43
- * The T-REX software is licensed under a proprietary license or the GPL v.3.
44
- * If you choose to receive it under the GPL v.3 license, the following applies:
45
- * T-REX is a suite of smart contracts implementing the ERC-3643 standard and
46
- * developed by Tokeny to manage and transfer financial assets on EVM blockchains
47
- *
48
- * Copyright (C) 2025, Tokeny sàrl.
49
- *
50
- * This program is free software: you can redistribute it and/or modify
51
- * it under the terms of the GNU General Public License as published by
52
- * the Free Software Foundation, either version 3 of the License, or
53
- * (at your option) any later version.
54
- *
55
- * This program is distributed in the hope that it will be useful,
56
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
57
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58
- * GNU General Public License for more details.
59
- *
60
- * You should have received a copy of the GNU General Public License
61
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
62
- */
40
+ // T-REX Smart Contracts
41
+ // The ERC-3643 token suite of the T-REX ecosystem.
42
+ //
43
+ // Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
44
+ //
45
+ // This file is part of the T-REX smart contract suite.
46
+ //
47
+ // This program is free software: you can redistribute it and/or modify
48
+ // it under the terms of the GNU General Public License as published by
49
+ // the Free Software Foundation, either version 3 of the License, or
50
+ // (at your option) any later version.
51
+ //
52
+ // This program is distributed in the hope that it will be useful,
53
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
54
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55
+ // GNU General Public License for more details.
56
+ //
57
+ // You should have received a copy of the GNU General Public License
58
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
63
59
 
64
60
  pragma solidity 0.8.30;
65
61
 
66
- import { IIdentity } from "@onchain-id/solidity/contracts/interface/IIdentity.sol";
67
-
68
- import {
69
- ContextUpgradeable,
70
- ERC2771ContextUpgradeable
71
- } from "@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol";
72
62
  import {
73
63
  ERC20PermitUpgradeable,
74
64
  ERC20Upgradeable,
75
65
  IERC20Permit
76
66
  } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
77
- import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
78
- import { EIP712Upgradeable } from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
79
- import { IERC20Errors } from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
80
67
  import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
81
68
  import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
82
- import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
83
69
 
84
- import { ERC3643EventsLib } from "../ERC-3643/ERC3643EventsLib.sol";
70
+ import { IIdentity } from "@onchain-id/solidity/contracts/interface/IIdentity.sol";
71
+
85
72
  import { IERC3643 } from "../ERC-3643/IERC3643.sol";
86
73
  import { IERC3643Compliance } from "../ERC-3643/IERC3643Compliance.sol";
87
- import { IERC3643IdentityRegistry } from "../ERC-3643/IERC3643IdentityRegistry.sol";
74
+ import { ERC3643Token } from "../ERC-3643/base/ERC3643Token.sol";
75
+ import { IModularCompliance } from "../compliance/modular/IModularCompliance.sol";
76
+ import { MovementKindLib } from "../compliance/modular/MovementKindLib.sol";
77
+ import { ITREXMessaging } from "../interop/ITREXMessaging.sol";
78
+ import { TREXMessaging } from "../interop/TREXMessaging.sol";
79
+ import { TREXMessagingLib } from "../interop/TREXMessagingLib.sol";
88
80
  import { ErrorsLib } from "../libraries/ErrorsLib.sol";
89
81
  import { EventsLib } from "../libraries/EventsLib.sol";
90
- import { AgentRoleUpgradeable } from "../roles/AgentRoleUpgradeable.sol";
91
- import { IERC173 } from "../roles/IERC173.sol";
82
+ import { MessageTypesLib } from "../libraries/MessageTypesLib.sol";
83
+ import { ITREXRegistry } from "../registry/interface/ITREXRegistry.sol";
84
+ import {
85
+ AccessManagedOwnableBase,
86
+ AccessManagedOwnableUpgradeable
87
+ } from "../utils/AccessManagedOwnableUpgradeable.sol";
92
88
  import { IToken } from "./IToken.sol";
93
- import { TokenRoles } from "./TokenStructs.sol";
89
+ import { TokenDelegationLib } from "./TokenDelegationLib.sol";
90
+ import { TokenGuardsLib } from "./TokenGuardsLib.sol";
91
+ import { TokenLedgerLib } from "./TokenLedgerLib.sol";
92
+ import { TokenRecoveryLib } from "./TokenRecoveryLib.sol";
94
93
 
95
- contract Token is
96
- ERC20PermitUpgradeable,
97
- PausableUpgradeable,
98
- AgentRoleUpgradeable,
99
- ERC2771ContextUpgradeable,
100
- IToken,
101
- IERC165
102
- {
94
+ /// @title Token
95
+ /// @dev The T-REX security token: {ERC3643Token} plus AccessManager authorization, validation on the
96
+ /// collaborator setters, the spender check on `transferFrom`, the extra recovery preconditions,
97
+ /// ERC-2612 permit, ERC-165, and the bridged ledger the ERC-7786 messaging endpoint settles onto.
98
+ contract Token is ERC3643Token, ERC20PermitUpgradeable, AccessManagedOwnableUpgradeable, TREXMessaging, IToken {
103
99
 
104
100
  string internal constant VERSION = "5.0.0";
105
101
 
106
- struct FrozenStatus {
107
- bool addressFrozen;
108
- uint256 amount;
109
- }
110
-
111
- /// @custom:storage-location erc7201:token.storage.main
112
- struct TokenStorage {
113
- string name;
114
- string symbol;
115
- uint8 decimals;
116
- address onchainId;
117
- IERC3643Compliance compliance;
118
- IERC3643IdentityRegistry identityRegistry;
119
- address trustedForwarder;
120
-
121
- mapping(address user => FrozenStatus) frozenStatus;
122
- mapping(address spender => bool) defaultAllowances;
123
- mapping(address user => bool) defaultAllowanceOptOuts;
124
-
125
- mapping(address agent => TokenRoles) agentsRestrictions;
126
- }
127
-
128
- // keccak256(abi.encode(uint256(keccak256("token.storage.main")) - 1)) & ~bytes32(uint256(0xff));
129
- bytes32 private constant TOKEN_STORAGE_LOCATION =
130
- 0x3eb201768b0b55c18fa93955aeb38c6bf0f381d8227d53e1b0e5b066883d4e00;
131
-
132
- constructor() ERC2771ContextUpgradeable(address(0)) {
102
+ constructor() {
133
103
  _disableInitializers();
134
104
  }
135
105
 
136
- /// @dev the constructor initiates the token contract
137
- /// @param tokenName the name of the token
138
- /// @param tokenSymbol the symbol of the token
139
- /// @param tokenDecimals the decimals of the token
140
- /// @param identityRegistryAddress the address of the Identity registry linked to the token
141
- /// @param complianceAddress the address of the compliance contract linked to the token
142
- /// The factory pre-binds the predicted Token CREATE3 address in MC.init, so Token.init does NOT
143
- /// call `bindToken` itself — the wiring is already in place by the time this code runs.
144
- /// @param onchainIdAddress the address of the onchainID of the token
145
- /// onchainID can be zero address if not set, can be set later by the owner
146
- /// @param owner final owner of the token, applied directly via `__Ownable_init(owner)` — no transient
147
- /// factory ownership
148
- /// @param tokenAgents addresses to grant the agent role at init time; capped at 5
149
- /// emits an `UpdatedTokenInformation` event
150
- /// emits an `IdentityRegistryAdded` event
151
- /// emits a `ComplianceAdded` event
152
- /// emits an `AgentAdded` event for each entry in `tokenAgents`
153
106
  function init(
154
107
  string memory tokenName,
155
108
  string memory tokenSymbol,
156
109
  uint8 tokenDecimals,
157
110
  address identityRegistryAddress,
158
111
  address complianceAddress,
112
+ address trustedGatewayRegistryAddress,
159
113
  address onchainIdAddress,
160
- address owner,
161
- address[] calldata tokenAgents
114
+ address accessManagerAddress
162
115
  ) external initializer {
163
116
  require(
164
- identityRegistryAddress != address(0) && complianceAddress != address(0) && owner != address(0),
117
+ identityRegistryAddress != address(0) && complianceAddress != address(0)
118
+ && accessManagerAddress != address(0),
165
119
  ErrorsLib.ZeroAddress()
166
120
  );
167
121
  require(bytes(tokenName).length > 0 && bytes(tokenSymbol).length > 0, ErrorsLib.EmptyString());
168
122
  require(tokenDecimals <= 18, ErrorsLib.DecimalsOutOfRange(tokenDecimals));
169
- require(tokenAgents.length <= 5, ErrorsLib.MaxAgentsReached(5));
170
123
 
171
124
  __ERC20_init(tokenName, tokenSymbol);
172
125
  __ERC20Permit_init(tokenName);
173
126
  __Pausable_init();
174
- __Ownable_init(owner);
127
+ __AccessManaged_init(accessManagerAddress);
175
128
 
176
- TokenStorage storage s = _tokenStorage();
177
- s.name = tokenName;
178
- s.symbol = tokenSymbol;
179
- s.decimals = tokenDecimals;
180
- s.onchainId = onchainIdAddress;
129
+ TokenLedgerLib.layout().decimals = tokenDecimals;
130
+ _initERC3643(identityRegistryAddress, complianceAddress, onchainIdAddress);
181
131
 
182
- s.identityRegistry = IERC3643IdentityRegistry(identityRegistryAddress);
183
- s.compliance = IERC3643Compliance(complianceAddress);
184
- _emitUpdatedTokenInformation();
185
-
186
- for (uint256 i = 0; i < tokenAgents.length; i++) {
187
- _addAgent(tokenAgents[i]);
188
- }
132
+ // The network's registry, fixed for the token's lifetime: no role can move it afterwards.
133
+ _setTrustedGatewayRegistry(trustedGatewayRegistryAddress);
189
134
 
190
135
  _pause();
191
136
  }
192
137
 
193
138
  /* ----- Main token properties ----- */
194
139
 
195
- /// @inheritdoc IERC3643
196
- function setName(string calldata tokenName) external override onlyOwner {
197
- require(bytes(tokenName).length > 0, ErrorsLib.EmptyString());
198
- _tokenStorage().name = tokenName;
199
- _emitUpdatedTokenInformation();
200
- }
201
-
202
- /// @inheritdoc IERC3643
203
- function setSymbol(string calldata tokenSymbol) external override onlyOwner {
204
- require(bytes(tokenSymbol).length > 0, ErrorsLib.EmptyString());
205
- _tokenStorage().symbol = tokenSymbol;
206
- _emitUpdatedTokenInformation();
207
- }
208
-
209
- /// @inheritdoc IERC3643
210
- /// @dev if _onchainID is set at zero address it means no ONCHAINID is bound to this token
211
- function setOnchainID(address onchainIdAddress) external override onlyOwner {
212
- _tokenStorage().onchainId = onchainIdAddress;
213
- _emitUpdatedTokenInformation();
140
+ /// @inheritdoc IERC20Metadata
141
+ /// @dev {IToken} re-declares the ERC-3643 surface, so `IERC20Metadata` reaches this contract by a
142
+ /// second path and has to be named among the overridden bases.
143
+ function decimals() public view override(ERC3643Token, ERC20Upgradeable, IERC20Metadata) returns (uint8) {
144
+ return TokenLedgerLib.layout().decimals;
214
145
  }
215
146
 
216
147
  /// @inheritdoc IERC3643
217
- function setIdentityRegistry(address _identityRegistry) public override onlyOwner {
218
- require(_identityRegistry != address(0), ErrorsLib.ZeroAddress());
219
-
220
- _tokenStorage().identityRegistry = IERC3643IdentityRegistry(_identityRegistry);
221
- emit ERC3643EventsLib.IdentityRegistryAdded(_identityRegistry);
148
+ /// @dev Required disambiguation between the {IToken} declaration and the base's implementation;
149
+ /// the pause state itself lives in `PausableUpgradeable` and nothing is added here.
150
+ function paused() public view override(ERC3643Token, IERC3643) returns (bool) {
151
+ return super.paused();
222
152
  }
223
153
 
224
- /// @inheritdoc IERC3643
225
- function setCompliance(address _compliance) public override onlyOwner {
226
- require(_compliance != address(0), ErrorsLib.ZeroAddress());
154
+ /* ----- Interop Configuration ----- */
227
155
 
228
- TokenStorage storage s = _tokenStorage();
229
- if (address(s.compliance) != address(0)) {
230
- s.compliance.unbindToken(address(this));
231
- }
232
- s.compliance = IERC3643Compliance(_compliance);
233
- s.compliance.bindToken(address(this));
234
- emit ERC3643EventsLib.ComplianceAdded(_compliance);
156
+ /// @inheritdoc ITREXMessaging
157
+ function setRoute(bytes2 chainType, bytes calldata chainReference, address gateway) external restricted {
158
+ _setRoute(chainType, chainReference, gateway);
235
159
  }
236
160
 
237
- /// @inheritdoc IERC20Metadata
238
- function name() public view override(ERC20Upgradeable, IERC20Metadata) returns (string memory) {
239
- return _tokenStorage().name;
161
+ /// @inheritdoc ITREXMessaging
162
+ function setPeer(bytes32 chainKey, bytes calldata peer) external restricted {
163
+ _setPeer(chainKey, peer);
240
164
  }
241
165
 
242
- /// @inheritdoc IERC20Metadata
243
- function symbol() public view override(ERC20Upgradeable, IERC20Metadata) returns (string memory) {
244
- return _tokenStorage().symbol;
245
- }
166
+ /* ----- Interop Dispatch ----- */
246
167
 
247
- /// @inheritdoc IERC20Metadata
248
- function decimals() public view override(ERC20Upgradeable, IERC20Metadata) returns (uint8) {
249
- return _tokenStorage().decimals;
250
- }
168
+ /// @dev Sends a compliance validation to this token's peer on `chainKey`, pinning the route it took.
169
+ ///
170
+ /// The reference side has two contracts with something to say, the compliance and the token, but
171
+ /// the wire has one author: the token. Compliance therefore dispatches through here, and the peer
172
+ /// only ever has to trust a single reference address. A cross-chain validation is dispatched once
173
+ /// per involved chain, under the same `validationId`, and each leg pins its own route.
174
+ ///
175
+ /// Callable by the bound compliance alone. No role opens this door: a validation body and the id it
176
+ /// travels under are the compliance's to author, and a human holding the selector could otherwise
177
+ /// forge either, or pin a route under an id the compliance has not reached yet. Reverts when the
178
+ /// chain was never opened, or when this validation already went out toward `chainKey` through
179
+ /// another gateway.
180
+ function dispatchComplianceValidation(bytes32 chainKey, uint256 validationId, bytes calldata body)
181
+ external
182
+ returns (bytes32)
183
+ {
184
+ require(_msgSender() == address(_getCompliance()), ErrorsLib.SenderNotCompliance(_msgSender()));
251
185
 
252
- /// @inheritdoc IERC3643
253
- function onchainID() external view override returns (address) {
254
- return _tokenStorage().onchainId;
186
+ return _sendComplianceValidation(chainKey, validationId, body);
255
187
  }
256
188
 
257
- /// @inheritdoc IERC3643
258
- function identityRegistry() external view override returns (IERC3643IdentityRegistry) {
259
- return _tokenStorage().identityRegistry;
260
- }
189
+ /// @inheritdoc IToken
190
+ /// @dev The native burn happens here, the only part the library cannot reach; {TokenDelegationLib-delegateOut}
191
+ /// then checks the burn stayed inside the free balance, credits the bridged position, checks the wallets, tells
192
+ /// the compliance, commits and sends the instruction. One transaction, so a refusal anywhere undoes the burn,
193
+ /// and the satellite is never told to mint what this chain still holds. It is the only way a native position
194
+ /// reaches a satellite, and `totalSupply` never moves.
195
+ function delegateOut(address holder, bytes calldata toWallet, uint256 amount)
196
+ external
197
+ whenNotPaused
198
+ nonReentrant
199
+ returns (bytes32)
200
+ {
201
+ ITREXRegistry registry = ITREXRegistry(address(_getIdentityRegistry()));
202
+ if (_msgSender() != holder && _msgSender() != address(registry.identity(holder))) {
203
+ _checkCanCallSelector(this.delegateOut.selector);
204
+ }
205
+ require(!_isFrozen(holder), ErrorsLib.FrozenWallet(holder));
261
206
 
262
- /// @inheritdoc IERC3643
263
- function compliance() external view override returns (IERC3643Compliance) {
264
- return _tokenStorage().compliance;
265
- }
207
+ ERC20Upgradeable._update(holder, address(0), amount);
266
208
 
267
- /// @inheritdoc IERC3643
268
- function version() public pure override returns (string memory) {
269
- return VERSION;
209
+ return TokenDelegationLib.delegateOut(holder, toWallet, amount);
270
210
  }
271
211
 
272
- function _EIP712Name() internal view override returns (string memory) {
273
- return name();
212
+ /// @inheritdoc IToken
213
+ /// @dev No pause guard: an instruction moves nothing here. The proof that answers it is applied only once the
214
+ /// token is unpaused, and stays deliverable until then.
215
+ function instructRecall(bytes calldata wallet, uint256 amount, address nativeWallet)
216
+ external
217
+ restricted
218
+ returns (uint256)
219
+ {
220
+ return TokenDelegationLib.instructRecall(wallet, amount, nativeWallet);
274
221
  }
275
222
 
276
- /* ----- Pause Functions ----- */
277
-
278
- /// @inheritdoc IERC3643
279
- function pause() external override onlyAgent whenNotPaused {
280
- require(
281
- !getAgentRestrictions(_msgSender()).disablePause,
282
- ErrorsLib.AgentNotAuthorized(_msgSender(), "pause disabled")
283
- );
284
-
285
- _pause();
223
+ /// @inheritdoc IToken
224
+ /// @dev No pause guard, like {instructRecall}: a resend moves nothing.
225
+ function resend(uint8 kind, uint256 id, bytes calldata data) external restricted returns (bytes32) {
226
+ return TokenDelegationLib.resend(kind, id, data);
286
227
  }
287
228
 
288
- /// @inheritdoc IERC3643
289
- function unpause() external override onlyAgent whenPaused {
290
- require(
291
- !getAgentRestrictions(_msgSender()).disablePause,
292
- ErrorsLib.AgentNotAuthorized(_msgSender(), "pause disabled")
293
- );
294
-
295
- _unpause();
229
+ /// @inheritdoc IToken
230
+ function settleValidation(bytes calldata from, bytes calldata to, uint256 amount, uint256 validationId)
231
+ external
232
+ whenNotPaused
233
+ {
234
+ _requireBoundCompliance();
235
+ _settle(from, to, amount, validationId);
296
236
  }
297
237
 
298
- /// @inheritdoc IERC3643
299
- function paused() public view override(PausableUpgradeable, IERC3643) returns (bool) {
300
- return super.paused();
238
+ /// @inheritdoc IToken
239
+ function holdInTransit(bytes calldata from, uint256 amount, uint256 validationId, uint256 reserved)
240
+ external
241
+ whenNotPaused
242
+ {
243
+ _requireBoundCompliance();
244
+ TokenLedgerLib.holdInTransit(from, amount, validationId, reserved);
301
245
  }
302
246
 
303
- /* ----- Minting & Burning Functions ----- */
247
+ /* ----- Ledger Views ----- */
304
248
 
305
- /// @inheritdoc IERC3643
306
- function mint(address to, uint256 amount) public override onlyAgent {
307
- require(
308
- !getAgentRestrictions(_msgSender()).disableMint, ErrorsLib.AgentNotAuthorized(_msgSender(), "mint disabled")
309
- );
310
- _mint(to, amount);
249
+ /// @inheritdoc IERC20
250
+ /// @dev The whole issuance: the native ERC-20 supply plus every position on a satellite. A delegation-out, a
251
+ /// recall or either native-side settlement leg moves between the two terms and never changes the sum; only a
252
+ /// mint or a burn does.
253
+ ///
254
+ /// The register reports the issuance, not the native float, and the events say so at the cost of one
255
+ /// trade-off. A native-to-bridged move emits `Transfer(holder, 0x0)` deliberately: that is what makes
256
+ /// `balanceOf` drop visibly and keeps every ERC-20 balance indexer correct. The price is that a supply
257
+ /// derived by summing `Transfer` events under-reports by `totalBridged`; `DelegatedOut`, `Recalled` and
258
+ /// `SettledToNative` are the reconciliation for anyone deriving it that way, and
259
+ /// `totalSupply() - totalBridged()` is the native float. An escrow address holding the delegated float
260
+ /// would keep Transfer-summing whole and was rejected: it would show the token holding its own supply.
261
+ /// `INV-7` sums the buckets to this figure and asserts that escrow is never there; `INV-8` holds
262
+ /// `totalBridged` to the positions, whichever transition moved it.
263
+ function totalSupply() public view override(ERC20Upgradeable, IERC20) returns (uint256) {
264
+ return super.totalSupply() + TokenLedgerLib.layout().totalBridged;
311
265
  }
312
266
 
313
- /// @inheritdoc IERC3643
314
- function burn(address from, uint256 amount) public override onlyAgent {
315
- require(
316
- !getAgentRestrictions(_msgSender()).disableBurn, ErrorsLib.AgentNotAuthorized(_msgSender(), "burn disabled")
317
- );
318
- _burn(from, amount);
267
+ /// @inheritdoc IToken
268
+ function freeBalanceOf(address wallet) public view returns (uint256) {
269
+ return balanceOf(wallet) - _getFrozenTokens(wallet);
319
270
  }
320
271
 
321
- /// @inheritdoc IERC3643
322
- function batchMint(address[] calldata tos, uint256[] calldata amounts) external override {
323
- for (uint256 i = 0; i < tos.length; i++) {
324
- mint(tos[i], amounts[i]);
325
- }
272
+ /// @inheritdoc IToken
273
+ function bridgedBalanceOf(bytes calldata wallet) external view returns (uint256) {
274
+ return TokenLedgerLib.bridgedBalanceOf(wallet);
326
275
  }
327
276
 
328
- /// @inheritdoc IERC3643
329
- function batchBurn(address[] calldata froms, uint256[] calldata amounts) external override {
330
- for (uint256 i = 0; i < froms.length; i++) {
331
- burn(froms[i], amounts[i]);
332
- }
277
+ /// @inheritdoc IToken
278
+ function returnHeldInTransit(bytes calldata to, uint256 validationId) external whenNotPaused {
279
+ _requireBoundCompliance();
280
+ TokenLedgerLib.returnHeldInTransit(to, validationId);
333
281
  }
334
282
 
335
- /* ----- Freezing Functions ----- */
336
-
337
- /// @inheritdoc IERC3643
338
- function freezePartialTokens(address user, uint256 amount) public override onlyAgent {
339
- require(
340
- !getAgentRestrictions(_msgSender()).disablePartialFreeze,
341
- ErrorsLib.AgentNotAuthorized(_msgSender(), "partial freeze disabled")
342
- );
343
-
344
- TokenStorage storage s = _tokenStorage();
345
- uint256 balance = balanceOf(user);
346
- require(
347
- balance >= s.frozenStatus[user].amount + amount,
348
- IERC20Errors.ERC20InsufficientBalance(user, balance, amount)
349
- );
350
- s.frozenStatus[user].amount += amount;
351
- emit ERC3643EventsLib.TokensFrozen(user, amount);
283
+ /// @inheritdoc IToken
284
+ function reservedOf(bytes calldata wallet) external view returns (uint256) {
285
+ return TokenLedgerLib.reservedOf(wallet);
352
286
  }
353
287
 
354
- /// @inheritdoc IERC3643
355
- function unfreezePartialTokens(address user, uint256 amount) public override onlyAgent {
356
- require(
357
- !getAgentRestrictions(_msgSender()).disablePartialFreeze,
358
- ErrorsLib.AgentNotAuthorized(_msgSender(), "partial freeze disabled")
359
- );
360
-
361
- TokenStorage storage s = _tokenStorage();
362
-
363
- require(
364
- s.frozenStatus[user].amount >= amount,
365
- ErrorsLib.AmountAboveFrozenTokens(amount, s.frozenStatus[user].amount)
366
- );
367
- s.frozenStatus[user].amount -= amount;
368
- emit ERC3643EventsLib.TokensUnfrozen(user, amount);
288
+ /// @inheritdoc IToken
289
+ function availableOf(bytes calldata wallet) public view returns (uint256) {
290
+ return TokenLedgerLib.availableOf(wallet);
369
291
  }
370
292
 
371
- /// @inheritdoc IERC3643
372
- function setAddressFrozen(address user, bool freeze) public override onlyAgent {
373
- require(
374
- !getAgentRestrictions(_msgSender()).disableAddressFreeze,
375
- ErrorsLib.AgentNotAuthorized(_msgSender(), "address freeze disabled")
376
- );
377
-
378
- _tokenStorage().frozenStatus[user].addressFrozen = freeze;
379
-
380
- emit ERC3643EventsLib.AddressFrozen(user, freeze, _msgSender());
293
+ /// @inheritdoc IToken
294
+ /// @dev No pause guard: a reservation moves no tokens, it only records what a validation may later draw.
295
+ /// Issuance itself is allowed while the token is paused, and the reservation has to follow it, or a paused
296
+ /// token would issue validations with nothing held against the wallet they draw from.
297
+ function reserveForValidation(bytes calldata wallet, uint256 amount) external {
298
+ _requireBoundCompliance();
299
+ TokenLedgerLib.reserve(wallet, amount);
381
300
  }
382
301
 
383
- /// @inheritdoc IERC3643
384
- function batchFreezePartialTokens(address[] calldata users, uint256[] calldata amounts) external {
385
- for (uint256 i = 0; i < users.length; i++) {
386
- freezePartialTokens(users[i], amounts[i]);
387
- }
302
+ /// @inheritdoc IToken
303
+ /// @dev No pause guard, for the reason `reserveForValidation` gives: a discard while the token is paused
304
+ /// must still give the wallet its room back.
305
+ function releaseFromValidation(bytes calldata wallet, uint256 amount) external {
306
+ _requireBoundCompliance();
307
+ TokenLedgerLib.release(wallet, amount);
388
308
  }
389
309
 
390
- /// @inheritdoc IERC3643
391
- function batchUnfreezePartialTokens(address[] calldata users, uint256[] calldata amounts) external override {
392
- for (uint256 i = 0; i < users.length; i++) {
393
- unfreezePartialTokens(users[i], amounts[i]);
394
- }
310
+ /// @inheritdoc IToken
311
+ function totalBridged() external view returns (uint256) {
312
+ return TokenLedgerLib.layout().totalBridged;
395
313
  }
396
314
 
397
- /// @inheritdoc IERC3643
398
- function batchSetAddressFrozen(address[] calldata users, bool[] calldata freezes) external override {
399
- for (uint256 i = 0; i < users.length; i++) {
400
- setAddressFrozen(users[i], freezes[i]);
401
- }
315
+ /// @inheritdoc IToken
316
+ function inTransitOf(uint256 validationId) external view returns (uint256) {
317
+ return TokenLedgerLib.layout().inTransit[validationId];
402
318
  }
403
319
 
404
- /// @inheritdoc IERC3643
405
- function isFrozen(address user) external view override returns (bool) {
406
- return _tokenStorage().frozenStatus[user].addressFrozen;
320
+ /// @inheritdoc IToken
321
+ function totalInTransit() external view returns (uint256) {
322
+ return TokenLedgerLib.layout().totalInTransit;
407
323
  }
408
324
 
409
- /// @inheritdoc IERC3643
410
- function getFrozenTokens(address user) external view override returns (uint256) {
411
- return _tokenStorage().frozenStatus[user].amount;
325
+ /// @inheritdoc IToken
326
+ function pendingRecall(uint256 recallId) external view returns (TokenLedgerLib.PendingRecall memory) {
327
+ return TokenLedgerLib.layout().recalls[recallId];
412
328
  }
413
329
 
414
- /* ----- Recovery Functions ----- */
330
+ /* ----- Transfer Functions ----- */
415
331
 
416
- /// @inheritdoc IERC3643
417
- function recoveryAddress(address lostWallet, address newWallet, address investorOnchainId)
418
- external
419
- override
420
- onlyAgent
332
+ /// @inheritdoc IERC20
333
+ /// @dev The bound modules vet the spender before the allowance is spent: a `SPENDER` module may refuse
334
+ /// the caller even when the transfer itself would comply.
335
+ /// A direct {transfer} never reaches this path, so it carries no spender check and no extra gas.
336
+ /// @param from address the tokens are taken from
337
+ /// @param to address the tokens are sent to
338
+ /// @param value amount of tokens moved
339
+ /// @return true when the transfer succeeded
340
+ function transferFrom(address from, address to, uint256 value)
341
+ public
342
+ override(ERC20Upgradeable, IERC20)
421
343
  returns (bool)
422
344
  {
423
345
  require(
424
- !getAgentRestrictions(_msgSender()).disableRecovery,
425
- ErrorsLib.AgentNotAuthorized(_msgSender(), "recovery disabled")
346
+ IModularCompliance(address(_getCompliance())).canSpenderCall(_msgSender(), from, to, value),
347
+ ErrorsLib.SpenderNotAllowed(_msgSender(), from, to, value)
426
348
  );
427
349
 
428
- TokenStorage storage s = _tokenStorage();
429
-
430
- uint256 investorTokens = balanceOf(lostWallet);
431
- require(investorTokens != 0, ErrorsLib.NoTokenToRecover());
350
+ return super.transferFrom(from, to, value);
351
+ }
352
+
353
+ /// @notice Moves tokens out of a wallet on behalf of the investor's own identity.
354
+ /// @dev The identity itself must be the caller: it is an ERC-7579 account, so the call already carries
355
+ /// the account's own authentication. A key holder calling the token directly is just another caller.
356
+ /// @dev No allowance is read or written, and the spender gate never runs: it vets third-party spenders,
357
+ /// and the owner's own identity is not one. `approve`, `transferFrom` and `permit` stay plain ERC-20.
358
+ /// @dev Carries no revocation gate of its own. A wallet revoked in ONCHAINID still resolves here whenever
359
+ /// it holds a local registration, and it can still {transfer} out, so gating this path alone would be
360
+ /// bypassable rather than protective. Revoked wallets are a token-wide policy question, not this
361
+ /// function's.
362
+ /// @param from wallet the tokens are taken from, linked to the calling identity
363
+ /// @param to address the tokens are sent to
364
+ /// @param amount number of tokens moved
365
+ /// @return true when the transfer succeeded
366
+ function identityTransfer(address from, address to, uint256 amount) external returns (bool) {
367
+ // An unlinked wallet resolves to the zero identity. No caller can be the zero address, so the sender
368
+ // check alone already rejects it; the explicit guard keeps the zero identity from ever authorizing
369
+ // itself if `_msgSender()` is later overridden.
370
+ IIdentity identity = _getIdentityRegistry().identity(from);
432
371
  require(
433
- s.identityRegistry.contains(lostWallet) || s.identityRegistry.contains(newWallet),
434
- ErrorsLib.RecoveryNotPossible()
372
+ address(identity) != address(0) && _msgSender() == address(identity),
373
+ ErrorsLib.NotLinkedIdentity(from, _msgSender())
435
374
  );
436
-
437
- uint256 frozenTokens = s.frozenStatus[lostWallet].amount;
438
- _forceUpdate(lostWallet, newWallet, investorTokens);
439
-
440
- if (frozenTokens > 0) {
441
- s.frozenStatus[newWallet].amount += frozenTokens;
442
- emit ERC3643EventsLib.TokensFrozen(newWallet, frozenTokens);
443
- }
444
-
445
- if (s.frozenStatus[lostWallet].addressFrozen) {
446
- s.frozenStatus[lostWallet].addressFrozen = false;
447
- emit ERC3643EventsLib.AddressFrozen(lostWallet, false, address(this));
448
-
449
- if (!s.frozenStatus[newWallet].addressFrozen) {
450
- s.frozenStatus[newWallet].addressFrozen = true;
451
- emit ERC3643EventsLib.AddressFrozen(newWallet, true, address(this));
452
- }
453
- }
454
- if (s.identityRegistry.contains(lostWallet)) {
455
- if (!s.identityRegistry.contains(newWallet)) {
456
- s.identityRegistry
457
- .registerIdentity(
458
- newWallet, IIdentity(investorOnchainId), s.identityRegistry.investorCountry(lostWallet)
459
- );
460
- }
461
- s.identityRegistry.deleteIdentity(lostWallet);
462
- }
463
-
464
- emit ERC3643EventsLib.RecoverySuccess(lostWallet, newWallet, investorOnchainId);
375
+ _transfer(from, to, amount);
376
+ // Emitted after the move so the operator event follows `Transfer`, the ordering {_forcedTransfer} keeps.
377
+ emit EventsLib.IdentityTransfer(address(identity), from, to, amount);
465
378
 
466
379
  return true;
467
380
  }
468
381
 
469
- /* ----- Transfer Functions ----- */
382
+ /* ----- Ledger Transitions ----- */
470
383
 
471
- /// @inheritdoc IERC3643
472
- function forcedTransfer(address from, address to, uint256 amount) public override onlyAgent returns (bool) {
473
- require(
474
- !getAgentRestrictions(_msgSender()).disableForceTransfer,
475
- ErrorsLib.AgentNotAuthorized(_msgSender(), "force transfer disabled")
476
- );
477
- TokenStorage storage s = _tokenStorage();
478
- require(s.identityRegistry.isVerified(to), ErrorsLib.UnverifiedIdentity());
479
- _forceUpdate(from, to, amount);
480
- s.compliance.transferred(from, to, amount);
481
- return true;
482
- }
384
+ // Pause policy for everything below: the transitions move balances without {_update} and check no pause
385
+ // themselves; the entry points that reach them do. Those are `_handleSettlement`, `settleValidation`,
386
+ // `holdInTransit`, `delegateOut` and `_handleBurnProof`, each of which requires the token not to be paused,
387
+ // so that the pause halts every movement between wallets, native or satellite, while mints and burns stay
388
+ // allowed.
483
389
 
484
- /// @inheritdoc IERC3643
485
- function batchTransfer(address[] calldata tos, uint256[] calldata amounts) external override {
486
- for (uint256 i = 0; i < tos.length; i++) {
487
- transfer(tos[i], amounts[i]);
488
- }
489
- }
390
+ /// @dev Applies the settled leg of a validation: `from`'s satellite position down, and either `to`'s free
391
+ /// balance up when `to` is on the reference chain (a native mint, `Transfer(0x0, to)`, and a distinct event
392
+ /// because ownership moves between identities), or `to`'s satellite position up otherwise (a bridged
393
+ /// transfer, nothing native). `validationId` is the validation the settlement consumed. The calling flow
394
+ /// owns the lifecycle; the ledger checks the buckets and the envelopes only. There is no mirror leaving a
395
+ /// native wallet: the compliance issues no validation whose sender is native, so the satellite executing
396
+ /// one always holds the position it moves. The one path every settlement takes, {settleValidation} adding
397
+ /// only the caller and pause checks.
398
+ function _settle(bytes calldata from, bytes calldata to, uint256 amount, uint256 validationId) internal {
399
+ (bool toNative, address recipient, bytes32 fromKey) = TokenLedgerLib.settle(from, to, amount, validationId);
400
+ if (!toNative) return;
490
401
 
491
- /// @inheritdoc IERC3643
492
- function batchForcedTransfer(address[] calldata froms, address[] calldata tos, uint256[] calldata amounts)
493
- external
494
- override
495
- {
496
- for (uint256 i = 0; i < froms.length; i++) {
497
- forcedTransfer(froms[i], tos[i], amounts[i]);
498
- }
499
- }
402
+ ERC20Upgradeable._update(address(0), recipient, amount);
500
403
 
501
- /* ----- Default Allowance Functions ----- */
404
+ emit EventsLib.SettledToNative(fromKey, recipient, validationId, from, amount);
405
+ }
502
406
 
503
- /// @inheritdoc IToken
504
- function setAllowanceForAll(address[] calldata targets, bool allow) external override onlyOwner {
505
- uint256 targetsCount = targets.length;
506
- require(targetsCount <= 100, ErrorsLib.ArraySizeLimited(100));
507
-
508
- TokenStorage storage s = _tokenStorage();
509
- for (uint256 i = 0; i < targetsCount; i++) {
510
- require(s.defaultAllowances[targets[i]] != allow, ErrorsLib.DefaultAllowanceAlreadySet(targets[i], allow));
511
- s.defaultAllowances[targets[i]] = allow;
512
- emit EventsLib.DefaultAllowanceUpdated(targets[i], allow, _msgSender());
513
- }
407
+ /// @dev The ledger entry points only the bound compliance may call, which classified the movement first.
408
+ function _requireBoundCompliance() private view {
409
+ require(_msgSender() == address(_getCompliance()), ErrorsLib.OnlyBoundCompliance());
514
410
  }
515
411
 
516
- /// @inheritdoc IToken
517
- function setDefaultAllowance(bool allow) external override {
518
- TokenStorage storage s = _tokenStorage();
519
- address sender = _msgSender();
520
- require(s.defaultAllowanceOptOuts[sender] == allow, ErrorsLib.DefaultAllowanceOptOutAlreadySet(sender, allow));
412
+ /* ----- Utility Functions ----- */
521
413
 
522
- s.defaultAllowanceOptOuts[sender] = !allow;
523
- emit EventsLib.DefaultAllowanceOptOutUpdated(sender, !allow);
414
+ /// @inheritdoc AccessManagedOwnableBase
415
+ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
416
+ return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC3643).interfaceId
417
+ || interfaceId == type(IERC20Permit).interfaceId || super.supportsInterface(interfaceId);
524
418
  }
525
419
 
526
- /// @inheritdoc IERC20
527
- function allowance(address _owner, address _spender)
528
- public
529
- view
530
- override(ERC20Upgradeable, IERC20)
531
- returns (uint256)
532
- {
533
- TokenStorage storage s = _tokenStorage();
534
- if (s.defaultAllowances[_spender] && !s.defaultAllowanceOptOuts[_owner]) {
535
- return type(uint256).max;
536
- }
420
+ /* ----- Layer-2 hook implementations ----- */
537
421
 
538
- return super.allowance(_owner, _spender);
422
+ /// @dev Required disambiguation between `ERC3643Token` and `ERC20Upgradeable`; the ERC-3643 rules
423
+ /// live in the former, so `super` resolves there first and nothing is added here.
424
+ function _update(address from, address to, uint256 value) internal override(ERC3643Token, ERC20Upgradeable) {
425
+ super._update(from, to, value);
539
426
  }
540
427
 
541
- /* ----- Agent Restrictions Functions ----- */
542
-
543
- /// @inheritdoc IToken
544
- function setAgentRestrictions(address agent, TokenRoles memory restrictions) external override onlyOwner {
545
- if (!isAgent(agent)) {
546
- revert ErrorsLib.AddressNotAgent(agent);
547
- }
548
- _tokenStorage().agentsRestrictions[agent] = restrictions;
549
- emit EventsLib.AgentRestrictionsSet(
550
- agent,
551
- restrictions.disableMint,
552
- restrictions.disableBurn,
553
- restrictions.disableAddressFreeze,
554
- restrictions.disableForceTransfer,
555
- restrictions.disablePartialFreeze,
556
- restrictions.disablePause,
557
- restrictions.disableRecovery
558
- );
428
+ function _checkTokenAdmin(bytes4 selector) internal override {
429
+ _checkCanCallSelector(selector);
559
430
  }
560
431
 
561
- /// @inheritdoc IToken
562
- function getAgentRestrictions(address agent) public view override returns (TokenRoles memory) {
563
- return _tokenStorage().agentsRestrictions[agent];
432
+ /// @dev T-REX rejects an empty name. Changing it rotates the EIP-712 domain separator,
433
+ /// invalidating outstanding ERC-2612 permit signatures.
434
+ function _setName(string memory tokenName) internal override {
435
+ require(bytes(tokenName).length > 0, ErrorsLib.EmptyString());
436
+ super._setName(tokenName);
564
437
  }
565
438
 
566
- /* ----- ERC2771 Context Functions ----- */
439
+ /// @dev T-REX rejects an empty symbol.
440
+ function _setSymbol(string memory tokenSymbol) internal override {
441
+ require(bytes(tokenSymbol).length > 0, ErrorsLib.EmptyString());
442
+ super._setSymbol(tokenSymbol);
443
+ }
444
+
445
+ /// @dev Adds T-REX validation to the standard setter. A wrong registry halts the token, since
446
+ /// `isVerified` is called on every transfer, so the target must advertise the standard interface
447
+ /// and share this token's authority. `onlySharedAuthority` is a misconfiguration guard only:
448
+ /// `authority()` is spoofable.
449
+ ///
450
+ /// A token with supply keeps its registry. The compliance attributes every position through it, so a
451
+ /// registry that binds wallets differently would leave positions under identities no wallet resolves
452
+ /// to any more. Wallet bindings are changed in the registry the token has, never by swapping it.
453
+ function _setIdentityRegistry(address identityRegistryAddress)
454
+ internal
455
+ override
456
+ onlySharedAuthority(identityRegistryAddress)
457
+ {
458
+ TokenGuardsLib.checkIdentityRegistry(address(_getIdentityRegistry()), identityRegistryAddress, totalSupply());
459
+
460
+ super._setIdentityRegistry(identityRegistryAddress);
461
+ }
462
+
463
+ /// @dev Adds T-REX validation and the bind/unbind handshake to the standard setter. A compliance
464
+ /// already bound to a different token would make every transferred/created/destroyed hook revert
465
+ /// (onlyBoundedToken), silently breaking transfers after the swap.
466
+ ///
467
+ /// A token with supply keeps its compliance. The compliance keeps every identity's position from the
468
+ /// token's first mint and has no seeding step, so a new one would start every holder at zero and every
469
+ /// rule over the ledger would be wrong from the first transfer. A circulating token's compliance is
470
+ /// upgraded in place through its beacon, or changed through its modules.
471
+ function _setCompliance(address complianceAddress) internal override onlySharedAuthority(complianceAddress) {
472
+ TokenGuardsLib.prepareCompliance(address(_getCompliance()), complianceAddress, totalSupply());
473
+
474
+ // The event lands after the bind so that it only ever reports a binding that succeeded.
475
+ _writeCompliance(complianceAddress);
476
+ IERC3643Compliance(complianceAddress).bindToken(address(this));
477
+ emit ComplianceAdded(complianceAddress);
478
+ }
479
+
480
+ /// @dev The standard recovery with the T-REX preconditions in front, a wallet may not be recovered onto
481
+ /// itself, there must be something to recover, at least one of the two wallets must already be known
482
+ /// to the identity registry, and each known wallet must belong to `investorOnchainId`, and the move
483
+ /// reported to the modular compliance as an agent's movement, so the trackers can leave it out of what
484
+ /// they count against the investor. The steps are the base's, see {ERC3643Token-_recoveryAddress}; only
485
+ /// the compliance call differs.
486
+ /// @dev Carries its own `nonReentrant` and `whenNotPaused` because it reimplements the base body instead
487
+ /// of calling `super`, like {_forcedTransfer}.
488
+ function _recoveryAddress(address lostWallet, address newWallet, address investorOnchainId)
489
+ internal
490
+ override
491
+ whenNotPaused
492
+ nonReentrant
493
+ returns (bool)
494
+ {
495
+ uint256 investorTokens = balanceOf(lostWallet);
496
+ TokenRecoveryLib.checkRecovery(_getIdentityRegistry(), lostWallet, newWallet, investorOnchainId, investorTokens);
567
497
 
568
- /// @inheritdoc ERC2771ContextUpgradeable
569
- function trustedForwarder() public view virtual override returns (address) {
570
- return _tokenStorage().trustedForwarder;
571
- }
498
+ uint256 frozenTokens = _erc3643TokenStorage().frozenTokens[lostWallet];
572
499
 
573
- /// @inheritdoc IToken
574
- function setTrustedForwarder(address newTrustedForwarder) external onlyOwner {
575
- _tokenStorage().trustedForwarder = newTrustedForwarder;
500
+ // The new wallet is registered before the move and the lost wallet is deleted after the compliance
501
+ // call, so that during `agentTransferred` both wallets still resolve to the identities that hold and
502
+ // receive the tokens. A module keyed by identity can then debit and credit through the registry.
503
+ bool migrateIdentity = _registerRecoveredWallet(lostWallet, newWallet, investorOnchainId);
576
504
 
577
- emit EventsLib.TrustedForwarderSet(newTrustedForwarder);
578
- }
505
+ _forceUpdate(lostWallet, newWallet, investorTokens);
506
+ _migrateFrozenAmount(newWallet, frozenTokens);
507
+ _migrateAddressFrozen(lostWallet, newWallet);
579
508
 
580
- function _msgSender() internal view override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address) {
581
- return super._msgSender();
582
- }
509
+ IModularCompliance(address(_getCompliance()))
510
+ .agentTransferred(lostWallet, newWallet, investorTokens, MovementKindLib.RECOVERY);
583
511
 
584
- function _msgData() internal view override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) {
585
- return super._msgData();
512
+ if (migrateIdentity) _getIdentityRegistry().deleteIdentity(lostWallet);
513
+
514
+ emit RecoverySuccess(lostWallet, newWallet, investorOnchainId);
515
+ return true;
586
516
  }
587
517
 
588
- function _contextSuffixLength()
518
+ /// @dev Adds the T-REX `ForcedTransfer` event to the standard forced transfer. It is emitted before
519
+ /// the compliance hook so that no module log can land between `Transfer` and this event.
520
+ /// @dev Carries its own `nonReentrant` and `whenNotPaused` because it reimplements the base body
521
+ /// instead of calling `super`, so the base modifiers never run on this path. {_recoveryAddress} does
522
+ /// the same.
523
+ function _forcedTransfer(address from, address to, uint256 amount)
589
524
  internal
590
- view
591
- override(ContextUpgradeable, ERC2771ContextUpgradeable)
592
- returns (uint256)
525
+ override
526
+ whenNotPaused
527
+ nonReentrant
528
+ returns (bool)
593
529
  {
594
- return super._contextSuffixLength();
595
- }
596
-
597
- function _checkIsAgent() internal view override {
598
- require(isAgent(_msgSender()), ErrorsLib.CallerDoesNotHaveAgentRole());
599
- }
600
-
601
- /* ----- Utility Functions ----- */
602
-
603
- /// @inheritdoc IERC165
604
- function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
605
- return interfaceId == type(IERC20).interfaceId || interfaceId == type(IToken).interfaceId
606
- || interfaceId == type(IERC173).interfaceId || interfaceId == type(IERC165).interfaceId
607
- || interfaceId == type(IERC3643).interfaceId || interfaceId == type(IERC20Permit).interfaceId;
530
+ require(_getIdentityRegistry().isVerified(to), ErrorsLib.UnverifiedIdentity());
531
+ _forceUpdate(from, to, amount);
532
+ emit EventsLib.ForcedTransfer(_msgSender());
533
+ // Reported as an agent's movement, so a module counting what the investor does can leave it out.
534
+ IModularCompliance(address(_getCompliance()))
535
+ .agentTransferred(from, to, amount, MovementKindLib.FORCED_TRANSFER);
536
+ return true;
608
537
  }
609
538
 
610
- function _tokenStorage() private pure returns (TokenStorage storage $) {
611
- assembly {
612
- $.slot := TOKEN_STORAGE_LOCATION
613
- }
539
+ /// @dev The new wallet is registered only when it resolves nowhere, so a wallet the global registry
540
+ /// already binds keeps following that binding rather than a local copy. Only local entries can be
541
+ /// deleted, so the lost wallet is reported for deletion only when it is locally registered. Country is
542
+ /// passed as 0 rather than read from the lost wallet, because T-REX stores none; drop this override if
543
+ /// country storage comes back, so the base reads the real value again.
544
+ function _registerRecoveredWallet(address lostWallet, address newWallet, address investorOnchainID)
545
+ internal
546
+ override
547
+ returns (bool)
548
+ {
549
+ return TokenRecoveryLib.registerRecoveredWallet(
550
+ _getIdentityRegistry(), lostWallet, newWallet, investorOnchainID
551
+ );
614
552
  }
615
553
 
616
- function _update(address from, address to, uint256 value) internal override {
617
- TokenStorage storage s = _tokenStorage();
618
- bool isMint = from == address(0);
619
- bool isBurn = to == address(0);
620
-
621
- if (!isMint && !isBurn) {
622
- _requireNotPaused();
623
- require(!s.frozenStatus[from].addressFrozen, ErrorsLib.FrozenWallet(from));
624
- require(!s.frozenStatus[to].addressFrozen, ErrorsLib.FrozenWallet(to));
625
- uint256 freeBalance = balanceOf(from) - s.frozenStatus[from].amount;
626
- require(value <= freeBalance, IERC20Errors.ERC20InsufficientBalance(from, freeBalance, value));
627
- } else if (isBurn) {
628
- _autoUnfreezeFor(from, value);
629
- }
630
-
631
- if (!isBurn) {
632
- require(s.identityRegistry.isVerified(to), ErrorsLib.UnverifiedIdentity());
633
- require(s.compliance.canTransfer(from, to, value), ErrorsLib.ComplianceNotFollowed());
554
+ /// @inheritdoc TREXMessaging
555
+ /// @dev The destination is structural: the bound compliance owns the slot lifecycle, so an attributed
556
+ /// settlement goes there and nowhere else. It is forwarded as decoded, by the linked messaging
557
+ /// library and with the token as the caller; classifying it against the stored validation is the
558
+ /// compliance's business, not the token's.
559
+ ///
560
+ /// While the token is paused nothing is applied: the delivery reverts and stays deliverable, so an
561
+ /// incident under investigation settles nothing. When the compliance reports a replayed or a never-issued
562
+ /// settlement, the token halts itself through its pause: the interop layer is misbehaving and every
563
+ /// notification is suspect until an agent has investigated, resolved and called `unpause`.
564
+ function _handleSettlement(bytes32 chainKey, bytes memory body) internal override whenNotPaused nonReentrant {
565
+ bool halt = TREXMessagingLib.forwardSettlement(address(_getCompliance()), chainKey, body);
566
+ if (halt) _pause();
567
+ }
568
+
569
+ /// @inheritdoc TREXMessaging
570
+ /// @dev The recall path: the proof is judged against the instruction it answers and the bridged position
571
+ /// debited, see {TokenDelegationLib-consumeBurnProof}, then the native wallet that instruction named is
572
+ /// minted to, so a recall never moves ownership or `totalSupply`. Same pause and halt policy as
573
+ /// {_handleSettlement}: a paused token leaves the proof deliverable, and a proof the token cannot account
574
+ /// for pauses it. A duplicate of a settled proof changes nothing.
575
+ function _handleBurnProof(bytes32 chainKey, bytes memory body)
576
+ internal
577
+ virtual
578
+ override
579
+ whenNotPaused
580
+ nonReentrant
581
+ {
582
+ (bool halt, address nativeWallet, uint256 amount) = TokenDelegationLib.consumeBurnProof(chainKey, body);
583
+ if (halt) {
584
+ _pause();
585
+ return;
634
586
  }
635
-
636
- super._update(from, to, value);
637
-
638
- if (isMint) s.compliance.created(to, value);
639
- else if (isBurn) s.compliance.destroyed(from, value);
640
- else s.compliance.transferred(from, to, value);
587
+ if (amount != 0) ERC20Upgradeable._update(address(0), nativeWallet, amount);
641
588
  }
642
589
 
643
- function _forceUpdate(address from, address to, uint256 value) private {
644
- _autoUnfreezeFor(from, value);
645
- super._update(from, to, value);
646
- }
647
-
648
- function _autoUnfreezeFor(address from, uint256 value) private {
649
- TokenStorage storage s = _tokenStorage();
650
- uint256 balance = balanceOf(from);
651
- require(value <= balance, IERC20Errors.ERC20InsufficientBalance(from, balance, value));
652
- uint256 freeBalance = balance - s.frozenStatus[from].amount;
653
- if (value > freeBalance) {
654
- uint256 toUnfreeze = value - freeBalance;
655
- s.frozenStatus[from].amount -= toUnfreeze;
656
- emit ERC3643EventsLib.TokensUnfrozen(from, toUnfreeze);
657
- }
590
+ /// @inheritdoc ERC3643Token
591
+ function _version() internal pure override returns (string memory) {
592
+ return VERSION;
658
593
  }
659
594
 
660
- function _emitUpdatedTokenInformation() internal {
661
- emit ERC3643EventsLib.UpdatedTokenInformation(name(), symbol(), decimals(), VERSION, _tokenStorage().onchainId);
595
+ function _EIP712Name() internal view override returns (string memory) {
596
+ return name();
662
597
  }
663
598
 
664
599
  }