@t-rex-network/onchainid 0.0.0-stage → 3.0.0-beta2

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 (237) hide show
  1. package/LICENSE.md +674 -0
  2. package/NOTICE.md +66 -0
  3. package/README.md +177 -2
  4. package/contracts/Identity.sol +235 -0
  5. package/contracts/IdentityUtilities.sol +269 -0
  6. package/contracts/KeyManager.sol +193 -0
  7. package/contracts/SmartAccount.sol +222 -0
  8. package/contracts/factory/IIdentityFactory.sol +325 -0
  9. package/contracts/factory/IdentityFactory.sol +818 -0
  10. package/contracts/interface/IClaimIssuer.sol +105 -0
  11. package/contracts/interface/IERC734.sol +69 -0
  12. package/contracts/interface/IERC735.sol +149 -0
  13. package/contracts/interface/IIdentity.sol +63 -0
  14. package/contracts/interface/IIdentityUtilities.sol +135 -0
  15. package/contracts/interface/IKeyExecutor.sol +84 -0
  16. package/contracts/libraries/Errors.sol +407 -0
  17. package/contracts/libraries/FormatResolver.sol +74 -0
  18. package/contracts/libraries/Hashing.sol +35 -0
  19. package/contracts/libraries/IdentityTypes.sol +53 -0
  20. package/contracts/libraries/KeyPurposes.sol +49 -0
  21. package/contracts/libraries/KeyTypes.sol +46 -0
  22. package/contracts/modules/claims/EASClaimIssuer.sol +348 -0
  23. package/contracts/modules/executors/KeyApprovalModule.sol +313 -0
  24. package/contracts/modules/executors/RecoveryModule.sol +88 -0
  25. package/contracts/modules/validators/ERC734Validator.sol +1000 -0
  26. package/contracts/modules/validators/ERC7579Validator.sol +74 -0
  27. package/contracts/proxy/IdentityUtilitiesProxy.sol +36 -0
  28. package/contracts/reputation/IReputationRegistry.sol +117 -0
  29. package/contracts/reputation/ReputationRegistry.sol +155 -0
  30. package/contracts/storage/Structs.sol +176 -0
  31. package/contracts/vendor/eas/IEAS.sol +36 -0
  32. package/contracts/vendor/utils/SafeCalldataBatch.sol +61 -0
  33. package/out/AbstractSigner.sol/AbstractSigner.json +1 -0
  34. package/out/AccessControlUpgradeable.sol/AccessControlUpgradeable.json +1 -0
  35. package/out/AccessManaged.sol/AccessManaged.json +1 -0
  36. package/out/AccessManager.sol/AccessManager.json +1 -0
  37. package/out/Account.sol/Account.json +1 -0
  38. package/out/AddClaimByTrustedIssuer.t.sol/AddClaimAsTrustedIssuerTest.json +1 -0
  39. package/out/Address.sol/Address.json +1 -0
  40. package/out/Arrays.sol/Arrays.json +1 -0
  41. package/out/AuthorityUtils.sol/AuthorityUtils.json +1 -0
  42. package/out/Base.sol/CommonBase.json +1 -0
  43. package/out/Base.sol/ScriptBase.json +1 -0
  44. package/out/Base.sol/TestBase.json +1 -0
  45. package/out/Base64.sol/Base64.json +1 -0
  46. package/out/BatchDecodeParity.t.sol/BatchDecodeParityTest.json +1 -0
  47. package/out/BeaconProxy.sol/BeaconProxy.json +1 -0
  48. package/out/Bytes.sol/Bytes.json +1 -0
  49. package/out/Calldata.sol/Calldata.json +1 -0
  50. package/out/ClaimSignatureDefinition.t.sol/ClaimSignatureDefinitionTest.json +1 -0
  51. package/out/ClaimSignatureDefinition.t.sol/NoERC1271Delegate.json +1 -0
  52. package/out/ClaimSignatureDefinition.t.sol/PickyERC1271Delegate.json +1 -0
  53. package/out/ClaimSignerHelper.sol/ClaimSignerHelper.json +1 -0
  54. package/out/ClaimTo.t.sol/ClaimToTest.json +1 -0
  55. package/out/Claims.t.sol/ClaimsTest.json +1 -0
  56. package/out/Claims.t.sol/ExternalIssuer.json +1 -0
  57. package/out/Comparators.sol/Comparators.json +1 -0
  58. package/out/Constants.sol/Constants.json +1 -0
  59. package/out/Context.sol/Context.json +1 -0
  60. package/out/ContextUpgradeable.sol/ContextUpgradeable.json +1 -0
  61. package/out/Create2.sol/Create2.json +1 -0
  62. package/out/Create3.sol/Create3.json +1 -0
  63. package/out/DeployOnchainID.s.sol/DeployOnchainID.json +1 -0
  64. package/out/EASClaimIssuer.sol/EASClaimIssuer.json +1 -0
  65. package/out/EASClaimIssuer.t.sol/EASClaimIssuerTest.json +1 -0
  66. package/out/EASClaimIssuer.t.sol/VmContractHelper29562166e1daff82a9ba4e08c324c14e885cfef135c42b5774ced18642e5fa19.json +1 -0
  67. package/out/EASTypes.sol/IEASTest.json +1 -0
  68. package/out/EASTypes.sol/ISchemaRegistryTest.json +1 -0
  69. package/out/ECDSA.sol/ECDSA.json +1 -0
  70. package/out/EIP712.sol/EIP712.json +1 -0
  71. package/out/ERC165.sol/ERC165.json +1 -0
  72. package/out/ERC165Upgradeable.sol/ERC165Upgradeable.json +1 -0
  73. package/out/ERC1967Proxy.sol/ERC1967Proxy.json +1 -0
  74. package/out/ERC1967Utils.sol/ERC1967Utils.json +1 -0
  75. package/out/ERC4337Utils.sol/ERC4337Utils.json +1 -0
  76. package/out/ERC4337Utils.sol/IEntryPointExtra.json +1 -0
  77. package/out/ERC734Validator.sol/ERC734Validator.json +1 -0
  78. package/out/ERC734Validator.t.sol/ERC734ValidatorTest.json +1 -0
  79. package/out/ERC734Validator.t.sol/PocCounter.json +1 -0
  80. package/out/ERC734Validator.t.sol/VmContractHelper7beb488c9b6c5f9f79178a8ce1e9ea8b7d447a9f1b366d4a3784214e9066b776.json +1 -0
  81. package/out/ERC7579DelayedExecutor.sol/ERC7579DelayedExecutor.json +1 -0
  82. package/out/ERC7579Executor.sol/ERC7579Executor.json +1 -0
  83. package/out/ERC7579Multisig.sol/ERC7579Multisig.json +1 -0
  84. package/out/ERC7579MultisigWeighted.sol/ERC7579MultisigWeighted.json +1 -0
  85. package/out/ERC7579SocialRecoveryExecutor.sol/ERC7579SocialRecoveryExecutor.json +1 -0
  86. package/out/ERC7579Validator.sol/ERC7579Validator.json +1 -0
  87. package/out/ERC7786Recipient.sol/ERC7786Recipient.json +1 -0
  88. package/out/ERC7913WebAuthnVerifier.sol/ERC7913WebAuthnVerifier.json +1 -0
  89. package/out/EnumerableSet.sol/EnumerableSet.json +1 -0
  90. package/out/Errors.sol/Errors.json +1 -0
  91. package/out/Executions.t.sol/ETHReceiver.json +1 -0
  92. package/out/Executions.t.sol/ExecutionsTest.json +1 -0
  93. package/out/Executions.t.sol/RevertingReceiver.json +1 -0
  94. package/out/FormatResolver.sol/FormatResolver.json +1 -0
  95. package/out/Hashes.sol/Hashes.json +1 -0
  96. package/out/IAccessControl.sol/IAccessControl.json +1 -0
  97. package/out/IAccessManaged.sol/IAccessManaged.json +1 -0
  98. package/out/IAccessManager.sol/IAccessManager.json +1 -0
  99. package/out/IAuthority.sol/IAuthority.json +1 -0
  100. package/out/IBeacon.sol/IBeacon.json +1 -0
  101. package/out/IClaimIssuer.sol/IClaimIssuer.json +1 -0
  102. package/out/IEAS.sol/IEAS.json +1 -0
  103. package/out/IERC1271.sol/IERC1271.json +1 -0
  104. package/out/IERC165.sol/IERC165.json +1 -0
  105. package/out/IERC1967.sol/IERC1967.json +1 -0
  106. package/out/IERC4337.sol/IAccount.json +1 -0
  107. package/out/IERC4337.sol/IAccountExecute.json +1 -0
  108. package/out/IERC4337.sol/IAggregator.json +1 -0
  109. package/out/IERC4337.sol/IEntryPoint.json +1 -0
  110. package/out/IERC4337.sol/IEntryPointNonces.json +1 -0
  111. package/out/IERC4337.sol/IEntryPointStake.json +1 -0
  112. package/out/IERC4337.sol/IPaymaster.json +1 -0
  113. package/out/IERC5267.sol/IERC5267.json +1 -0
  114. package/out/IERC734.sol/IERC734.json +1 -0
  115. package/out/IERC734Surface.t.sol/IERC734SurfaceTest.json +1 -0
  116. package/out/IERC735.sol/IERC735.json +1 -0
  117. package/out/IERC7913.sol/IERC7913SignatureVerifier.json +1 -0
  118. package/out/IIdentity.sol/IIdentity.json +1 -0
  119. package/out/IIdentityFactory.sol/IIdentityFactory.json +1 -0
  120. package/out/IIdentityUtilities.sol/IIdentityUtilities.json +1 -0
  121. package/out/IKeyExecutor.sol/IKeyExecutor.json +1 -0
  122. package/out/IMulticall3.sol/IMulticall3.json +1 -0
  123. package/out/IReputationRegistry.sol/IReputationRegistry.json +1 -0
  124. package/out/Identity.sol/Identity.json +1 -0
  125. package/out/IdentityFactory.sol/IdentityFactory.json +1 -0
  126. package/out/IdentityFactory.t.sol/IdentityFactoryTest.json +1 -0
  127. package/out/IdentityFactory.t.sol/VmContractHelper28a7b3ffc37fea8b5c41ecc8f253eb5ab470e21bb0401440d9a55fcb4f8afe5c.json +1 -0
  128. package/out/IdentityHelper.sol/IdentityHelper.json +1 -0
  129. package/out/IdentityHelper.sol/VmContractHelper78387a8fc41a64804f1f0fc2cbba310bbca11e4f057b06dfa169d4c103c08be5.json +1 -0
  130. package/out/IdentityTypes.sol/IdentityTypes.json +1 -0
  131. package/out/IdentityUtilities.sol/IdentityUtilities.json +1 -0
  132. package/out/IdentityUtilities.t.sol/IdentityUtilitiesTest.json +1 -0
  133. package/out/IdentityUtilities.t.sol/VmContractHelper7ed074704942d210565581d7e79e91a1d3425a5a7e758acb90866c42420e726c.json +1 -0
  134. package/out/IdentityUtilitiesProxy.sol/IdentityUtilitiesProxy.json +1 -0
  135. package/out/Init.t.sol/InitTest.json +1 -0
  136. package/out/Init.t.sol/VmContractHelper95bc81f417f4a3acb58eafba49b7834c5e65588c78654308ee428eb7d9276cce.json +1 -0
  137. package/out/Initializable.sol/Initializable.json +1 -0
  138. package/out/InteroperableAddressEncoding.t.sol/InteroperableAddressEncodingTest.json +1 -0
  139. package/out/KeyApprovalModule.sol/IIdentityAccount.json +1 -0
  140. package/out/KeyApprovalModule.sol/KeyApprovalModule.json +1 -0
  141. package/out/KeyApprovalModuleFactoryGuard.t.sol/KeyApprovalModuleFactoryGuardTest.json +1 -0
  142. package/out/KeyManager.sol/KeyManager.json +1 -0
  143. package/out/KeyPurposes.sol/KeyPurposes.json +1 -0
  144. package/out/KeyTypes.sol/KeyTypes.json +1 -0
  145. package/out/Keys.t.sol/KeysTest.json +1 -0
  146. package/out/LowLevelCall.sol/LowLevelCall.json +1 -0
  147. package/out/Math.sol/Math.json +1 -0
  148. package/out/MessageHashUtils.sol/MessageHashUtils.json +1 -0
  149. package/out/MockERC1271Signer.sol/MockERC1271Signer.json +1 -0
  150. package/out/MockERC1271Wallet.sol/MockERC1271Wallet.json +1 -0
  151. package/out/MockERC7786Gateway.sol/MockERC7786Gateway.json +1 -0
  152. package/out/MockERC7913PermissiveVerifier.sol/MockERC7913PermissiveVerifier.json +1 -0
  153. package/out/MockLyingERC734Getter.sol/MockLyingERC734Getter.json +1 -0
  154. package/out/MockStockECDSAValidator.sol/MockStockECDSAValidator.json +1 -0
  155. package/out/Multicall.sol/Multicall.json +1 -0
  156. package/out/Multisig.sol/Multisig.json +1 -0
  157. package/out/Nonces.sol/Nonces.json +1 -0
  158. package/out/OnchainIDSetup.sol/OnchainIDSetup.json +1 -0
  159. package/out/Ownable.sol/Ownable.json +1 -0
  160. package/out/P256.sol/P256.json +1 -0
  161. package/out/Packing.sol/Packing.json +1 -0
  162. package/out/Panic.sol/Panic.json +1 -0
  163. package/out/PrivilegedReentryGuard.t.sol/PocCounter.json +1 -0
  164. package/out/PrivilegedReentryGuard.t.sol/PrivilegedReentryGuardTest.json +1 -0
  165. package/out/Proxy.sol/Proxy.json +1 -0
  166. package/out/Proxy.t.sol/ProxyTest.json +1 -0
  167. package/out/Proxy.t.sol/VmContractHelper20ec29ce959b555228240226871c123d935ae49f617ce49540ee53c85f9f8cd4.json +1 -0
  168. package/out/ProxyPattern.t.sol/ProxyPatternTest.json +1 -0
  169. package/out/RecoveryModule.sol/RecoveryModule.json +1 -0
  170. package/out/RecoveryModule.t.sol/RecoveryModuleTest.json +1 -0
  171. package/out/RecoveryModule.t.sol/VmContractHelper84563bc19cefad0d2824def84f4cab79093d389b1866eff467a2908e14dd8421.json +1 -0
  172. package/out/ReputationRegistry.sol/ReputationRegistry.json +1 -0
  173. package/out/ReputationRegistry.t.sol/FakeIdentity.json +1 -0
  174. package/out/ReputationRegistry.t.sol/ReputationRegistryTest.json +1 -0
  175. package/out/ReputationRegistry.t.sol/VmContractHelper4353cedc5e63171396a0756138ec48ebba489252c7f4fef50b08f9e2c0989ec9.json +1 -0
  176. package/out/RevertingIdentity.sol/RevertingIdentity.json +1 -0
  177. package/out/SafeCalldataBatch.sol/SafeCalldataBatch.json +1 -0
  178. package/out/SafeCast.sol/SafeCast.json +1 -0
  179. package/out/Script.sol/Script.json +1 -0
  180. package/out/ShortStrings.sol/ShortStrings.json +1 -0
  181. package/out/SignatureChecker.sol/SignatureChecker.json +1 -0
  182. package/out/SignedMath.sol/SignedMath.json +1 -0
  183. package/out/SlotDerivation.sol/SlotDerivation.json +1 -0
  184. package/out/SmartAccount.sol/SmartAccount.json +1 -0
  185. package/out/SmartAccount.t.sol/AlwaysApprovePolicy.json +1 -0
  186. package/out/SmartAccount.t.sol/Counter.json +1 -0
  187. package/out/SmartAccount.t.sol/IAddKeyWithData.json +1 -0
  188. package/out/SmartAccount.t.sol/ReentrantUninstaller.json +1 -0
  189. package/out/SmartAccount.t.sol/SmartAccountTest.json +1 -0
  190. package/out/SmartAccount.t.sol/TestExecutor.json +1 -0
  191. package/out/StdAssertions.sol/StdAssertions.json +1 -0
  192. package/out/StdChains.sol/StdChains.json +1 -0
  193. package/out/StdCheats.sol/StdCheats.json +1 -0
  194. package/out/StdCheats.sol/StdCheatsSafe.json +1 -0
  195. package/out/StdConstants.sol/StdConstants.json +1 -0
  196. package/out/StdError.sol/stdError.json +1 -0
  197. package/out/StdInvariant.sol/StdInvariant.json +1 -0
  198. package/out/StdJson.sol/stdJson.json +1 -0
  199. package/out/StdMath.sol/stdMath.json +1 -0
  200. package/out/StdStorage.sol/stdStorage.json +1 -0
  201. package/out/StdStorage.sol/stdStorageSafe.json +1 -0
  202. package/out/StdStyle.sol/StdStyle.json +1 -0
  203. package/out/StdToml.sol/stdToml.json +1 -0
  204. package/out/StdUtils.sol/StdUtils.json +1 -0
  205. package/out/StorageSlot.sol/StorageSlot.json +1 -0
  206. package/out/Strings.sol/Strings.json +1 -0
  207. package/out/Structs.sol/Structs.json +1 -0
  208. package/out/Test.sol/Test.json +1 -0
  209. package/out/TestIdentityUtilities.sol/TestIdentityUtilities.json +1 -0
  210. package/out/Time.sol/Time.json +1 -0
  211. package/out/TokenOid.t.sol/TokenOidTest.json +1 -0
  212. package/out/UUPSUpgradeable.sol/UUPSUpgradeable.json +1 -0
  213. package/out/UnlockedIdentity.sol/UnlockedIdentity.json +1 -0
  214. package/out/UpgradeableBeacon.sol/UpgradeableBeacon.json +1 -0
  215. package/out/VersionUpgrade.t.sol/VersionUpgradeTest.json +1 -0
  216. package/out/Vm.sol/Vm.json +1 -0
  217. package/out/Vm.sol/VmSafe.json +1 -0
  218. package/out/WebAuthn.sol/WebAuthn.json +1 -0
  219. package/out/WebAuthn.t.sol/WebAuthnTest.json +1 -0
  220. package/out/build-info/1056f64abc9637ee.json +1 -0
  221. package/out/console.sol/console.json +1 -0
  222. package/out/draft-AccountERC7579Upgradeable.sol/AccountERC7579Upgradeable.json +1 -0
  223. package/out/draft-ERC7579Utils.sol/ERC7579Utils.json +1 -0
  224. package/out/draft-IERC1822.sol/IERC1822Proxiable.json +1 -0
  225. package/out/draft-IERC7579.sol/IERC7579AccountConfig.json +1 -0
  226. package/out/draft-IERC7579.sol/IERC7579Execution.json +1 -0
  227. package/out/draft-IERC7579.sol/IERC7579Hook.json +1 -0
  228. package/out/draft-IERC7579.sol/IERC7579Module.json +1 -0
  229. package/out/draft-IERC7579.sol/IERC7579ModuleConfig.json +1 -0
  230. package/out/draft-IERC7579.sol/IERC7579Validator.json +1 -0
  231. package/out/draft-IERC7786.sol/IERC7786GatewaySource.json +1 -0
  232. package/out/draft-IERC7786.sol/IERC7786Recipient.json +1 -0
  233. package/out/draft-InteroperableAddress.sol/InteroperableAddress.json +1 -0
  234. package/out/safeconsole.sol/safeconsole.json +1 -0
  235. package/out/src/Test.sol/Test.json +1 -0
  236. package/out/utils/Errors.sol/Errors.json +1 -0
  237. package/package.json +75 -4
@@ -0,0 +1,818 @@
1
+ // SPDX-License-Identifier: GPL-3.0
2
+ //
3
+ // ONCHAINID Smart Contracts
4
+ // Digital identities for the T-REX ecosystem.
5
+ //
6
+ // Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
7
+ //
8
+ // This file is part of the ONCHAINID smart contract suite.
9
+ //
10
+ // This program is free software: you can redistribute it and/or modify
11
+ // it under the terms of the GNU General Public License as published by
12
+ // the Free Software Foundation, either version 3 of the License, or
13
+ // (at your option) any later version.
14
+ //
15
+ // This program is distributed in the hope that it will be useful,
16
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
17
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
+ // GNU General Public License for more details.
19
+ //
20
+ // You should have received a copy of the GNU General Public License
21
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
22
+
23
+ pragma solidity ^0.8.27;
24
+
25
+ import { AccessManaged } from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
26
+ import { IAccessManager } from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
27
+ import { ERC7786Recipient } from "@openzeppelin/contracts/crosschain/ERC7786Recipient.sol";
28
+ import { Nonces } from "@openzeppelin/contracts/utils/Nonces.sol";
29
+ import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
30
+ import { SignatureChecker } from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
31
+ import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
32
+
33
+ import { BeaconProxy } from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
34
+ import { UpgradeableBeacon } from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
35
+
36
+ import { InteroperableAddress } from "@openzeppelin/contracts/utils/draft-InteroperableAddress.sol";
37
+
38
+ import { Identity } from "../Identity.sol";
39
+ import { IIdentity } from "../interface/IIdentity.sol";
40
+ import { Errors } from "../libraries/Errors.sol";
41
+ import { hashAddress } from "../libraries/Hashing.sol";
42
+ import { KeyPurposes } from "../libraries/KeyPurposes.sol";
43
+ import { KeyTypes } from "../libraries/KeyTypes.sol";
44
+ import { Create3 } from "@openzeppelin/contracts/utils/Create3.sol";
45
+
46
+ import { ERC734Validator } from "../modules/validators/ERC734Validator.sol";
47
+ import { Structs } from "../storage/Structs.sol";
48
+ import { IIdentityFactory } from "./IIdentityFactory.sol";
49
+
50
+ /// @title IdentityFactory
51
+ /// @notice Deploys ONCHAINID identity proxies.
52
+ ///
53
+ /// createIdentity: caller deploys for themselves and is auto-linked as the
54
+ /// first wallet. Gated per type by `selfDeployable`. Contract-shaped types
55
+ /// like ASSET and SMART_CONTRACT opt out because the `msg.sender = first
56
+ /// wallet` binding does not apply to them.
57
+ ///
58
+ /// createIdentityFor: caller deploys for another EVM account and must hold the
59
+ /// per-type role. The account signs nothing, which keeps onboarding easy. Instead
60
+ /// it has to end up as the only wallet with MANAGEMENT, so the identity is managed
61
+ /// by the wallet it was created for. Single binding types (ASSET, SMART_CONTRACT)
62
+ /// hold no key, so only the role gate protects them and it must not be PUBLIC_ROLE.
63
+ ///
64
+ /// Admin registers each identity type up front via setIdentityTypePolicy, and the
65
+ /// modules it deploys with via setIdentityTypeModules. Unregistered types revert
66
+ /// from both entry points. Use the AM's PUBLIC_ROLE for open types. Any other role
67
+ /// restricts createIdentityFor to its holders.
68
+ ///
69
+ /// Callers never pass modules. Every identity installs exactly what is registered
70
+ /// for its type, so the admin decides which code runs on an identity and with which
71
+ /// purpose, not whoever pays for the deploy.
72
+ ///
73
+ /// Wallets and signers share the same bytes shape. Bindings are sticky and
74
+ /// revocation is terminal.
75
+ contract IdentityFactory is IIdentityFactory, AccessManaged, EIP712, Nonces, ERC7786Recipient {
76
+
77
+ using EnumerableSet for EnumerableSet.Bytes32Set;
78
+
79
+ /// @dev EIP-712 typehash for wallet → identity link.
80
+ bytes32 private constant _LINK_ACCOUNT_TYPEHASH =
81
+ keccak256("LinkAccount(bytes account,address identity,uint256 nonce,uint256 expiry)");
82
+
83
+ /// @dev CREATE3 salt for the beacon's predetermined slot.
84
+ bytes32 private constant _BEACON_SALT = keccak256("onchainid.beacon.v1");
85
+
86
+ /// @notice OZ UpgradeableBeacon that every BeaconProxy delegates to. Owned by the factory
87
+ /// itself, so upgrades run through {upgradeBeacon}, which is gated by the factory's
88
+ /// current authority. Ownership is a stable anchor (the factory address never
89
+ /// changes) while the real permission follows `authority()`, so an authority
90
+ /// rotation can never leave a stale account able to upgrade every identity.
91
+ /// @dev The address is a CREATE3 slot committed at construction: it depends only on this
92
+ /// factory's address and a fixed salt, so it can be an immutable even though the
93
+ /// beacon itself can only exist after the factory (the beacon needs the Identity
94
+ /// implementation, which needs the enshrined validator, which needs this factory).
95
+ /// {initializeBeacon} deploys it there; identity deployment reverts until then.
96
+ address public immutable beacon;
97
+
98
+ /// @dev One slot per wallet, keyed by keccak256(signer bytes). identity stays set
99
+ /// after revoke (sticky binding). record is written once for getAccounts()
100
+ /// enumeration. status starts at None and is terminal once Revoked.
101
+ struct WalletEntry {
102
+ address identity;
103
+ AccountStatus status;
104
+ bytes record;
105
+ }
106
+
107
+ /// @dev Per-type deploy policy. `registered` carries registration explicitly so
108
+ /// `roleId == 0` (the AM's ADMIN_ROLE) stays usable as a type's required role.
109
+ /// Unregistered types revert from both deploy entry points. `selfDeployable`
110
+ /// gates {createIdentity}. `singleBinding` is true for types that represent a
111
+ /// contract, not a signer (ASSET, SMART_CONTRACT, ...): they keep the one account
112
+ /// set at deploy and can never link or revoke another. uint64 + three bools pack
113
+ /// into one storage slot.
114
+ struct TypePolicy {
115
+ uint64 roleId;
116
+ bool selfDeployable;
117
+ bool singleBinding;
118
+ bool registered;
119
+ }
120
+
121
+ /// @dev Pending cross-chain link proposed via ERC-7786. `identity` is the
122
+ /// ONCHAINID on this chain that the wallet has named. The wallet half of
123
+ /// proof-of-control comes from the authenticated inbound message; the
124
+ /// identity half comes later when the identity itself calls
125
+ /// {settlePendingCrossChainLink}. Until then the link is not active.
126
+ struct PendingLink {
127
+ address identity;
128
+ uint256 expiry;
129
+ }
130
+
131
+ /// @dev EIP-7201 namespaced storage. All mutable state lives here so a future
132
+ /// upgrade won't collide with inherited slots.
133
+ /// @custom:storage-location erc7201:onchainid.IdentityFactory
134
+ struct IdentityFactoryStorage {
135
+ mapping(bytes32 walletKey => WalletEntry entry) wallets;
136
+ mapping(address identity => EnumerableSet.Bytes32Set walletKeys) accounts;
137
+ mapping(address identity => bool deployedByFactory) isFactoryIdentity;
138
+ /// @dev Per-type deploy policy. Unregistered types revert.
139
+ mapping(uint256 identityType => TypePolicy policy) typePolicies;
140
+ /// @dev Gateways trusted per origin chain. The key is
141
+ /// keccak256(chainType, chainReference). Inbound messages from anyone
142
+ /// else are rejected. Manage via {setTrustedGateway}.
143
+ mapping(address gateway => mapping(bytes32 originKey => bool trusted)) trustedGateways;
144
+ /// @dev Approved ERC-7913 verifiers for {linkAccount}. Signers longer than
145
+ /// 20 bytes only link when their verifier is listed here. Manage via
146
+ /// {setTrustedVerifier}.
147
+ mapping(address verifier => bool trusted) trustedVerifiers;
148
+ /// @dev Cross-chain link proposals awaiting identity-side confirmation.
149
+ /// Keyed by {_walletKey} so every encoding of a wallet shares one
150
+ /// pending slot. Cleared on {settlePendingCrossChainLink}, whether the
151
+ /// identity accepts or declines.
152
+ mapping(bytes32 walletKey => PendingLink proposal) pendingLinks;
153
+ /// @dev Modules installed on every identity of a given type, set by the admin via
154
+ /// {setIdentityTypeModules}. Deploy callers pass no modules. This is what makes
155
+ /// the management guarantee in {createIdentityFor} hold, because a caller cannot
156
+ /// install a contract of its own and act through it.
157
+ mapping(uint256 identityType => Structs.ModuleInstall[] modules) typeModules;
158
+ }
159
+
160
+ // keccak256(abi.encode(uint256(keccak256("onchainid.IdentityFactory")) - 1)) & ~bytes32(uint256(0xff))
161
+ bytes32 private constant _IDENTITY_FACTORY_STORAGE_SLOT =
162
+ 0x2cefd7c6aca4efb6085e4a9235cc3be23e6beeb0245cf23a279c1cb689649300;
163
+
164
+ function _storage() private pure returns (IdentityFactoryStorage storage $) {
165
+ bytes32 slot = _IDENTITY_FACTORY_STORAGE_SLOT;
166
+ assembly ("memory-safe") {
167
+ $.slot := slot
168
+ }
169
+ }
170
+
171
+ /// @param initialAuthority AccessManager that backs every `restricted` function here.
172
+ /// @dev The EIP-712 domain version "1" is baked into every wallet link signature made
173
+ /// against this factory. It is not a release marker and does not follow the identity
174
+ /// implementation version.
175
+ constructor(address initialAuthority) AccessManaged(initialAuthority) EIP712("IdentityFactory", "1") {
176
+ require(initialAuthority != address(0), Errors.ZeroAddress());
177
+ beacon = Create3.computeAddress(_BEACON_SALT);
178
+ }
179
+
180
+ /// @inheritdoc IIdentityFactory
181
+ function initializeBeacon(address implementation) external restricted {
182
+ require(implementation != address(0), Errors.ZeroAddress());
183
+ require(beacon.code.length == 0, Errors.BeaconAlreadyInitialized());
184
+ _checkImplementation(implementation, address(0));
185
+ // Own the beacon from the factory. Upgrades then go through {upgradeBeacon}, which the
186
+ // factory's live authority gates, so ownership never has to be re-transferred on an
187
+ // authority rotation.
188
+ address deployed = Create3.deploy(
189
+ 0,
190
+ _BEACON_SALT,
191
+ abi.encodePacked(type(UpgradeableBeacon).creationCode, abi.encode(implementation, address(this)))
192
+ );
193
+ // On chains with a non-canonical CREATE2 derivation (zkSync Era et al.) the beacon lands
194
+ // somewhere other than the address committed in the constructor. Fail loudly instead of
195
+ // leaving the factory permanently pointed at empty code.
196
+ require(deployed == beacon, Errors.BeaconAddressMismatch(beacon, deployed));
197
+ emit BeaconInitialized(implementation);
198
+ }
199
+
200
+ /// @inheritdoc IIdentityFactory
201
+ function upgradeBeacon(address newImplementation, string calldata expectedVersion) external restricted {
202
+ require(newImplementation != address(0), Errors.ZeroAddress());
203
+ _checkImplementation(newImplementation, UpgradeableBeacon(beacon).implementation());
204
+
205
+ // The version string is compiled into the implementation. Without this check, a build
206
+ // that forgot the version bump would leave every identity reporting a stale release.
207
+ string memory actualVersion = Identity(payable(newImplementation)).version();
208
+ require(
209
+ keccak256(bytes(actualVersion)) == keccak256(bytes(expectedVersion)),
210
+ Errors.ImplementationVersionMismatch(expectedVersion, actualVersion)
211
+ );
212
+ UpgradeableBeacon(beacon).upgradeTo(newImplementation);
213
+ emit BeaconUpgraded(newImplementation);
214
+ }
215
+
216
+ /// @dev Shape check for an implementation about to sit behind the beacon. An identity's
217
+ /// trust anchors are implementation immutables, not proxy storage, so swapping the
218
+ /// implementation silently re-points every deployed identity at whatever registry the
219
+ /// new one names. Require the candidate to answer for this factory, to keep the
220
+ /// outgoing registry when there is one, and to have its own initializers locked.
221
+ /// `current` is the zero address on the initial deploy, where there is nothing to
222
+ /// stay continuous with.
223
+ function _checkImplementation(address implementation, address current) private view {
224
+ require(implementation.code.length != 0, Errors.ImplementationNotAContract(implementation));
225
+ require(
226
+ Identity(payable(implementation)).identityFactory() == address(this),
227
+ Errors.ImplementationFactoryMismatch(implementation)
228
+ );
229
+ require(
230
+ Identity(payable(implementation)).initializedVersion() == type(uint64).max,
231
+ Errors.ImplementationInitializersNotDisabled(implementation)
232
+ );
233
+
234
+ if (current != address(0)) {
235
+ address expected = Identity(payable(current)).registryModule();
236
+ address actual = Identity(payable(implementation)).registryModule();
237
+ require(actual == expected, Errors.ImplementationRegistryMismatch(expected, actual));
238
+ }
239
+ }
240
+
241
+ /// @inheritdoc IIdentityFactory
242
+ function setIdentityTypePolicy(uint256 _identityType, uint64 _roleId, bool _selfDeployable, bool _singleBinding)
243
+ external
244
+ restricted
245
+ {
246
+ // Single binding types skip the sole management check, their role gate is the only
247
+ // thing standing between an open deploy and a hijacked contract identity. Refuse
248
+ // the config instead of trusting every operator to remember that.
249
+ require(!_singleBinding || _roleId != type(uint64).max, Errors.SingleBindingTypeCannotBePublic(_identityType));
250
+ _storage().typePolicies[_identityType] = TypePolicy(_roleId, _selfDeployable, _singleBinding, true);
251
+ emit IdentityTypePolicySet(_identityType, _roleId, _selfDeployable, _singleBinding);
252
+ }
253
+
254
+ /// @inheritdoc IIdentityFactory
255
+ function removeIdentityTypePolicy(uint256 _identityType) external restricted {
256
+ delete _storage().typePolicies[_identityType];
257
+ emit IdentityTypePolicyRemoved(_identityType);
258
+ }
259
+
260
+ /// @inheritdoc IIdentityFactory
261
+ function setIdentityTypeModules(uint256 _identityType, Structs.ModuleInstall[] calldata _modules)
262
+ external
263
+ restricted
264
+ {
265
+ // Solidity cannot copy a calldata array of structs with dynamic members into
266
+ // storage in one go, so replace the list entry by entry.
267
+ Structs.ModuleInstall[] storage stored = _storage().typeModules[_identityType];
268
+ delete _storage().typeModules[_identityType];
269
+ for (uint256 i = 0; i < _modules.length; i++) {
270
+ stored.push(_modules[i]);
271
+ }
272
+ emit IdentityTypeModulesSet(_identityType, _modules);
273
+ }
274
+
275
+ /// @inheritdoc IIdentityFactory
276
+ function getIdentityTypeModules(uint256 _identityType) external view returns (Structs.ModuleInstall[] memory) {
277
+ return _storage().typeModules[_identityType];
278
+ }
279
+
280
+ /// @inheritdoc IIdentityFactory
281
+ function createIdentity(uint256 _identityType, string memory _salt, Structs.KeyParam[] memory _keys)
282
+ external
283
+ returns (address)
284
+ {
285
+ // Self-deploy is gated per type. Contract-shaped types like ASSET / SMART_CONTRACT
286
+ // opt out because their identity represents a contract, not msg.sender.
287
+ TypePolicy storage policy = _storage().typePolicies[_identityType];
288
+ require(policy.registered, Errors.UnknownIdentityType(_identityType));
289
+ require(policy.selfDeployable, Errors.IdentityTypeNotSelfDeployable(_identityType));
290
+
291
+ // Always store the wallet as an ERC-7930 envelope. If we stored raw 20-byte
292
+ // addresses here and envelopes in linkAccount, the same wallet would hash to
293
+ // two different keys and sticky binding would not catch the collision.
294
+ bytes memory account = InteroperableAddress.formatEvmV1(block.chainid, msg.sender);
295
+ return _doCreateIdentity(account, _identityType, _salt, _keys);
296
+ }
297
+
298
+ /// @inheritdoc IIdentityFactory
299
+ function createIdentityFor(
300
+ address _account,
301
+ uint256 _identityType,
302
+ string memory _salt,
303
+ Structs.KeyParam[] memory _keys
304
+ ) external returns (address) {
305
+ _checkTypeRole(_identityType, msg.sender);
306
+ require(_account != address(0), Errors.ZeroAddress());
307
+ bytes memory account = InteroperableAddress.formatEvmV1(block.chainid, _account);
308
+
309
+ // The identity is created for _account, so _account has to end up managing it. The
310
+ // account signs nothing, which keeps onboarding easy. For signing types the caller
311
+ // may only grant purposes to _account itself: no lesser keys for the caller or
312
+ // anyone else that _account never asked for. _account can add more keys later once
313
+ // it is in control. Single binding types (ASSET, SMART_CONTRACT) are contracts and
314
+ // hold no key, so they skip this and rely on their role gate instead.
315
+ //
316
+ // The check reads the hash derived from signerData, not the caller supplied keyHash
317
+ // field. The registry stores each key under keccak256(signerData) and never reads
318
+ // keyHash, so trusting that field would let a caller pass the account's hash while
319
+ // pointing signerData at its own address.
320
+ bool singleBinding = _storage().typePolicies[_identityType].singleBinding;
321
+ if (!singleBinding) {
322
+ bytes32 accountKey = hashAddress(_account);
323
+ for (uint256 i = 0; i < _keys.length; i++) {
324
+ bytes32 derivedKey = keccak256(_keys[i].signerData);
325
+ require(derivedKey == accountKey, Errors.KeyNotForAccount(derivedKey));
326
+ }
327
+ }
328
+
329
+ address identity = _doCreateIdentity(account, _identityType, _salt, _keys);
330
+
331
+ if (!singleBinding) {
332
+ _requireSoleManagementKey(identity, _account);
333
+ }
334
+
335
+ return identity;
336
+ }
337
+
338
+ /// @inheritdoc IIdentityFactory
339
+ function linkAccount(bytes calldata account, bytes calldata signature, uint256 nonce, uint256 expiry) external {
340
+ // `account` is an ERC-7930 envelope wrapping the wallet. Its layout is:
341
+ // [ chainType | chainReference | signer ]
342
+ // bytes feed the signature check. parseV1Calldata reverts on malformed input.
343
+ // The registry is keyed on the canonical re-encoding (see _walletKey), so padded
344
+ // variants of the same wallet all resolve to one entry.
345
+ (bytes2 chainType, bytes calldata chainReference, bytes calldata signer) =
346
+ InteroperableAddress.parseV1Calldata(account);
347
+
348
+ // The signature check below only proves control for EVM signers (EOA,
349
+ // ERC-1271, ERC-7913). A foreign-chain envelope proves nothing here, so it
350
+ // must come through the cross-chain path instead. 0x0000 is eip-155.
351
+ require(chainType == 0x0000, Errors.NonEvmAccount(account));
352
+
353
+ // The chain reference must name this chain: a signature verified here says
354
+ // nothing about the wallet at that address on another EVM chain, so
355
+ // envelopes for other chains must not link through the signature path.
356
+ require(keccak256(chainReference) == keccak256(_localChainReference()), Errors.AccountNotOnLocalChain(account));
357
+
358
+ // An ERC-7913 signer names its own verifier in its first 20 bytes, so the
359
+ // proof is self-certifying unless the verifier is admin-approved.
360
+ if (signer.length > 20) {
361
+ address verifier = address(bytes20(signer[:20]));
362
+ require(isTrustedVerifier(verifier), Errors.UntrustedVerifier(verifier));
363
+ }
364
+
365
+ // expiry == 0 reverts (block.timestamp <= 0 is false). Forces callers to pick a window.
366
+ require(block.timestamp <= expiry, Errors.ExpiredSignature(expiry));
367
+
368
+ // Only identities this factory deployed can pull wallets in. Otherwise random
369
+ // contracts could register themselves and feed bogus claims to T-REX modules.
370
+ require(_storage().isFactoryIdentity[msg.sender], Errors.NotFactoryIdentity(msg.sender));
371
+
372
+ bytes32 digest = _hashTypedDataV4(
373
+ keccak256(abi.encode(_LINK_ACCOUNT_TYPEHASH, keccak256(account), msg.sender, nonce, expiry))
374
+ );
375
+
376
+ // One dispatch covers every supported signer shape:
377
+ // 20 bytes -> EOA (ECDSA recover) or ERC-1271 smart wallet
378
+ // 20 + N bytes -> ERC-7913: first 20 bytes = verifier contract,
379
+ // rest = signer key (passkey pubkey, RSA key, ...)
380
+ require(SignatureChecker.isValidSignatureNow(signer, digest, signature), Errors.InvalidSignature());
381
+
382
+ // Nonce keyed by the canonical wallet key cast to address so every envelope
383
+ // shape (EVM, ERC-7913, future non-EVM) shares the OZ Nonces store and every
384
+ // encoding of the same wallet consumes one nonce sequence.
385
+ _useCheckedNonce(_addressKeyForAccount(account), nonce);
386
+
387
+ _linkAccount(account, msg.sender);
388
+ }
389
+
390
+ /// @inheritdoc IIdentityFactory
391
+ function revokeAccount(bytes calldata account) external {
392
+ // Symmetric with the link guard: a single-binding identity cannot re-link a
393
+ // fresh account because the bound contract can't sign a LinkAccount digest,
394
+ // so allowing revoke would orphan the factory's discovery entry permanently.
395
+ require(
396
+ !_storage().typePolicies[IIdentity(msg.sender).getIdentityType()].singleBinding,
397
+ Errors.CannotRevokeFromNonSigningIdentity(msg.sender)
398
+ );
399
+
400
+ bytes32 key = _walletKey(account);
401
+ require(_storage().wallets[key].identity == msg.sender, Errors.WalletNotLinkedToIdentity(account));
402
+ _revokeAccount(account, msg.sender);
403
+ }
404
+
405
+ // ============ ERC-7786 — cross-chain wallet linking ============
406
+
407
+ /// @inheritdoc IIdentityFactory
408
+ function setTrustedGateway(address gateway, bytes2 chainType, bytes calldata chainReference, bool trusted)
409
+ external
410
+ restricted
411
+ {
412
+ require(gateway != address(0), Errors.ZeroAddress());
413
+ _storage().trustedGateways[gateway][_originKey(chainType, chainReference)] = trusted;
414
+ emit TrustedGatewaySet(gateway, chainType, chainReference, trusted);
415
+ }
416
+
417
+ /// @inheritdoc IIdentityFactory
418
+ function isTrustedGateway(address gateway, bytes2 chainType, bytes calldata chainReference)
419
+ external
420
+ view
421
+ returns (bool)
422
+ {
423
+ return _storage().trustedGateways[gateway][_originKey(chainType, chainReference)];
424
+ }
425
+
426
+ /// @inheritdoc IIdentityFactory
427
+ function setTrustedVerifier(address verifier, bool trusted) external restricted {
428
+ require(verifier != address(0), Errors.ZeroAddress());
429
+ _storage().trustedVerifiers[verifier] = trusted;
430
+ emit TrustedVerifierSet(verifier, trusted);
431
+ }
432
+
433
+ /// @inheritdoc IIdentityFactory
434
+ function isTrustedVerifier(address verifier) public view returns (bool) {
435
+ return _storage().trustedVerifiers[verifier];
436
+ }
437
+
438
+ /// @inheritdoc IIdentityFactory
439
+ function getPendingCrossChainLink(bytes calldata account) external view returns (address identity, uint256 expiry) {
440
+ PendingLink storage pending = _storage().pendingLinks[_walletKey(account)];
441
+ return (pending.identity, pending.expiry);
442
+ }
443
+
444
+ /// @inheritdoc IIdentityFactory
445
+ function settlePendingCrossChainLink(bytes calldata account, bool accept) external {
446
+ // The wallet named an identity when it sent the cross-chain message. Only
447
+ // that identity gets to settle the proposal. Anyone else calling here is
448
+ // rejected. The identity reaches us via its own execution path, so a
449
+ // MANAGEMENT key on the identity is what actually signs this off.
450
+ bytes32 key = _walletKey(account);
451
+ PendingLink memory pending = _storage().pendingLinks[key];
452
+ // Missing proposal: `pending.identity == address(0)` never equals
453
+ // `msg.sender`, so one equality check covers both cases.
454
+ require(
455
+ pending.identity == msg.sender,
456
+ Errors.PendingCrossChainLinkIdentityMismatch(account, msg.sender, pending.identity)
457
+ );
458
+
459
+ delete _storage().pendingLinks[key];
460
+
461
+ // Declining is allowed at any time, expired or not. Accepting is the only
462
+ // other way a slot gets cleared and it reverts once past expiry, so without
463
+ // this a proposal nobody accepted in time would sit here forever.
464
+ if (!accept) {
465
+ emit CrossChainLinkRejected(account, msg.sender, pending.expiry);
466
+ return;
467
+ }
468
+
469
+ require(block.timestamp <= pending.expiry, Errors.PendingCrossChainLinkExpired(pending.expiry));
470
+ _linkAccount(account, msg.sender);
471
+ emit CrossChainLinkConfirmed(account, msg.sender);
472
+ }
473
+
474
+ /// @dev ERC-7786 gateway authorization. The gateway must be trusted for the
475
+ /// origin chain encoded in `sender`, so trusting it for one chain does
476
+ /// not let it deliver from another.
477
+ function _isAuthorizedGateway(address gateway, bytes calldata sender) internal view override returns (bool) {
478
+ (bool success, bytes2 chainType, bytes calldata chainReference,) =
479
+ InteroperableAddress.tryParseV1Calldata(sender);
480
+ return success && _storage().trustedGateways[gateway][_originKey(chainType, chainReference)];
481
+ }
482
+
483
+ /// @dev Storage key for one origin chain.
484
+ function _originKey(bytes2 chainType, bytes calldata chainReference) private pure returns (bytes32) {
485
+ return keccak256(abi.encodePacked(chainType, chainReference));
486
+ }
487
+
488
+ /// @dev Decode an inbound cross-chain link proposal and stage it as pending.
489
+ /// Replay across receiveIds is prevented by the gateway per ERC-7786; we
490
+ /// add wallet-level replay protection via sticky binding (an active or
491
+ /// revoked entry blocks fresh proposals from taking effect on confirm).
492
+ function _processMessage(
493
+ address, /* gateway */
494
+ bytes32, /* receiveId */
495
+ bytes calldata sender,
496
+ bytes calldata payload
497
+ )
498
+ internal
499
+ override
500
+ {
501
+ (bytes memory walletEnvelope, address identity, uint256 expiry) = abi.decode(payload, (bytes, address, uint256));
502
+
503
+ // The wallet must originate the bridge call itself. `sender` is the
504
+ // source-chain caller authenticated by ERC-7786, so requiring it to
505
+ // equal the wallet envelope is the proof-of-control for the wallet half.
506
+ require(
507
+ keccak256(sender) == keccak256(walletEnvelope),
508
+ Errors.CrossChainSenderWalletMismatch(sender, walletEnvelope)
509
+ );
510
+
511
+ // Malformed envelopes fail at delivery instead of surfacing at confirm.
512
+ InteroperableAddress.parseV1(walletEnvelope);
513
+
514
+ // A wallet on this chain already has the signature-checked linkAccount path,
515
+ // and a faithful gateway never authenticates a local sender. Accepting one
516
+ // here would link the wallet without its signature.
517
+ (bool isEvm, uint256 chainId,) = InteroperableAddress.tryParseEvmV1(walletEnvelope);
518
+ require(!isEvm || chainId != block.chainid, Errors.CrossChainLinkForLocalWallet(walletEnvelope));
519
+
520
+ require(block.timestamp <= expiry, Errors.PendingCrossChainLinkExpired(expiry));
521
+ require(_storage().isFactoryIdentity[identity], Errors.NotFactoryIdentity(identity));
522
+
523
+ // The canonical key collapses padded variants of the envelope, so a linked
524
+ // or revoked wallet cannot be re-proposed under a different encoding.
525
+ bytes32 key = _walletKey(walletEnvelope);
526
+
527
+ // Sticky binding still applies: a wallet that is already linked or
528
+ // revoked cannot be re-proposed. The confirm step would reject anyway,
529
+ // but failing fast here saves the identity owner a wasted transaction.
530
+ require(_storage().wallets[key].status == AccountStatus.None, Errors.WalletAlreadyHasEntry(walletEnvelope));
531
+
532
+ // One pending slot per wallet; the freshest proposal is the one that can
533
+ // be confirmed. Safe to overwrite because the status check above rejects
534
+ // any wallet that is already linked or revoked.
535
+ _storage().pendingLinks[key] = PendingLink({ identity: identity, expiry: expiry });
536
+ emit PendingCrossChainLinkProposed(walletEnvelope, identity, expiry);
537
+ }
538
+
539
+ /// @inheritdoc IIdentityFactory
540
+ function getIdentity(bytes calldata account) external view returns (address) {
541
+ WalletEntry storage entry = _storage().wallets[_walletKey(account)];
542
+ return entry.status == AccountStatus.Active ? entry.identity : address(0);
543
+ }
544
+
545
+ /// @inheritdoc IIdentityFactory
546
+ function getIdentityIncludingRevoked(bytes calldata account)
547
+ external
548
+ view
549
+ returns (address identity, AccountStatus status)
550
+ {
551
+ WalletEntry storage entry = _storage().wallets[_walletKey(account)];
552
+ return (entry.identity, entry.status);
553
+ }
554
+
555
+ /// @inheritdoc IIdentityFactory
556
+ function getAccountStatus(bytes calldata account) external view returns (AccountStatus) {
557
+ return _storage().wallets[_walletKey(account)].status;
558
+ }
559
+
560
+ /// @inheritdoc IIdentityFactory
561
+ function getAccounts(address identity, uint256 start, uint256 end) external view returns (bytes[] memory) {
562
+ return _accountsRange(identity, start, end);
563
+ }
564
+
565
+ /// @inheritdoc IIdentityFactory
566
+ function getAccountsCount(address identity) external view returns (uint256) {
567
+ return _storage().accounts[identity].length();
568
+ }
569
+
570
+ /// @inheritdoc IIdentityFactory
571
+ function isFactoryIdentity(address identity) external view returns (bool) {
572
+ return _storage().isFactoryIdentity[identity];
573
+ }
574
+
575
+ /// @inheritdoc IIdentityFactory
576
+ function nonceForAccount(bytes calldata account) external view returns (uint256) {
577
+ return super.nonces(_addressKeyForAccount(account));
578
+ }
579
+
580
+ /// @inheritdoc IIdentityFactory
581
+ function getIdentityTypePolicy(uint256 _identityType)
582
+ external
583
+ view
584
+ returns (uint64 roleId, bool selfDeployable, bool singleBinding, bool registered)
585
+ {
586
+ TypePolicy storage policy = _storage().typePolicies[_identityType];
587
+ return (policy.roleId, policy.selfDeployable, policy.singleBinding, policy.registered);
588
+ }
589
+
590
+ /// @dev Per-type gate for {createIdentityFor}. Unknown types revert. Admin registers
591
+ /// a type with `setIdentityTypePolicy` (use the AM's `PUBLIC_ROLE` for open types).
592
+ /// Memberships carrying an AM execution delay are rejected rather than let the
593
+ /// delay be silently bypassed — the factory has no scheduling flow.
594
+ function _checkTypeRole(uint256 _identityType, address caller) private view {
595
+ TypePolicy storage policy = _storage().typePolicies[_identityType];
596
+ require(policy.registered, Errors.UnknownIdentityType(_identityType));
597
+ (bool isMember, uint32 executionDelay) = IAccessManager(authority()).hasRole(policy.roleId, caller);
598
+ require(isMember, Errors.NotAuthorizedForIdentityType(caller, _identityType, policy.roleId));
599
+ require(executionDelay == 0, Errors.DelayedRoleNotSupported(caller, policy.roleId, executionDelay));
600
+ }
601
+
602
+ /// @dev `block.chainid` encoded as an ERC-7930 chain reference. Round-trips
603
+ /// through the library so the encoding is exactly the one it emits.
604
+ function _localChainReference() private view returns (bytes memory chainReference) {
605
+ (, chainReference,) = InteroperableAddress.parseV1(InteroperableAddress.formatEvmV1(block.chainid));
606
+ }
607
+
608
+ /// @dev {_walletKey} cast to address. Used as the nonce key so OZ Nonces
609
+ /// (address-keyed) works for ERC-7913 signers (passkeys etc.) and every
610
+ /// encoding of the same wallet shares one nonce sequence. Not a real
611
+ /// account, just a unique slot.
612
+ function _addressKeyForAccount(bytes memory account) private pure returns (address) {
613
+ return address(uint160(uint256(_walletKey(account))));
614
+ }
615
+
616
+ /// @dev `_account` must be the only wallet holding MANAGEMENT on the new identity.
617
+ /// MODULE keys never enter the MANAGEMENT index, so the count below only sees
618
+ /// wallet keys. Callers cannot abuse that exception because the deploy rejects
619
+ /// caller keys typed MODULE, so the only MODULE keys are the ones the module
620
+ /// install itself registers. The deployed registry is read rather than `_keys`
621
+ /// inspected up front, because a module can seed keys through `onInstall`.
622
+ /// Read through `registryModule()` rather than the account, so a fallback handler
623
+ /// the caller installed cannot answer these reads (M-04).
624
+ function _requireSoleManagementKey(address identity, address _account) private view {
625
+ ERC734Validator registry = ERC734Validator(Identity(payable(identity)).registryModule());
626
+
627
+ require(
628
+ registry.keyHasPurpose(identity, hashAddress(_account), KeyPurposes.MANAGEMENT),
629
+ Errors.AccountNotSoleManagementKey(_account)
630
+ );
631
+
632
+ require(
633
+ registry.getKeysByPurpose(identity, KeyPurposes.MANAGEMENT).length == 1,
634
+ Errors.AccountNotSoleManagementKey(_account)
635
+ );
636
+ }
637
+
638
+ /// @dev Shared deploy core. CREATE3 deploys the proxy with keys and modules baked into
639
+ /// the init calldata. Identity.initialize runs in the proxy constructor frame so
640
+ /// keys and modules are applied without any cross-contract dance and without the
641
+ /// factory ever holding a MANAGEMENT key. After deploy we check the post-state
642
+ /// shape (at least one MANAGEMENT key), mark the identity as factory-deployed,
643
+ /// and auto-link the account.
644
+ function _doCreateIdentity(
645
+ bytes memory _account,
646
+ uint256 _identityType,
647
+ string memory _salt,
648
+ Structs.KeyParam[] memory _keys
649
+ ) private returns (address identity) {
650
+ require(bytes(_salt).length != 0, Errors.EmptyString());
651
+ require(_keys.length > 0, Errors.EmptyListOfKeys());
652
+
653
+ // Caller keys are wallet keys. The MODULE type is reserved for the keys the module
654
+ // install registers: MODULE keys stay out of the MANAGEMENT index and cannot sign,
655
+ // so a wallet key labeled MODULE would hold management authority through the
656
+ // approval queue while every count and guard misses it.
657
+ for (uint256 i = 0; i < _keys.length; i++) {
658
+ require(_keys[i].keyType != KeyTypes.MODULE, Errors.CallerKeyCannotBeModule(keccak256(_keys[i].signerData)));
659
+ }
660
+
661
+ // Modules come from the type's registered configuration, never from the caller. A
662
+ // type with no modules registered cannot deploy, because Identity.initialize needs
663
+ // a validator or an executor.
664
+ Structs.ModuleInstall[] memory _modules = _storage().typeModules[_identityType];
665
+
666
+ // Both entry points build the envelope from a 20-byte EVM address, so the shape is
667
+ // guaranteed here. Asset identities are deployed for a token contract and the token
668
+ // is auto-linked as the identity's sole wallet like any other signer; the difference
669
+ // is the identity's `type`. Off-chain readers can recover the token by reading
670
+ // `getAccounts(identity, 0, 1)[0]` and checking `getIdentityType()`.
671
+ //
672
+ // Refuse a zero account: it gets linked as a wallet below and bindings are sticky,
673
+ // so the identity would be stuck with an account nobody can sign for.
674
+ (, address account) = InteroperableAddress.parseEvmV1(_account);
675
+ require(account != address(0), Errors.ZeroAddress());
676
+
677
+ // Salt covers type, user salt, keys and the account that gets auto-linked, but not
678
+ // modules: a module config change should not move the identity's address, so the
679
+ // same inputs always land at the same slot regardless of which modules are installed
680
+ // at deploy. The account is in there because it is bound to the identity right after
681
+ // this deploy, and the binding is sticky. Leaving it out would let anyone replay a
682
+ // pending creation with an account of their own, take the address the caller was
683
+ // going to get, and have their wallet auto-linked to it. Hashing the parsed address
684
+ // rather than the envelope keeps the address the same across chains.
685
+ bytes32 deploySalt = keccak256(abi.encode(_identityType, _salt, account, keccak256(abi.encode(_keys))));
686
+
687
+ identity = _deployIdentity(deploySalt, _identityType, _keys, _modules);
688
+
689
+ // The identity must end up with at least one MANAGEMENT key. Without it nobody
690
+ // can manage the identity, so deploy is treated as a programmer error and reverts.
691
+ // Read the enshrined registry directly rather than through the account, so the check
692
+ // is answered by the canonical key store and not by any handler the caller installed.
693
+ // `registryModule()` is a plain function on the beacon-controlled implementation.
694
+ require(
695
+ ERC734Validator(Identity(payable(identity)).registryModule())
696
+ .getKeysByPurpose(identity, KeyPurposes.MANAGEMENT)
697
+ .length >= 1,
698
+ Errors.NoManagementKeyInKeys()
699
+ );
700
+
701
+ // Mark factory-deployed BEFORE linking so a re-entrant module can't pretend
702
+ // to be a non-factory caller.
703
+ _storage().isFactoryIdentity[identity] = true;
704
+ _linkAccount(_account, identity);
705
+ }
706
+
707
+ /// @dev Link rule. Enforces sticky binding and terminal revocation. Tokens and
708
+ /// wallets share the same keyspace, so the same address or signer can only
709
+ /// live in one entry, so there's no separate collision check needed.
710
+ function _linkAccount(bytes memory account, address identity) internal {
711
+ // Normalize first so the key, the stored record and the emitted event all
712
+ // carry the canonical form no matter which encoding the caller supplied.
713
+ // This parses too, so a raw byte string can never become an enumerable record.
714
+ account = _canonicalEnvelope(account);
715
+
716
+ // A single-binding identity takes exactly one account: the first, which is
717
+ // the factory's auto-link at deploy. Anything after that would break the
718
+ // 1:1 contract↔identity mapping.
719
+ require(
720
+ !_storage().typePolicies[IIdentity(identity).getIdentityType()].singleBinding
721
+ || _storage().accounts[identity].length() == 0,
722
+ Errors.CannotLinkToAssetIdentity(identity)
723
+ );
724
+
725
+ bytes32 key = keccak256(account);
726
+ WalletEntry storage entry = _storage().wallets[key];
727
+
728
+ // Once revoked, never re-linkable.
729
+ require(entry.status != AccountStatus.Revoked, Errors.WalletAlreadyRevoked(account));
730
+
731
+ // If already bound, must be the same identity.
732
+ require(
733
+ entry.identity == address(0) || entry.identity == identity,
734
+ Errors.WalletBoundToAnotherIdentity(account, entry.identity)
735
+ );
736
+
737
+ require(_storage().accounts[identity].add(key), Errors.WalletAlreadyLinkedToIdentity(account));
738
+
739
+ entry.identity = identity;
740
+ entry.status = AccountStatus.Active;
741
+ if (entry.record.length == 0) {
742
+ entry.record = account;
743
+ }
744
+
745
+ emit AccountLinked(account, identity);
746
+ }
747
+
748
+ /// @dev Revoke rule. Flips status to Revoked and drops the wallet from the active
749
+ /// set. identity + record stay so the binding is visible via
750
+ /// getIdentityIncludingRevoked. Revoking the last wallet leaves the active set
751
+ /// empty but the identity manageable: keys are a separate namespace, so a
752
+ /// MANAGEMENT key can still link a fresh wallet.
753
+ function _revokeAccount(bytes memory account, address identity) internal {
754
+ account = _canonicalEnvelope(account);
755
+ bytes32 key = keccak256(account);
756
+ WalletEntry storage entry = _storage().wallets[key];
757
+ require(entry.status == AccountStatus.Active, Errors.WalletNotActive(account));
758
+ require(_storage().accounts[identity].remove(key), Errors.WalletNotLinkedToIdentity(account));
759
+
760
+ entry.status = AccountStatus.Revoked;
761
+
762
+ emit AccountRevoked(account, identity);
763
+ }
764
+
765
+ function _accountsRange(address identity, uint256 start, uint256 end) private view returns (bytes[] memory out) {
766
+ bytes32[] memory keys = _storage().accounts[identity].values(start, end);
767
+ out = new bytes[](keys.length);
768
+ for (uint256 i = 0; i < keys.length; i++) {
769
+ out[i] = _storage().wallets[keys[i]].record;
770
+ }
771
+ }
772
+
773
+ /// @dev Registry key for a wallet: the hash of its canonical envelope. The key
774
+ /// is canonical by construction, so every valid encoding of a wallet
775
+ /// resolves to the same entry on every path that touches the registry.
776
+ function _walletKey(bytes memory account) private pure returns (bytes32) {
777
+ return keccak256(_canonicalEnvelope(account));
778
+ }
779
+
780
+ /// @dev One wallet must have one encoding, or it would get several registry
781
+ /// keys. The OZ parser is more lenient than that: it ignores
782
+ /// trailing bytes and accepts zero-padded eip-155 chain references.
783
+ /// Re-encoding from the parsed fields drops the trailing bytes; padded
784
+ /// chain references are rejected. Reverts on invalid envelopes.
785
+ function _canonicalEnvelope(bytes memory account) private pure returns (bytes memory) {
786
+ (bytes2 chainType, bytes memory chainReference, bytes memory addr) = InteroperableAddress.parseV1(account);
787
+
788
+ // eip-155 chain references are numeric, so a leading zero byte is padding
789
+ // for the same chainid. Only the minimal encoding (what formatEvmV1 emits)
790
+ // is accepted; a single 0x00 byte is chainid 0 itself, not padding.
791
+ require(
792
+ chainType != 0x0000 || chainReference.length < 2 || chainReference[0] != 0,
793
+ Errors.NonCanonicalAccount(account)
794
+ );
795
+
796
+ return InteroperableAddress.formatV1(chainType, chainReference, addr);
797
+ }
798
+
799
+ /// @dev CREATE3 deploy of a fresh BeaconProxy. The address depends only on the factory
800
+ /// address and the deploySalt, so the same salt gives the same identity address
801
+ /// on every canonical EVM chain where this factory shares the same address. The
802
+ /// proxy's constructor calls beacon.implementation() and forwards this calldata
803
+ /// via delegatecall, so Identity.initialize runs inside the new proxy's storage
804
+ /// and applies keys and modules in the same frame.
805
+ function _deployIdentity(
806
+ bytes32 deploySalt,
807
+ uint256 _identityType,
808
+ Structs.KeyParam[] memory _keys,
809
+ Structs.ModuleInstall[] memory _modules
810
+ ) private returns (address) {
811
+ require(beacon.code.length != 0, Errors.BeaconNotInitialized());
812
+ bytes memory initData = abi.encodeCall(Identity.initialize, (_identityType, _keys, _modules));
813
+ bytes memory bytecode = abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(beacon, initData));
814
+
815
+ return Create3.deploy(0, deploySalt, bytecode);
816
+ }
817
+
818
+ }