@linealqorum/js 0.0.0-stage → 0.0.1
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.
- package/package.json +16 -5
- package/src/artifact-service.js +94 -0
- package/src/artifacts/artifacts.d.ts +13 -0
- package/src/artifacts/build-info/solc-0_8_30-e703f2fe389268a2246aec69fef2175182b7b532.json +392 -0
- package/src/artifacts/build-info/solc-0_8_30-e703f2fe389268a2246aec69fef2175182b7b532.output.json +1 -0
- package/src/artifacts/contracts/Counter.sol/Counter.json +60 -0
- package/src/artifacts/contracts/Counter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/BaseAccount.sol/BaseAccount.json +116 -0
- package/src/artifacts/contracts/core/BaseAccount.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/BasePaymaster.sol/BasePaymaster.json +281 -0
- package/src/artifacts/contracts/core/BasePaymaster.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/EntryPoint.sol/EntryPoint.json +1019 -0
- package/src/artifacts/contracts/core/EntryPoint.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/EntryPointSimulations.sol/EntryPointSimulations.json +1324 -0
- package/src/artifacts/contracts/core/EntryPointSimulations.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/Groth16Verifier.sol/Groth16Verifier.json +48 -0
- package/src/artifacts/contracts/core/Groth16Verifier.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/Helpers.sol/artifacts.d.ts +0 -0
- package/src/artifacts/contracts/core/LinealDeployer.sol/LinealDeployer.json +51 -0
- package/src/artifacts/contracts/core/LinealDeployer.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/NonceManager.sol/NonceManager.json +75 -0
- package/src/artifacts/contracts/core/NonceManager.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/SenderCreator.sol/SenderCreator.json +33 -0
- package/src/artifacts/contracts/core/SenderCreator.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/StakeManager.sol/StakeManager.json +299 -0
- package/src/artifacts/contracts/core/StakeManager.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/core/UserOperationLib.sol/UserOperationLib.json +53 -0
- package/src/artifacts/contracts/core/UserOperationLib.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealDex.sol/LinealDex.json +530 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealDex.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealLiquidity.sol/LinealLiquidity.json +876 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealLiquidity.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/ILinealCitizens.json +46 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/LinealMilestones.json +986 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/artifacts.d.ts +43 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealSeed.sol/LinealSeed.json +808 -0
- package/src/artifacts/contracts/economy/Liquidity/LinealSeed.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/accounts/LinealAccount.sol/LinealAccount.json +591 -0
- package/src/artifacts/contracts/economy/accounts/LinealAccount.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/accounts/LinealAccountFactory.sol/LinealAccountFactory.json +101 -0
- package/src/artifacts/contracts/economy/accounts/LinealAccountFactory.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/accounts/callback/TokenCallbackHandler.sol/TokenCallbackHandler.json +145 -0
- package/src/artifacts/contracts/economy/accounts/callback/TokenCallbackHandler.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/IBankDeposit.json +56 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/ICitizensAccounts.json +33 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/IInstitutionIdentity.json +27 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/ILinealTransactions.json +53 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/LinealBank.json +1072 -0
- package/src/artifacts/contracts/economy/banks/LinealBank.sol/artifacts.d.ts +91 -0
- package/src/artifacts/contracts/economy/banks/LinealQantum.sol/LinealQantum.json +496 -0
- package/src/artifacts/contracts/economy/banks/LinealQantum.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/ILinealBank.json +27 -0
- package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/LinealTransactions.json +1352 -0
- package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/artifacts.d.ts +43 -0
- package/src/artifacts/contracts/economy/interfaces/ICLPStablecoin.sol/ICLPStablecoin.json +459 -0
- package/src/artifacts/contracts/economy/interfaces/ICLPStablecoin.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/IDEXRouter.sol/IDEXRouter.json +117 -0
- package/src/artifacts/contracts/economy/interfaces/IDEXRouter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/IFeeSplitter.sol/IFeeSplitter.json +40 -0
- package/src/artifacts/contracts/economy/interfaces/IFeeSplitter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/IIncomeToken.sol/IIncomeToken.json +197 -0
- package/src/artifacts/contracts/economy/interfaces/IIncomeToken.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/ILinealIdentity.sol/ILinealIdentity.json +90 -0
- package/src/artifacts/contracts/economy/interfaces/ILinealIdentity.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/IMetricsAdapter.sol/IMetricsAdapter.json +32 -0
- package/src/artifacts/contracts/economy/interfaces/IMetricsAdapter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/interfaces/IQorumsToken.sol/IQorumsToken.json +267 -0
- package/src/artifacts/contracts/economy/interfaces/IQorumsToken.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/paymasters/LinealPaymaster.sol/LinealPaymaster.json +487 -0
- package/src/artifacts/contracts/economy/paymasters/LinealPaymaster.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/paymasters/LinealRouter.sol/LinealRouter.json +945 -0
- package/src/artifacts/contracts/economy/paymasters/LinealRouter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/economy/token/LinealToken.sol/LinealToken.json +1567 -0
- package/src/artifacts/contracts/economy/token/LinealToken.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/governance/LinealQorum.sol/LinealQorum.json +567 -0
- package/src/artifacts/contracts/governance/LinealQorum.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/institution/LinealCitizens.sol/LinealCitizens.json +986 -0
- package/src/artifacts/contracts/institution/LinealCitizens.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/institution/LinealInstitution.sol/LinealInstitution.json +1607 -0
- package/src/artifacts/contracts/institution/LinealInstitution.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/institution/LinealTender.sol/LinealTender.json +1055 -0
- package/src/artifacts/contracts/institution/LinealTender.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IAccount.sol/IAccount.json +90 -0
- package/src/artifacts/contracts/interfaces/IAccount.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IAccountExecute.sol/IAccountExecute.json +79 -0
- package/src/artifacts/contracts/interfaces/IAccountExecute.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IAggregator.sol/IAggregator.json +211 -0
- package/src/artifacts/contracts/interfaces/IAggregator.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IEntryPoint.sol/IEntryPoint.json +809 -0
- package/src/artifacts/contracts/interfaces/IEntryPoint.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IEntryPointSimulations.sol/IEntryPointSimulations.json +1097 -0
- package/src/artifacts/contracts/interfaces/IEntryPointSimulations.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IMetricsAdapter.sol/IMetricsAdapter.json +32 -0
- package/src/artifacts/contracts/interfaces/IMetricsAdapter.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/INonceManager.sol/INonceManager.json +51 -0
- package/src/artifacts/contracts/interfaces/INonceManager.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IPaymaster.sol/IPaymaster.json +123 -0
- package/src/artifacts/contracts/interfaces/IPaymaster.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IQorumsToken.sol/IQorumsToken.json +267 -0
- package/src/artifacts/contracts/interfaces/IQorumsToken.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/IStakeManager.sol/IStakeManager.json +256 -0
- package/src/artifacts/contracts/interfaces/IStakeManager.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/interfaces/PackedUserOperation.sol/artifacts.d.ts +0 -0
- package/src/artifacts/contracts/kernel/LinealEconomy.sol/LinealEconomicKernel.json +743 -0
- package/src/artifacts/contracts/kernel/LinealEconomy.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/social/LinealStorage.sol/PostBoard.json +1317 -0
- package/src/artifacts/contracts/social/LinealStorage.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/test.sol/LinealSecureStorage.json +634 -0
- package/src/artifacts/contracts/test.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/utils/Exec.sol/Exec.json +13 -0
- package/src/artifacts/contracts/utils/Exec.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/utils/IOracle.sol/IOracle.json +60 -0
- package/src/artifacts/contracts/utils/IOracle.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/utils/OracleHelper.sol/OracleHelper.json +84 -0
- package/src/artifacts/contracts/utils/OracleHelper.sol/artifacts.d.ts +27 -0
- package/src/artifacts/contracts/utils/UniswapHelper.sol/UniswapHelper.json +132 -0
- package/src/artifacts/contracts/utils/UniswapHelper.sol/artifacts.d.ts +27 -0
- package/src/contract-service.js +53 -0
- package/src/database/mongodb.js +181 -0
- package/src/index.js +11 -0
- package/src/middleware/actionMiddleware.js +17 -0
- package/src/middleware/actionsMiddleware.js +18 -0
- package/src/middleware/authMachineMiddleware.js +34 -0
- package/src/middleware/middleware.js +36 -0
- package/src/middleware/onlyQorum.js +57 -0
- package/src/middleware/onlyServer.js +36 -0
- package/src/middleware/readStateMiddleware.js +19 -0
- package/src/middleware/unauthorizeMiddleware.js +37 -0
- package/src/middleware/userOperation.js +25 -0
- package/src/operation-service.js +71 -0
- package/src/schemas/abiFolderSchema.js +9 -0
- package/src/schemas/abiSchema.js +16 -0
- package/src/schemas/applicationSchema.js +32 -0
- package/src/schemas/authorizedWalletSchema.js +9 -0
- package/src/schemas/deploySchema.js +11 -0
- package/src/schemas/expenseSchema.js +17 -0
- package/src/schemas/feeSchema.js +17 -0
- package/src/schemas/fixedExpenseSchema.js +18 -0
- package/src/schemas/fixedFeeSchema.js +17 -0
- package/src/schemas/identitySchema.js +33 -0
- package/src/schemas/institutionSchema.js +28 -0
- package/src/schemas/onlyQorumSchema.js +27 -0
- package/src/schemas/onlyServerSchema.js +26 -0
- package/src/schemas/serverWalletSchema.js +9 -0
- package/src/schemas/subaccountSchema.js +31 -0
- package/src/schemas/tenderSchema.js +36 -0
- package/src/schemas/transactionSchema.js +29 -0
- package/src/schemas/userOperationSchema.js +15 -0
- package/src/schemas/valuationSchema.js +10 -0
- package/src/signer-client.js +280 -0
- package/README.md +0 -3
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_format": "hh3-sol-build-info-1",
|
|
3
|
+
"id": "solc-0_8_30-e703f2fe389268a2246aec69fef2175182b7b532",
|
|
4
|
+
"solcVersion": "0.8.30",
|
|
5
|
+
"solcLongVersion": "0.8.30+commit.73712a01",
|
|
6
|
+
"compilerType": "solc",
|
|
7
|
+
"userSourceNameMap": {
|
|
8
|
+
"contracts/core/BaseAccount.sol": "project/contracts/core/BaseAccount.sol",
|
|
9
|
+
"contracts/core/BasePaymaster.sol": "project/contracts/core/BasePaymaster.sol",
|
|
10
|
+
"contracts/core/EntryPoint.sol": "project/contracts/core/EntryPoint.sol",
|
|
11
|
+
"contracts/core/EntryPointSimulations.sol": "project/contracts/core/EntryPointSimulations.sol",
|
|
12
|
+
"contracts/core/Groth16Verifier.sol": "project/contracts/core/Groth16Verifier.sol",
|
|
13
|
+
"contracts/core/Helpers.sol": "project/contracts/core/Helpers.sol",
|
|
14
|
+
"contracts/core/LinealDeployer.sol": "project/contracts/core/LinealDeployer.sol",
|
|
15
|
+
"contracts/core/NonceManager.sol": "project/contracts/core/NonceManager.sol",
|
|
16
|
+
"contracts/core/SenderCreator.sol": "project/contracts/core/SenderCreator.sol",
|
|
17
|
+
"contracts/core/StakeManager.sol": "project/contracts/core/StakeManager.sol",
|
|
18
|
+
"contracts/core/UserOperationLib.sol": "project/contracts/core/UserOperationLib.sol",
|
|
19
|
+
"contracts/Counter.sol": "project/contracts/Counter.sol",
|
|
20
|
+
"contracts/economy/accounts/callback/TokenCallbackHandler.sol": "project/contracts/economy/accounts/callback/TokenCallbackHandler.sol",
|
|
21
|
+
"contracts/economy/accounts/LinealAccount.sol": "project/contracts/economy/accounts/LinealAccount.sol",
|
|
22
|
+
"contracts/economy/accounts/LinealAccountFactory.sol": "project/contracts/economy/accounts/LinealAccountFactory.sol",
|
|
23
|
+
"contracts/economy/banks/LinealBank.sol": "project/contracts/economy/banks/LinealBank.sol",
|
|
24
|
+
"contracts/economy/banks/LinealQantum.sol": "project/contracts/economy/banks/LinealQantum.sol",
|
|
25
|
+
"contracts/economy/banks/LinealTransaction.sol": "project/contracts/economy/banks/LinealTransaction.sol",
|
|
26
|
+
"contracts/economy/interfaces/ICLPStablecoin.sol": "project/contracts/economy/interfaces/ICLPStablecoin.sol",
|
|
27
|
+
"contracts/economy/interfaces/IDEXRouter.sol": "project/contracts/economy/interfaces/IDEXRouter.sol",
|
|
28
|
+
"contracts/economy/interfaces/IFeeSplitter.sol": "project/contracts/economy/interfaces/IFeeSplitter.sol",
|
|
29
|
+
"contracts/economy/interfaces/IIncomeToken.sol": "project/contracts/economy/interfaces/IIncomeToken.sol",
|
|
30
|
+
"contracts/economy/interfaces/ILinealIdentity.sol": "project/contracts/economy/interfaces/ILinealIdentity.sol",
|
|
31
|
+
"contracts/economy/interfaces/IMetricsAdapter.sol": "project/contracts/economy/interfaces/IMetricsAdapter.sol",
|
|
32
|
+
"contracts/economy/interfaces/IQorumsToken.sol": "project/contracts/economy/interfaces/IQorumsToken.sol",
|
|
33
|
+
"contracts/economy/Liquidity/LinealDex.sol": "project/contracts/economy/Liquidity/LinealDex.sol",
|
|
34
|
+
"contracts/economy/Liquidity/LinealLiquidity.sol": "project/contracts/economy/Liquidity/LinealLiquidity.sol",
|
|
35
|
+
"contracts/economy/Liquidity/LinealMilestones.sol": "project/contracts/economy/Liquidity/LinealMilestones.sol",
|
|
36
|
+
"contracts/economy/Liquidity/LinealSeed.sol": "project/contracts/economy/Liquidity/LinealSeed.sol",
|
|
37
|
+
"contracts/economy/paymasters/LinealPaymaster.sol": "project/contracts/economy/paymasters/LinealPaymaster.sol",
|
|
38
|
+
"contracts/economy/paymasters/LinealRouter.sol": "project/contracts/economy/paymasters/LinealRouter.sol",
|
|
39
|
+
"contracts/economy/token/LinealToken.sol": "project/contracts/economy/token/LinealToken.sol",
|
|
40
|
+
"contracts/governance/LinealQorum.sol": "project/contracts/governance/LinealQorum.sol",
|
|
41
|
+
"contracts/institution/LinealCitizens.sol": "project/contracts/institution/LinealCitizens.sol",
|
|
42
|
+
"contracts/institution/LinealInstitution.sol": "project/contracts/institution/LinealInstitution.sol",
|
|
43
|
+
"contracts/institution/LinealTender.sol": "project/contracts/institution/LinealTender.sol",
|
|
44
|
+
"contracts/interfaces/IAccount.sol": "project/contracts/interfaces/IAccount.sol",
|
|
45
|
+
"contracts/interfaces/IAccountExecute.sol": "project/contracts/interfaces/IAccountExecute.sol",
|
|
46
|
+
"contracts/interfaces/IAggregator.sol": "project/contracts/interfaces/IAggregator.sol",
|
|
47
|
+
"contracts/interfaces/IEntryPoint.sol": "project/contracts/interfaces/IEntryPoint.sol",
|
|
48
|
+
"contracts/interfaces/IEntryPointSimulations.sol": "project/contracts/interfaces/IEntryPointSimulations.sol",
|
|
49
|
+
"contracts/interfaces/IMetricsAdapter.sol": "project/contracts/interfaces/IMetricsAdapter.sol",
|
|
50
|
+
"contracts/interfaces/INonceManager.sol": "project/contracts/interfaces/INonceManager.sol",
|
|
51
|
+
"contracts/interfaces/IPaymaster.sol": "project/contracts/interfaces/IPaymaster.sol",
|
|
52
|
+
"contracts/interfaces/IQorumsToken.sol": "project/contracts/interfaces/IQorumsToken.sol",
|
|
53
|
+
"contracts/interfaces/IStakeManager.sol": "project/contracts/interfaces/IStakeManager.sol",
|
|
54
|
+
"contracts/interfaces/PackedUserOperation.sol": "project/contracts/interfaces/PackedUserOperation.sol",
|
|
55
|
+
"contracts/kernel/LinealEconomy.sol": "project/contracts/kernel/LinealEconomy.sol",
|
|
56
|
+
"contracts/social/LinealStorage.sol": "project/contracts/social/LinealStorage.sol",
|
|
57
|
+
"contracts/test.sol": "project/contracts/test.sol",
|
|
58
|
+
"contracts/utils/Exec.sol": "project/contracts/utils/Exec.sol",
|
|
59
|
+
"contracts/utils/IOracle.sol": "project/contracts/utils/IOracle.sol",
|
|
60
|
+
"contracts/utils/OracleHelper.sol": "project/contracts/utils/OracleHelper.sol",
|
|
61
|
+
"contracts/utils/UniswapHelper.sol": "project/contracts/utils/UniswapHelper.sol"
|
|
62
|
+
},
|
|
63
|
+
"input": {
|
|
64
|
+
"language": "Solidity",
|
|
65
|
+
"settings": {
|
|
66
|
+
"evmVersion": "prague",
|
|
67
|
+
"optimizer": {
|
|
68
|
+
"enabled": true,
|
|
69
|
+
"runs": 200
|
|
70
|
+
},
|
|
71
|
+
"outputSelection": {
|
|
72
|
+
"*": {
|
|
73
|
+
"": [
|
|
74
|
+
"ast"
|
|
75
|
+
],
|
|
76
|
+
"*": [
|
|
77
|
+
"abi",
|
|
78
|
+
"evm.bytecode.linkReferences",
|
|
79
|
+
"evm.bytecode.object",
|
|
80
|
+
"evm.bytecode.opcodes",
|
|
81
|
+
"evm.bytecode.sourceMap",
|
|
82
|
+
"evm.deployedBytecode.immutableReferences",
|
|
83
|
+
"evm.deployedBytecode.linkReferences",
|
|
84
|
+
"evm.deployedBytecode.object",
|
|
85
|
+
"evm.deployedBytecode.opcodes",
|
|
86
|
+
"evm.deployedBytecode.sourceMap",
|
|
87
|
+
"evm.methodIdentifiers"
|
|
88
|
+
]
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
"remappings": [
|
|
92
|
+
"npm/@uniswap/v3-periphery@1.4.4/:@uniswap/v3-core/=npm/@uniswap/v3-core@1.0.1/",
|
|
93
|
+
"project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.1.0/",
|
|
94
|
+
"project/:@uniswap/v3-periphery/=npm/@uniswap/v3-periphery@1.4.4/"
|
|
95
|
+
],
|
|
96
|
+
"viaIR": true
|
|
97
|
+
},
|
|
98
|
+
"sources": {
|
|
99
|
+
"npm/@openzeppelin/contracts@5.1.0/access/Ownable.sol": {
|
|
100
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
|
|
101
|
+
},
|
|
102
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/draft-IERC1822.sol": {
|
|
103
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n"
|
|
104
|
+
},
|
|
105
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/draft-IERC6093.sol": {
|
|
106
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"
|
|
107
|
+
},
|
|
108
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/IERC1363.sol": {
|
|
109
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n /*\n * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n * 0xb0202a11 ===\n * bytes4(keccak256('transferAndCall(address,uint256)')) ^\n * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n * bytes4(keccak256('approveAndCall(address,uint256)')) ^\n * bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n */\n\n /**\n * @dev Moves a `value` amount of tokens from the caller's account to `to`\n * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n * @param to The address which you want to transfer to.\n * @param value The amount of tokens to be transferred.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function transferAndCall(address to, uint256 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from the caller's account to `to`\n * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n * @param to The address which you want to transfer to.\n * @param value The amount of tokens to be transferred.\n * @param data Additional data with no specified format, sent in call to `to`.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n * @param from The address which you want to send tokens from.\n * @param to The address which you want to transfer to.\n * @param value The amount of tokens to be transferred.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n * @param from The address which you want to send tokens from.\n * @param to The address which you want to transfer to.\n * @param value The amount of tokens to be transferred.\n * @param data Additional data with no specified format, sent in call to `to`.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n /**\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n * @param spender The address which will spend the funds.\n * @param value The amount of tokens to be spent.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function approveAndCall(address spender, uint256 value) external returns (bool);\n\n /**\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n * @param spender The address which will spend the funds.\n * @param value The amount of tokens to be spent.\n * @param data Additional data with no specified format, sent in call to `spender`.\n * @return A boolean value indicating whether the operation succeeded unless throwing.\n */\n function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"
|
|
110
|
+
},
|
|
111
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/IERC165.sol": {
|
|
112
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"
|
|
113
|
+
},
|
|
114
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/IERC1967.sol": {
|
|
115
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}\n"
|
|
116
|
+
},
|
|
117
|
+
"npm/@openzeppelin/contracts@5.1.0/interfaces/IERC20.sol": {
|
|
118
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"
|
|
119
|
+
},
|
|
120
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/beacon/IBeacon.sol": {
|
|
121
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n"
|
|
122
|
+
},
|
|
123
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/ERC1967/ERC1967Proxy.sol": {
|
|
124
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.20;\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}\n"
|
|
125
|
+
},
|
|
126
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/ERC1967/ERC1967Utils.sol": {
|
|
127
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.21;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This library provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit IERC1967.Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit IERC1967.AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit IERC1967.BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}\n"
|
|
128
|
+
},
|
|
129
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/Proxy.sol": {
|
|
130
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}\n"
|
|
131
|
+
},
|
|
132
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/utils/Initializable.sol": {
|
|
133
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Storage of the initializable contract.\n *\n * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n * when using with upgradeable contracts.\n *\n * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n */\n struct InitializableStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint64 _initialized;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool _initializing;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n /**\n * @dev The contract is already initialized.\n */\n error InvalidInitialization();\n\n /**\n * @dev The contract is not initializing.\n */\n error NotInitializing();\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint64 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n * production.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n // Cache values to avoid duplicated sloads\n bool isTopLevelCall = !$._initializing;\n uint64 initialized = $._initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - construction: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool construction = initialized == 1 && address(this).code.length == 0;\n\n if (!initialSetup && !construction) {\n revert InvalidInitialization();\n }\n $._initialized = 1;\n if (isTopLevelCall) {\n $._initializing = true;\n }\n _;\n if (isTopLevelCall) {\n $._initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint64 version) {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing || $._initialized >= version) {\n revert InvalidInitialization();\n }\n $._initialized = version;\n $._initializing = true;\n _;\n $._initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n _checkInitializing();\n _;\n }\n\n /**\n * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n */\n function _checkInitializing() internal view virtual {\n if (!_isInitializing()) {\n revert NotInitializing();\n }\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing) {\n revert InvalidInitialization();\n }\n if ($._initialized != type(uint64).max) {\n $._initialized = type(uint64).max;\n emit Initialized(type(uint64).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint64) {\n return _getInitializableStorage()._initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _getInitializableStorage()._initializing;\n }\n\n /**\n * @dev Returns a pointer to the storage namespace.\n */\n // solhint-disable-next-line var-name-mixedcase\n function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n assembly {\n $.slot := INITIALIZABLE_STORAGE\n }\n }\n}\n"
|
|
134
|
+
},
|
|
135
|
+
"npm/@openzeppelin/contracts@5.1.0/proxy/utils/UUPSUpgradeable.sol": {
|
|
136
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC1822Proxiable} from \"../../interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"../ERC1967/ERC1967Utils.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n */\nabstract contract UUPSUpgradeable is IERC1822Proxiable {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address private immutable __self = address(this);\n\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev The call is from an unauthorized context.\n */\n error UUPSUnauthorizedCallContext();\n\n /**\n * @dev The storage `slot` is unsupported as a UUID.\n */\n error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n /**\n * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case\n * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n * fail.\n */\n modifier onlyProxy() {\n _checkProxy();\n _;\n }\n\n /**\n * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n * callable on the implementing contract but not through proxies.\n */\n modifier notDelegated() {\n _checkNotDelegated();\n _;\n }\n\n /**\n * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the\n * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n */\n function proxiableUUID() external view virtual notDelegated returns (bytes32) {\n return ERC1967Utils.IMPLEMENTATION_SLOT;\n }\n\n /**\n * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n * encoded in `data`.\n *\n * Calls {_authorizeUpgrade}.\n *\n * Emits an {Upgraded} event.\n *\n * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, data);\n }\n\n /**\n * @dev Reverts if the execution is not performed via delegatecall or the execution\n * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.\n * See {_onlyProxy}.\n */\n function _checkProxy() internal view virtual {\n if (\n address(this) == __self || // Must be called through delegatecall\n ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n ) {\n revert UUPSUnauthorizedCallContext();\n }\n }\n\n /**\n * @dev Reverts if the execution is performed via delegatecall.\n * See {notDelegated}.\n */\n function _checkNotDelegated() internal view virtual {\n if (address(this) != __self) {\n // Must not be called through delegatecall\n revert UUPSUnauthorizedCallContext();\n }\n }\n\n /**\n * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n * {upgradeToAndCall}.\n *\n * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n *\n * ```solidity\n * function _authorizeUpgrade(address) internal onlyOwner {}\n * ```\n */\n function _authorizeUpgrade(address newImplementation) internal virtual;\n\n /**\n * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n *\n * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n * is expected to be the implementation slot in ERC-1967.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n revert UUPSUnsupportedProxiableUUID(slot);\n }\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n } catch {\n // The implementation is not UUPS\n revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n }\n }\n}\n"
|
|
137
|
+
},
|
|
138
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC1155/IERC1155Receiver.sol": {
|
|
139
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface that must be implemented by smart contracts in order to receive\n * ERC-1155 token transfers.\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC-1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC-1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
|
|
140
|
+
},
|
|
141
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC20/ERC20.sol": {
|
|
142
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n mapping(address account => uint256) private _balances;\n\n mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `value`.\n */\n function transfer(address to, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Skips emitting an {Approval} event indicating an allowance update. This is not\n * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `value`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `value`.\n */\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, value);\n _transfer(from, to, value);\n return true;\n }\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _transfer(address from, address to, uint256 value) internal {\n if (from == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n if (to == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(from, to, value);\n }\n\n /**\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n * this function.\n *\n * Emits a {Transfer} event.\n */\n function _update(address from, address to, uint256 value) internal virtual {\n if (from == address(0)) {\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\n _totalSupply += value;\n } else {\n uint256 fromBalance = _balances[from];\n if (fromBalance < value) {\n revert ERC20InsufficientBalance(from, fromBalance, value);\n }\n unchecked {\n // Overflow not possible: value <= fromBalance <= totalSupply.\n _balances[from] = fromBalance - value;\n }\n }\n\n if (to == address(0)) {\n unchecked {\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n _totalSupply -= value;\n }\n } else {\n unchecked {\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n _balances[to] += value;\n }\n }\n\n emit Transfer(from, to, value);\n }\n\n /**\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n * Relies on the `_update` mechanism\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _mint(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(address(0), account, value);\n }\n\n /**\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n * Relies on the `_update` mechanism.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead\n */\n function _burn(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n _update(account, address(0), value);\n }\n\n /**\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address owner, address spender, uint256 value) internal {\n _approve(owner, spender, value, true);\n }\n\n /**\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n *\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n * `Approval` event during `transferFrom` operations.\n *\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n * true using the following override:\n *\n * ```solidity\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n * super._approve(owner, spender, value, true);\n * }\n * ```\n *\n * Requirements are the same as {_approve}.\n */\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n if (owner == address(0)) {\n revert ERC20InvalidApprover(address(0));\n }\n if (spender == address(0)) {\n revert ERC20InvalidSpender(address(0));\n }\n _allowances[owner][spender] = value;\n if (emitEvent) {\n emit Approval(owner, spender, value);\n }\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n *\n * Does not update the allowance value in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Does not emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n if (currentAllowance < value) {\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n }\n unchecked {\n _approve(owner, spender, currentAllowance - value, false);\n }\n }\n }\n}\n"
|
|
143
|
+
},
|
|
144
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC20/extensions/IERC20Metadata.sol": {
|
|
145
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
|
|
146
|
+
},
|
|
147
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC20/IERC20.sol": {
|
|
148
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 value) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n * caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"
|
|
149
|
+
},
|
|
150
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC20/utils/SafeERC20.sol": {
|
|
151
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n * targeting contracts.\n *\n * Reverts if the returned value is other than `true`.\n */\n function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n if (to.code.length == 0) {\n safeTransfer(token, to, value);\n } else if (!token.transferAndCall(to, value, data)) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n * targeting contracts.\n *\n * Reverts if the returned value is other than `true`.\n */\n function transferFromAndCallRelaxed(\n IERC1363 token,\n address from,\n address to,\n uint256 value,\n bytes memory data\n ) internal {\n if (to.code.length == 0) {\n safeTransferFrom(token, from, to, value);\n } else if (!token.transferFromAndCall(from, to, value, data)) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n * targeting contracts.\n *\n * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n * once without retrying, and relies on the returned value to be true.\n *\n * Reverts if the returned value is other than `true`.\n */\n function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n if (to.code.length == 0) {\n forceApprove(token, to, value);\n } else if (!token.approveAndCall(to, value, data)) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly (\"memory-safe\") {\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly (\"memory-safe\") {\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}\n"
|
|
152
|
+
},
|
|
153
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC721/ERC721.sol": {
|
|
154
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"./IERC721.sol\";\nimport {IERC721Metadata} from \"./extensions/IERC721Metadata.sol\";\nimport {ERC721Utils} from \"./utils/ERC721Utils.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {Strings} from \"../../utils/Strings.sol\";\nimport {IERC165, ERC165} from \"../../utils/introspection/ERC165.sol\";\nimport {IERC721Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n mapping(uint256 tokenId => address) private _owners;\n\n mapping(address owner => uint256) private _balances;\n\n mapping(uint256 tokenId => address) private _tokenApprovals;\n\n mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual returns (uint256) {\n if (owner == address(0)) {\n revert ERC721InvalidOwner(address(0));\n }\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual returns (address) {\n return _requireOwned(tokenId);\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n _requireOwned(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual {\n _approve(to, tokenId, _msgSender());\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual returns (address) {\n _requireOwned(tokenId);\n\n return _getApproved(tokenId);\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n address previousOwner = _update(to, tokenId, _msgSender());\n if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n transferFrom(from, to, tokenId);\n ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n *\n * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n */\n function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n * particular (ignoring whether it is owned by `owner`).\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n return\n spender != address(0) &&\n (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n * Reverts if:\n * - `spender` does not have approval from `owner` for `tokenId`.\n * - `spender` does not have approval to manage all of `owner`'s assets.\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n if (!_isAuthorized(owner, spender, tokenId)) {\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else {\n revert ERC721InsufficientApproval(spender, tokenId);\n }\n }\n }\n\n /**\n * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n *\n * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n *\n * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n * remain consistent with one another.\n */\n function _increaseBalance(address account, uint128 value) internal virtual {\n unchecked {\n _balances[account] += value;\n }\n }\n\n /**\n * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n *\n * Emits a {Transfer} event.\n *\n * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n */\n function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n address from = _ownerOf(tokenId);\n\n // Perform (optional) operator check\n if (auth != address(0)) {\n _checkAuthorized(from, auth, tokenId);\n }\n\n // Execute the update\n if (from != address(0)) {\n // Clear approval. No need to re-authorize or emit the Approval event\n _approve(address(0), tokenId, address(0), false);\n\n unchecked {\n _balances[from] -= 1;\n }\n }\n\n if (to != address(0)) {\n unchecked {\n _balances[to] += 1;\n }\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n return from;\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner != address(0)) {\n revert ERC721InvalidSender(address(0));\n }\n }\n\n /**\n * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n _mint(to, tokenId);\n ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal {\n address previousOwner = _update(address(0), tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n * are aware of the ERC-721 standard to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is like {safeTransferFrom} in the sense that it invokes\n * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `tokenId` token must exist and be owned by `from`.\n * - `to` cannot be the zero address.\n * - `from` cannot be the zero address.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId) internal {\n _safeTransfer(from, to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n _transfer(from, to, tokenId);\n ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n * either the owner of the token, or approved to operate on all tokens held by this owner.\n *\n * Emits an {Approval} event.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address to, uint256 tokenId, address auth) internal {\n _approve(to, tokenId, auth, true);\n }\n\n /**\n * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n * emitted in the context of transfers.\n */\n function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n // Avoid reading the owner unless necessary\n if (emitEvent || auth != address(0)) {\n address owner = _requireOwned(tokenId);\n\n // We do not use _isAuthorized because single-token approvals should not be able to call approve\n if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n revert ERC721InvalidApprover(auth);\n }\n\n if (emitEvent) {\n emit Approval(owner, to, tokenId);\n }\n }\n\n _tokenApprovals[tokenId] = to;\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Requirements:\n * - operator can't be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n if (operator == address(0)) {\n revert ERC721InvalidOperator(operator);\n }\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n * Returns the owner.\n *\n * Overrides to ownership logic should be done to {_ownerOf}.\n */\n function _requireOwned(uint256 tokenId) internal view returns (address) {\n address owner = _ownerOf(tokenId);\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n return owner;\n }\n}\n"
|
|
155
|
+
},
|
|
156
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC721/extensions/IERC721Metadata.sol": {
|
|
157
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
|
|
158
|
+
},
|
|
159
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC721/IERC721.sol": {
|
|
160
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC-721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC-721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n * {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
|
|
161
|
+
},
|
|
162
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC721/IERC721Receiver.sol": {
|
|
163
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC-721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC-721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n * reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
|
|
164
|
+
},
|
|
165
|
+
"npm/@openzeppelin/contracts@5.1.0/token/ERC721/utils/ERC721Utils.sol": {
|
|
166
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/utils/ERC721Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721Receiver} from \"../IERC721Receiver.sol\";\nimport {IERC721Errors} from \"../../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Library that provide common ERC-721 utility functions.\n *\n * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].\n *\n * _Available since v5.1._\n */\nlibrary ERC721Utils {\n /**\n * @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}\n * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).\n *\n * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).\n * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept\n * the transfer.\n */\n function checkOnERC721Received(\n address operator,\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal {\n if (to.code.length > 0) {\n try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {\n if (retval != IERC721Receiver.onERC721Received.selector) {\n // Token rejected\n revert IERC721Errors.ERC721InvalidReceiver(to);\n }\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n // non-IERC721Receiver implementer\n revert IERC721Errors.ERC721InvalidReceiver(to);\n } else {\n assembly (\"memory-safe\") {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n }\n }\n}\n"
|
|
167
|
+
},
|
|
168
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Address.sol": {
|
|
169
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n assembly (\"memory-safe\") {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert Errors.FailedCall();\n }\n }\n}\n"
|
|
170
|
+
},
|
|
171
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Base64.sol": {
|
|
172
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Base64.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n * See sections 4 and 5 of https://datatracker.ietf.org/doc/html/rfc4648\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n string internal constant _TABLE_URL = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n return _encode(data, _TABLE, true);\n }\n\n /**\n * @dev Converts a `bytes` to its Bytes64Url `string` representation.\n * Output is not padded with `=` as specified in https://www.rfc-editor.org/rfc/rfc4648[rfc4648].\n */\n function encodeURL(bytes memory data) internal pure returns (string memory) {\n return _encode(data, _TABLE_URL, false);\n }\n\n /**\n * @dev Internal table-agnostic conversion\n */\n function _encode(bytes memory data, string memory table, bool withPadding) private pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // If padding is enabled, the final length should be `bytes` data length divided by 3 rounded up and then\n // multiplied by 4 so that it leaves room for padding the last chunk\n // - `data.length + 2` -> Prepare for division rounding up\n // - `/ 3` -> Number of 3-bytes chunks (rounded up)\n // - `4 *` -> 4 characters for each chunk\n // This is equivalent to: 4 * Math.ceil(data.length / 3)\n //\n // If padding is disabled, the final length should be `bytes` data length multiplied by 4/3 rounded up as\n // opposed to when padding is required to fill the last chunk.\n // - `4 * data.length` -> 4 characters for each chunk\n // - ` + 2` -> Prepare for division rounding up\n // - `/ 3` -> Number of 3-bytes chunks (rounded up)\n // This is equivalent to: Math.ceil((4 * data.length) / 3)\n uint256 resultLength = withPadding ? 4 * ((data.length + 2) / 3) : (4 * data.length + 2) / 3;\n\n string memory result = new string(resultLength);\n\n assembly (\"memory-safe\") {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 0x20)\n let dataPtr := data\n let endPtr := add(data, mload(data))\n\n // In some cases, the last iteration will read bytes after the end of the data. We cache the value, and\n // set it to zero to make sure no dirty bytes are read in that section.\n let afterPtr := add(endPtr, 0x20)\n let afterCache := mload(afterPtr)\n mstore(afterPtr, 0x00)\n\n // Run over the input, 3 bytes at a time\n for {\n\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 byte (24 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F to bitmask the least significant 6 bits.\n // Use this as an index into the lookup table, mload an entire word\n // so the desired character is in the least significant byte, and\n // mstore8 this least significant byte into the result and continue.\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // Reset the value that was cached\n mstore(afterPtr, afterCache)\n\n if withPadding {\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n }\n\n return result;\n }\n}\n"
|
|
173
|
+
},
|
|
174
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Context.sol": {
|
|
175
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}\n"
|
|
176
|
+
},
|
|
177
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Create2.sol": {
|
|
178
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n /**\n * @dev There's no code to deploy.\n */\n error Create2EmptyBytecode();\n\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n if (bytecode.length == 0) {\n revert Create2EmptyBytecode();\n }\n assembly (\"memory-safe\") {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n // if no address was created, and returndata is not empty, bubble revert\n if and(iszero(addr), not(iszero(returndatasize()))) {\n let p := mload(0x40)\n returndatacopy(p, 0, returndatasize())\n revert(p, returndatasize())\n }\n }\n if (addr == address(0)) {\n revert Errors.FailedDeployment();\n }\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n assembly (\"memory-safe\") {\n let ptr := mload(0x40) // Get free memory pointer\n\n // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |\n // |-------------------|---------------------------------------------------------------------------|\n // | bytecodeHash | CCCCCCCCCCCCC...CC |\n // | salt | BBBBBBBBBBBBB...BB |\n // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |\n // | 0xFF | FF |\n // |-------------------|---------------------------------------------------------------------------|\n // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n mstore(add(ptr, 0x40), bytecodeHash)\n mstore(add(ptr, 0x20), salt)\n mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n mstore8(start, 0xff)\n addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)\n }\n }\n}\n"
|
|
179
|
+
},
|
|
180
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/cryptography/ECDSA.sol": {
|
|
181
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS\n }\n\n /**\n * @dev The signature derives the `address(0)`.\n */\n error ECDSAInvalidSignature();\n\n /**\n * @dev The signature has an invalid length.\n */\n error ECDSAInvalidSignatureLength(uint256 length);\n\n /**\n * @dev The signature has an S value that is in the upper half order.\n */\n error ECDSAInvalidSignatureS(bytes32 s);\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n * and a bytes32 providing additional information about the error.\n *\n * If no error is returned, then the address can be used for verification purposes.\n *\n * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n */\n function tryRecover(\n bytes32 hash,\n bytes memory signature\n ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly (\"memory-safe\") {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n _throwError(error, errorArg);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n unchecked {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n // We do not check for an overflow here since the shift operation results in 0 or 1.\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n */\n function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n _throwError(error, errorArg);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS, s);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature, bytes32(0));\n }\n\n return (signer, RecoverError.NoError, bytes32(0));\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n _throwError(error, errorArg);\n return recovered;\n }\n\n /**\n * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n */\n function _throwError(RecoverError error, bytes32 errorArg) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert ECDSAInvalidSignature();\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert ECDSAInvalidSignatureLength(uint256(errorArg));\n } else if (error == RecoverError.InvalidSignatureS) {\n revert ECDSAInvalidSignatureS(errorArg);\n }\n }\n}\n"
|
|
182
|
+
},
|
|
183
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/cryptography/MessageHashUtils.sol": {
|
|
184
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n /**\n * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n * `0x45` (`personal_sign` messages).\n *\n * The digest is calculated by prefixing a bytes32 `messageHash` with\n * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n *\n * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n * keccak256, although any bytes32 value can be safely used because the final digest will\n * be re-hashed.\n *\n * See {ECDSA-recover}.\n */\n function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n assembly (\"memory-safe\") {\n mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n }\n }\n\n /**\n * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n * `0x45` (`personal_sign` messages).\n *\n * The digest is calculated by prefixing an arbitrary `message` with\n * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n *\n * See {ECDSA-recover}.\n */\n function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n return\n keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n }\n\n /**\n * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n * `0x00` (data with intended validator).\n *\n * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n * `validator` address. Then hashing the result.\n *\n * See {ECDSA-recover}.\n */\n function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n }\n\n /**\n * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n *\n * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n *\n * See {ECDSA-recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n assembly (\"memory-safe\") {\n let ptr := mload(0x40)\n mstore(ptr, hex\"19_01\")\n mstore(add(ptr, 0x02), domainSeparator)\n mstore(add(ptr, 0x22), structHash)\n digest := keccak256(ptr, 0x42)\n }\n }\n}\n"
|
|
185
|
+
},
|
|
186
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Errors.sol": {
|
|
187
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n\n /**\n * @dev A necessary precompile is missing.\n */\n error MissingPrecompile(address);\n}\n"
|
|
188
|
+
},
|
|
189
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/introspection/ERC165.sol": {
|
|
190
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
|
|
191
|
+
},
|
|
192
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/introspection/IERC165.sol": {
|
|
193
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
|
|
194
|
+
},
|
|
195
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/math/Math.sol": {
|
|
196
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n *\n * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n * one branch when needed, making this function more expensive.\n */\n function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n unchecked {\n // branchless ternary works because:\n // b ^ (a ^ b) == a\n // b ^ 0 == b\n return b ^ ((a ^ b) * SafeCast.toUint(condition));\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return ternary(a > b, a, b);\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return ternary(a < b, a, b);\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n Panic.panic(Panic.DIVISION_BY_ZERO);\n }\n\n // The following calculation ensures accurate ceiling division without overflow.\n // Since a is non-zero, (a - 1) / b will not overflow.\n // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n // but the largest value we can obtain is type(uint256).max - 1, which happens\n // when a = type(uint256).max and b = 1.\n unchecked {\n return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n }\n }\n\n /**\n * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n *\n * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2²⁵⁶ + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n if (denominator <= prod1) {\n Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n inverse *= 2 - denominator * inverse; // inverse mod 2³²\n inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n }\n\n /**\n * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n *\n * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n *\n * If the input value is not inversible, 0 is returned.\n *\n * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n */\n function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n unchecked {\n if (n == 0) return 0;\n\n // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n // ax + ny = 1\n // ax = 1 + (-y)n\n // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n // If the remainder is 0 the gcd is n right away.\n uint256 remainder = a % n;\n uint256 gcd = n;\n\n // Therefore the initial coefficients are:\n // ax + ny = gcd(a, n) = n\n // 0a + 1n = n\n int256 x = 0;\n int256 y = 1;\n\n while (remainder != 0) {\n uint256 quotient = gcd / remainder;\n\n (gcd, remainder) = (\n // The old remainder is the next gcd to try.\n remainder,\n // Compute the next remainder.\n // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n // where gcd is at most n (capped to type(uint256).max)\n gcd - remainder * quotient\n );\n\n (x, y) = (\n // Increment the coefficient of a.\n y,\n // Decrement the coefficient of n.\n // Can overflow, but the result is casted to uint256 so that the\n // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n x - y * int256(quotient)\n );\n }\n\n if (gcd != 1) return 0; // No inverse exists.\n return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n }\n }\n\n /**\n * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n *\n * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n *\n * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n */\n function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n unchecked {\n return Math.modExp(a, p - 2, p);\n }\n }\n\n /**\n * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n *\n * Requirements:\n * - modulus can't be zero\n * - underlying staticcall to precompile must succeed\n *\n * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n * interpreted as 0.\n */\n function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n (bool success, uint256 result) = tryModExp(b, e, m);\n if (!success) {\n Panic.panic(Panic.DIVISION_BY_ZERO);\n }\n return result;\n }\n\n /**\n * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n * to operate modulo 0 or if the underlying precompile reverted.\n *\n * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n * of a revert, but the result may be incorrectly interpreted as 0.\n */\n function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n if (m == 0) return (false, 0);\n assembly (\"memory-safe\") {\n let ptr := mload(0x40)\n // | Offset | Content | Content (Hex) |\n // |-----------|------------|--------------------------------------------------------------------|\n // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n mstore(ptr, 0x20)\n mstore(add(ptr, 0x20), 0x20)\n mstore(add(ptr, 0x40), 0x20)\n mstore(add(ptr, 0x60), b)\n mstore(add(ptr, 0x80), e)\n mstore(add(ptr, 0xa0), m)\n\n // Given the result < m, it's guaranteed to fit in 32 bytes,\n // so we can use the memory scratch space located at offset 0.\n success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n result := mload(0x00)\n }\n }\n\n /**\n * @dev Variant of {modExp} that supports inputs of arbitrary length.\n */\n function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n (bool success, bytes memory result) = tryModExp(b, e, m);\n if (!success) {\n Panic.panic(Panic.DIVISION_BY_ZERO);\n }\n return result;\n }\n\n /**\n * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n */\n function tryModExp(\n bytes memory b,\n bytes memory e,\n bytes memory m\n ) internal view returns (bool success, bytes memory result) {\n if (_zeroBytes(m)) return (false, new bytes(0));\n\n uint256 mLen = m.length;\n\n // Encode call args in result and move the free memory pointer\n result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n assembly (\"memory-safe\") {\n let dataPtr := add(result, 0x20)\n // Write result on top of args to avoid allocating extra memory.\n success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n // Overwrite the length.\n // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n mstore(result, mLen)\n // Set the memory pointer after the returned data.\n mstore(0x40, add(dataPtr, mLen))\n }\n }\n\n /**\n * @dev Returns whether the provided byte array is zero.\n */\n function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n for (uint256 i = 0; i < byteArray.length; ++i) {\n if (byteArray[i] != 0) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n * using integer operations.\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n unchecked {\n // Take care of easy edge cases when a == 0 or a == 1\n if (a <= 1) {\n return a;\n }\n\n // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n // the current value as `ε_n = | x_n - sqrt(a) |`.\n //\n // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n // bigger than any uint256.\n //\n // By noticing that\n // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n // to the msb function.\n uint256 aa = a;\n uint256 xn = 1;\n\n if (aa >= (1 << 128)) {\n aa >>= 128;\n xn <<= 64;\n }\n if (aa >= (1 << 64)) {\n aa >>= 64;\n xn <<= 32;\n }\n if (aa >= (1 << 32)) {\n aa >>= 32;\n xn <<= 16;\n }\n if (aa >= (1 << 16)) {\n aa >>= 16;\n xn <<= 8;\n }\n if (aa >= (1 << 8)) {\n aa >>= 8;\n xn <<= 4;\n }\n if (aa >= (1 << 4)) {\n aa >>= 4;\n xn <<= 2;\n }\n if (aa >= (1 << 2)) {\n xn <<= 1;\n }\n\n // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n //\n // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n // This is going to be our x_0 (and ε_0)\n xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n // From here, Newton's method give us:\n // x_{n+1} = (x_n + a / x_n) / 2\n //\n // One should note that:\n // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n // = ((x_n² + a) / (2 * x_n))² - a\n // = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n // = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n // = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n // = (x_n² - a)² / (2 * x_n)²\n // = ((x_n² - a) / (2 * x_n))²\n // ≥ 0\n // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n //\n // This gives us the proof of quadratic convergence of the sequence:\n // ε_{n+1} = | x_{n+1} - sqrt(a) |\n // = | (x_n + a / x_n) / 2 - sqrt(a) |\n // = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n // = | (x_n - sqrt(a))² / (2 * x_n) |\n // = | ε_n² / (2 * x_n) |\n // = ε_n² / | (2 * x_n) |\n //\n // For the first iteration, we have a special case where x_0 is known:\n // ε_1 = ε_0² / | (2 * x_0) |\n // ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n // ≤ 2**(2*e-4) / (3 * 2**(e-1))\n // ≤ 2**(e-3) / 3\n // ≤ 2**(e-3-log2(3))\n // ≤ 2**(e-4.5)\n //\n // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n // ε_{n+1} = ε_n² / | (2 * x_n) |\n // ≤ (2**(e-k))² / (2 * 2**(e-1))\n // ≤ 2**(2*e-2*k) / 2**e\n // ≤ 2**(e-2*k)\n xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above\n xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5\n xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9\n xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18\n xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36\n xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72\n\n // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n // sqrt(a) or sqrt(a) + 1.\n return xn - SafeCast.toUint(xn > a / xn);\n }\n }\n\n /**\n * @dev Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n uint256 exp;\n unchecked {\n exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);\n value >>= exp;\n result += exp;\n\n exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);\n value >>= exp;\n result += exp;\n\n exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);\n value >>= exp;\n result += exp;\n\n exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);\n value >>= exp;\n result += exp;\n\n exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);\n value >>= exp;\n result += exp;\n\n exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);\n value >>= exp;\n result += exp;\n\n exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);\n value >>= exp;\n result += exp;\n\n result += SafeCast.toUint(value > 1);\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n uint256 isGt;\n unchecked {\n isGt = SafeCast.toUint(value > (1 << 128) - 1);\n value >>= isGt * 128;\n result += isGt * 16;\n\n isGt = SafeCast.toUint(value > (1 << 64) - 1);\n value >>= isGt * 64;\n result += isGt * 8;\n\n isGt = SafeCast.toUint(value > (1 << 32) - 1);\n value >>= isGt * 32;\n result += isGt * 4;\n\n isGt = SafeCast.toUint(value > (1 << 16) - 1);\n value >>= isGt * 16;\n result += isGt * 2;\n\n result += SafeCast.toUint(value > (1 << 8) - 1);\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"
|
|
197
|
+
},
|
|
198
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/math/SafeCast.sol": {
|
|
199
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n /**\n * @dev Value doesn't fit in an uint of `bits` size.\n */\n error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n /**\n * @dev An int value doesn't fit in an uint of `bits` size.\n */\n error SafeCastOverflowedIntToUint(int256 value);\n\n /**\n * @dev Value doesn't fit in an int of `bits` size.\n */\n error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n /**\n * @dev An uint value doesn't fit in an int of `bits` size.\n */\n error SafeCastOverflowedUintToInt(uint256 value);\n\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n if (value > type(uint248).max) {\n revert SafeCastOverflowedUintDowncast(248, value);\n }\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n if (value > type(uint240).max) {\n revert SafeCastOverflowedUintDowncast(240, value);\n }\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n if (value > type(uint232).max) {\n revert SafeCastOverflowedUintDowncast(232, value);\n }\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n if (value > type(uint224).max) {\n revert SafeCastOverflowedUintDowncast(224, value);\n }\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n if (value > type(uint216).max) {\n revert SafeCastOverflowedUintDowncast(216, value);\n }\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n if (value > type(uint208).max) {\n revert SafeCastOverflowedUintDowncast(208, value);\n }\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n if (value > type(uint200).max) {\n revert SafeCastOverflowedUintDowncast(200, value);\n }\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n if (value > type(uint192).max) {\n revert SafeCastOverflowedUintDowncast(192, value);\n }\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n if (value > type(uint184).max) {\n revert SafeCastOverflowedUintDowncast(184, value);\n }\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n if (value > type(uint176).max) {\n revert SafeCastOverflowedUintDowncast(176, value);\n }\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n if (value > type(uint168).max) {\n revert SafeCastOverflowedUintDowncast(168, value);\n }\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n if (value > type(uint160).max) {\n revert SafeCastOverflowedUintDowncast(160, value);\n }\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n if (value > type(uint152).max) {\n revert SafeCastOverflowedUintDowncast(152, value);\n }\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n if (value > type(uint144).max) {\n revert SafeCastOverflowedUintDowncast(144, value);\n }\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n if (value > type(uint136).max) {\n revert SafeCastOverflowedUintDowncast(136, value);\n }\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n if (value > type(uint128).max) {\n revert SafeCastOverflowedUintDowncast(128, value);\n }\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n if (value > type(uint120).max) {\n revert SafeCastOverflowedUintDowncast(120, value);\n }\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n if (value > type(uint112).max) {\n revert SafeCastOverflowedUintDowncast(112, value);\n }\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n if (value > type(uint104).max) {\n revert SafeCastOverflowedUintDowncast(104, value);\n }\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n if (value > type(uint96).max) {\n revert SafeCastOverflowedUintDowncast(96, value);\n }\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n if (value > type(uint88).max) {\n revert SafeCastOverflowedUintDowncast(88, value);\n }\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n if (value > type(uint80).max) {\n revert SafeCastOverflowedUintDowncast(80, value);\n }\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n if (value > type(uint72).max) {\n revert SafeCastOverflowedUintDowncast(72, value);\n }\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n if (value > type(uint64).max) {\n revert SafeCastOverflowedUintDowncast(64, value);\n }\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n if (value > type(uint56).max) {\n revert SafeCastOverflowedUintDowncast(56, value);\n }\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n if (value > type(uint48).max) {\n revert SafeCastOverflowedUintDowncast(48, value);\n }\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n if (value > type(uint40).max) {\n revert SafeCastOverflowedUintDowncast(40, value);\n }\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n if (value > type(uint32).max) {\n revert SafeCastOverflowedUintDowncast(32, value);\n }\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n if (value > type(uint24).max) {\n revert SafeCastOverflowedUintDowncast(24, value);\n }\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n if (value > type(uint16).max) {\n revert SafeCastOverflowedUintDowncast(16, value);\n }\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n if (value > type(uint8).max) {\n revert SafeCastOverflowedUintDowncast(8, value);\n }\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n if (value < 0) {\n revert SafeCastOverflowedIntToUint(value);\n }\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(248, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(240, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(232, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(224, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(216, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(208, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(200, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(192, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(184, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(176, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(168, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(160, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(152, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(144, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(136, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\n downcasted = int128(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(128, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(120, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(112, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(104, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(96, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(88, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(80, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(72, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\n downcasted = int64(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(64, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(56, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(48, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(40, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\n downcasted = int32(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(32, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(24, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\n downcasted = int16(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(16, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n */\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\n downcasted = int8(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(8, value);\n }\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n if (value > uint256(type(int256).max)) {\n revert SafeCastOverflowedUintToInt(value);\n }\n return int256(value);\n }\n\n /**\n * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n */\n function toUint(bool b) internal pure returns (uint256 u) {\n assembly (\"memory-safe\") {\n u := iszero(iszero(b))\n }\n }\n}\n"
|
|
200
|
+
},
|
|
201
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/math/SignedMath.sol": {
|
|
202
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n *\n * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n * one branch when needed, making this function more expensive.\n */\n function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n unchecked {\n // branchless ternary works because:\n // b ^ (a ^ b) == a\n // b ^ 0 == b\n return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n }\n }\n\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return ternary(a > b, a, b);\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return ternary(a < b, a, b);\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n int256 mask = n >> 255;\n\n // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n return uint256((n + mask) ^ mask);\n }\n }\n}\n"
|
|
203
|
+
},
|
|
204
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Panic.sol": {
|
|
205
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n * using Panic for uint256;\n *\n * // Use any of the declared internal constants\n * function foo() { Panic.GENERIC.panic(); }\n *\n * // Alternatively\n * function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n /// @dev generic / unspecified error\n uint256 internal constant GENERIC = 0x00;\n /// @dev used by the assert() builtin\n uint256 internal constant ASSERT = 0x01;\n /// @dev arithmetic underflow or overflow\n uint256 internal constant UNDER_OVERFLOW = 0x11;\n /// @dev division or modulo by zero\n uint256 internal constant DIVISION_BY_ZERO = 0x12;\n /// @dev enum conversion error\n uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n /// @dev invalid encoding in storage\n uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n /// @dev empty array pop\n uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n /// @dev array out of bounds access\n uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n /// @dev resource error (too large allocation or too large array)\n uint256 internal constant RESOURCE_ERROR = 0x41;\n /// @dev calling invalid internal function\n uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n /// @dev Reverts with a panic code. Recommended to use with\n /// the internal constants with predefined codes.\n function panic(uint256 code) internal pure {\n assembly (\"memory-safe\") {\n mstore(0x00, 0x4e487b71)\n mstore(0x20, code)\n revert(0x1c, 0x24)\n }\n }\n}\n"
|
|
206
|
+
},
|
|
207
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Pausable.sol": {
|
|
208
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n bool private _paused;\n\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n /**\n * @dev The operation failed because the contract is paused.\n */\n error EnforcedPause();\n\n /**\n * @dev The operation failed because the contract is not paused.\n */\n error ExpectedPause();\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n if (paused()) {\n revert EnforcedPause();\n }\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n if (!paused()) {\n revert ExpectedPause();\n }\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n}\n"
|
|
209
|
+
},
|
|
210
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/ReentrancyGuard.sol": {
|
|
211
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n uint256 private _status;\n\n /**\n * @dev Unauthorized reentrant call.\n */\n error ReentrancyGuardReentrantCall();\n\n constructor() {\n _status = NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be NOT_ENTERED\n if (_status == ENTERED) {\n revert ReentrancyGuardReentrantCall();\n }\n\n // Any calls to nonReentrant after this point will fail\n _status = ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n return _status == ENTERED;\n }\n}\n"
|
|
212
|
+
},
|
|
213
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/StorageSlot.sol": {
|
|
214
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct Int256Slot {\n int256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n */\n function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns a `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n assembly (\"memory-safe\") {\n r.slot := store.slot\n }\n }\n}\n"
|
|
215
|
+
},
|
|
216
|
+
"npm/@openzeppelin/contracts@5.1.0/utils/Strings.sol": {
|
|
217
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n uint8 private constant ADDRESS_LENGTH = 20;\n\n /**\n * @dev The `value` string doesn't fit in the specified `length`.\n */\n error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n assembly (\"memory-safe\") {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n assembly (\"memory-safe\") {\n mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toStringSigned(int256 value) internal pure returns (string memory) {\n return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n uint256 localValue = value;\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = HEX_DIGITS[localValue & 0xf];\n localValue >>= 4;\n }\n if (localValue != 0) {\n revert StringsInsufficientHexLength(value, length);\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n * representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n * representation, according to EIP-55.\n */\n function toChecksumHexString(address addr) internal pure returns (string memory) {\n bytes memory buffer = bytes(toHexString(addr));\n\n // hash the hex part of buffer (skip length + 2 bytes, length 40)\n uint256 hashValue;\n assembly (\"memory-safe\") {\n hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n }\n\n for (uint256 i = 41; i > 1; --i) {\n // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n // case shift by xoring with 0x20\n buffer[i] ^= 0x20;\n }\n hashValue >>= 4;\n }\n return string(buffer);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
|
|
218
|
+
},
|
|
219
|
+
"npm/@uniswap/v3-core@1.0.1/contracts/interfaces/callback/IUniswapV3SwapCallback.sol": {
|
|
220
|
+
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n"
|
|
221
|
+
},
|
|
222
|
+
"npm/@uniswap/v3-periphery@1.4.4/contracts/interfaces/IPeripheryPayments.sol": {
|
|
223
|
+
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n /// @param amountMinimum The minimum amount of WETH9 to unwrap\n /// @param recipient The address receiving ETH\n function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;\n\n /// @notice Refunds any ETH balance held by this contract to the `msg.sender`\n /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps\n /// that use ether for the input amount\n function refundETH() external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n /// @param token The contract address of the token which will be transferred to `recipient`\n /// @param amountMinimum The minimum amount of token required for a transfer\n /// @param recipient The destination address of the token\n function sweepToken(\n address token,\n uint256 amountMinimum,\n address recipient\n ) external payable;\n}\n"
|
|
224
|
+
},
|
|
225
|
+
"npm/@uniswap/v3-periphery@1.4.4/contracts/interfaces/ISwapRouter.sol": {
|
|
226
|
+
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter is IUniswapV3SwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n"
|
|
227
|
+
},
|
|
228
|
+
"project/contracts/core/BaseAccount.sol": {
|
|
229
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-empty-blocks */\n\nimport \"../interfaces/IAccount.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"./UserOperationLib.sol\";\n\n/**\n * Basic account implementation.\n * This contract provides the basic logic for implementing the IAccount interface - validateUserOp\n * Specific account implementation should inherit it and provide the account-specific logic.\n */\nabstract contract BaseAccount is IAccount {\n using UserOperationLib for PackedUserOperation;\n\n /**\n * Return the account nonce.\n * This method returns the next sequential nonce.\n * For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function getNonce() public view virtual returns (uint256) {\n return entryPoint().getNonce(address(this), 0);\n }\n\n /**\n * Return the entryPoint used by this account.\n * Subclass should return the current entryPoint used by this account.\n */\n function entryPoint() public view virtual returns (IEntryPoint);\n\n /// @inheritdoc IAccount\n function validateUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n _requireFromEntryPoint();\n validationData = _validateSignature(userOp, userOpHash);\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * Ensure the request comes from the known entrypoint.\n */\n function _requireFromEntryPoint() internal view virtual {\n require(\n msg.sender == address(entryPoint()),\n \"account: not from EntryPoint\"\n );\n }\n\n /**\n * Validate the signature is valid for this message.\n * @param userOp - Validate the userOp.signature field.\n * @param userOpHash - Convenient field: the hash of the request, to check the signature against.\n * (also hashes the entrypoint and chain id)\n * @return validationData - Signature and time-range of this operation.\n * <20-byte> aggregatorOrSigFail - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an aggregator contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return\n * SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function _validateSignature(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (uint256 validationData);\n\n /**\n * Validate the nonce of the UserOperation.\n * This method may validate the nonce requirement of this account.\n * e.g.\n * To limit the nonce to use sequenced UserOps only (no \"out of order\" UserOps):\n * `require(nonce < type(uint64).max)`\n * For a hypothetical account that *requires* the nonce to be out-of-order:\n * `require(nonce & type(uint64).max == 0)`\n *\n * The actual nonce uniqueness is managed by the EntryPoint, and thus no other\n * action is needed by the account itself.\n *\n * @param nonce to validate\n *\n * solhint-disable-next-line no-empty-blocks\n */\n function _validateNonce(uint256 nonce) internal view virtual {\n }\n\n /**\n * Sends to the entrypoint (msg.sender) the missing funds for this transaction.\n * SubClass MAY override this method for better funds management\n * (e.g. send to the entryPoint more than the minimum required, so that in future transactions\n * it will not be required to send again).\n * @param missingAccountFunds - The minimum value this method should send the entrypoint.\n * This value MAY be zero, in case there is enough deposit,\n * or the userOp has a paymaster.\n */\n function _payPrefund(uint256 missingAccountFunds) internal virtual {\n if (missingAccountFunds != 0) {\n (bool success, ) = payable(msg.sender).call{\n value: missingAccountFunds,\n gas: type(uint256).max\n }(\"\");\n (success);\n //ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n}\n"
|
|
230
|
+
},
|
|
231
|
+
"project/contracts/core/BasePaymaster.sol": {
|
|
232
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"../interfaces/IPaymaster.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"./UserOperationLib.sol\";\n/**\n * Helper class for creating a paymaster.\n * provides helper methods for staking.\n * Validates that the postOp is called only by the entryPoint.\n */\nabstract contract BasePaymaster is IPaymaster, Ownable {\n IEntryPoint public immutable entryPoint;\n\n uint256 internal constant PAYMASTER_VALIDATION_GAS_OFFSET = UserOperationLib.PAYMASTER_VALIDATION_GAS_OFFSET;\n uint256 internal constant PAYMASTER_POSTOP_GAS_OFFSET = UserOperationLib.PAYMASTER_POSTOP_GAS_OFFSET;\n uint256 internal constant PAYMASTER_DATA_OFFSET = UserOperationLib.PAYMASTER_DATA_OFFSET;\n\n constructor(IEntryPoint _entryPoint) Ownable(msg.sender) {\n _validateEntryPointInterface(_entryPoint);\n entryPoint = _entryPoint;\n }\n\n //sanity check: make sure this EntryPoint was compiled against the same\n // IEntryPoint of this paymaster\n function _validateEntryPointInterface(IEntryPoint _entryPoint) internal virtual {\n require(IERC165(address(_entryPoint)).supportsInterface(type(IEntryPoint).interfaceId), \"IEntryPoint interface mismatch\");\n }\n\n /// @inheritdoc IPaymaster\n function validatePaymasterUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) external override returns (bytes memory context, uint256 validationData) {\n _requireFromEntryPoint();\n return _validatePaymasterUserOp(userOp, userOpHash, maxCost);\n }\n\n /**\n * Validate a user operation.\n * @param userOp - The user operation.\n * @param userOpHash - The hash of the user operation.\n * @param maxCost - The maximum cost of the user operation.\n */\n function _validatePaymasterUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) internal virtual returns (bytes memory context, uint256 validationData);\n\n /// @inheritdoc IPaymaster\n function postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost,\n uint256 actualUserOpFeePerGas\n ) external override {\n _requireFromEntryPoint();\n _postOp(mode, context, actualGasCost, actualUserOpFeePerGas);\n }\n\n /**\n * Post-operation handler.\n * (verified to be called only through the entryPoint)\n * @dev If subclass returns a non-empty context from validatePaymasterUserOp,\n * it must also implement this method.\n * @param mode - Enum with the following options:\n * opSucceeded - User operation succeeded.\n * opReverted - User op reverted. The paymaster still has to pay for gas.\n * postOpReverted - never passed in a call to postOp().\n * @param context - The context value returned by validatePaymasterUserOp\n * @param actualGasCost - Actual gas used so far (without this postOp call).\n * @param actualUserOpFeePerGas - the gas price this UserOp pays. This value is based on the UserOp's maxFeePerGas\n * and maxPriorityFee (and basefee)\n * It is not the same as tx.gasprice, which is what the bundler pays.\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost,\n uint256 actualUserOpFeePerGas\n ) internal virtual {\n (mode, context, actualGasCost, actualUserOpFeePerGas); // unused params\n // subclass must override this method if validatePaymasterUserOp returns a context\n revert(\"must override\");\n }\n\n /**\n * Add a deposit for this paymaster, used for paying for transaction fees.\n */\n function deposit() public payable {\n entryPoint.depositTo{value: msg.value}(address(this));\n }\n\n /**\n * Withdraw value from the deposit.\n * @param withdrawAddress - Target to send to.\n * @param amount - Amount to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 amount\n ) public onlyOwner {\n entryPoint.withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * Add stake for this paymaster.\n * This method can also carry eth value to add to the current stake.\n * @param unstakeDelaySec - The unstake delay for this paymaster. Can only be increased.\n */\n function addStake(uint32 unstakeDelaySec) external payable onlyOwner {\n entryPoint.addStake{value: msg.value}(unstakeDelaySec);\n }\n\n /**\n * Return current paymaster's deposit on the entryPoint.\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint.balanceOf(address(this));\n }\n\n /**\n * Unlock the stake, in order to withdraw it.\n * The paymaster can't serve requests once unlocked, until it calls addStake again\n */\n function unlockStake() external onlyOwner {\n entryPoint.unlockStake();\n }\n\n /**\n * Withdraw the entire paymaster's stake.\n * stake must be unlocked first (and then wait for the unstakeDelay to be over)\n * @param withdrawAddress - The address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external onlyOwner {\n entryPoint.withdrawStake(withdrawAddress);\n }\n\n /**\n * Validate the call is made from a valid entrypoint\n */\n function _requireFromEntryPoint() internal virtual {\n require(msg.sender == address(entryPoint), \"Sender not EntryPoint\");\n }\n}\n"
|
|
233
|
+
},
|
|
234
|
+
"project/contracts/core/EntryPoint.sol": {
|
|
235
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n\nimport \"../interfaces/IAccount.sol\";\nimport \"../interfaces/IAccountExecute.sol\";\nimport \"../interfaces/IPaymaster.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\n\nimport \"../utils/Exec.sol\";\nimport \"./StakeManager.sol\";\nimport \"./SenderCreator.sol\";\nimport \"./Helpers.sol\";\nimport \"./NonceManager.sol\";\nimport \"./UserOperationLib.sol\";\n\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\n/*\n * Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n * Only one instance required on each chain.\n */\n\n/// @custom:security-contact https://bounty.ethereum.org\ncontract EntryPoint is IEntryPoint, StakeManager, NonceManager, ReentrancyGuard, ERC165 {\n\n using UserOperationLib for PackedUserOperation;\n\n SenderCreator private immutable _senderCreator = new SenderCreator();\n\n function senderCreator() internal view virtual returns (SenderCreator) {\n return _senderCreator;\n }\n\n //compensate for innerHandleOps' emit message and deposit refund.\n // allow some slack for future gas price changes.\n uint256 private constant INNER_GAS_OVERHEAD = 10000;\n\n // Marker for inner call revert on out of gas\n bytes32 private constant INNER_OUT_OF_GAS = hex\"deaddead\";\n bytes32 private constant INNER_REVERT_LOW_PREFUND = hex\"deadaa51\";\n\n uint256 private constant REVERT_REASON_MAX_LEN = 2048;\n uint256 private constant PENALTY_PERCENT = 10;\n\n /// @inheritdoc IERC165\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n // note: solidity \"type(IEntryPoint).interfaceId\" is without inherited methods but we want to check everything\n return interfaceId == (type(IEntryPoint).interfaceId ^ type(IStakeManager).interfaceId ^ type(INonceManager).interfaceId) ||\n interfaceId == type(IEntryPoint).interfaceId ||\n interfaceId == type(IStakeManager).interfaceId ||\n interfaceId == type(INonceManager).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * Compensate the caller's beneficiary address with the collected fees of all UserOperations.\n * @param beneficiary - The address to receive the fees.\n * @param amount - Amount to transfer.\n */\n function _compensate(address payable beneficiary, uint256 amount) internal {\n require(beneficiary != address(0), \"AA90 invalid beneficiary\");\n (bool success, ) = beneficiary.call{value: amount}(\"\");\n require(success, \"AA91 failed send to beneficiary\");\n }\n\n /**\n * Execute a user operation.\n * @param opIndex - Index into the opInfo array.\n * @param userOp - The userOp to execute.\n * @param opInfo - The opInfo filled by validatePrepayment for this userOp.\n * @return collected - The total amount this userOp paid.\n */\n function _executeUserOp(\n uint256 opIndex,\n PackedUserOperation calldata userOp,\n UserOpInfo memory opInfo\n )\n internal\n returns\n (uint256 collected) {\n uint256 preGas = gasleft();\n bytes memory context = getMemoryBytesFromOffset(opInfo.contextOffset);\n bool success;\n {\n uint256 saveFreePtr;\n assembly (\"memory-safe\") {\n saveFreePtr := mload(0x40)\n }\n bytes calldata callData = userOp.callData;\n bytes memory innerCall;\n bytes4 methodSig;\n assembly {\n let len := callData.length\n if gt(len, 3) {\n methodSig := calldataload(callData.offset)\n }\n }\n if (methodSig == IAccountExecute.executeUserOp.selector) {\n bytes memory executeUserOp = abi.encodeCall(IAccountExecute.executeUserOp, (userOp, opInfo.userOpHash));\n innerCall = abi.encodeCall(this.innerHandleOp, (executeUserOp, opInfo, context));\n } else\n {\n innerCall = abi.encodeCall(this.innerHandleOp, (callData, opInfo, context));\n }\n assembly (\"memory-safe\") {\n success := call(gas(), address(), 0, add(innerCall, 0x20), mload(innerCall), 0, 32)\n collected := mload(0)\n mstore(0x40, saveFreePtr)\n }\n }\n if (!success) {\n bytes32 innerRevertCode;\n assembly (\"memory-safe\") {\n let len := returndatasize()\n if eq(32,len) {\n returndatacopy(0, 0, 32)\n innerRevertCode := mload(0)\n }\n }\n if (innerRevertCode == INNER_OUT_OF_GAS) {\n // handleOps was called with gas limit too low. abort entire bundle.\n //can only be caused by bundler (leaving not enough gas for inner call)\n revert FailedOp(opIndex, \"AA95 out of gas\");\n } else if (innerRevertCode == INNER_REVERT_LOW_PREFUND) {\n // innerCall reverted on prefund too low. treat entire prefund as \"gas cost\"\n uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;\n uint256 actualGasCost = opInfo.prefund;\n emitPrefundTooLow(opInfo);\n emitUserOperationEvent(opInfo, false, actualGasCost, actualGas);\n collected = actualGasCost;\n } else {\n emit PostOpRevertReason(\n opInfo.userOpHash,\n opInfo.mUserOp.sender,\n opInfo.mUserOp.nonce,\n Exec.getReturnData(REVERT_REASON_MAX_LEN)\n );\n\n uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;\n collected = _postExecution(\n IPaymaster.PostOpMode.postOpReverted,\n opInfo,\n context,\n actualGas\n );\n }\n }\n }\n\n function emitUserOperationEvent(UserOpInfo memory opInfo, bool success, uint256 actualGasCost, uint256 actualGas) internal virtual {\n emit UserOperationEvent(\n opInfo.userOpHash,\n opInfo.mUserOp.sender,\n opInfo.mUserOp.paymaster,\n opInfo.mUserOp.nonce,\n success,\n actualGasCost,\n actualGas\n );\n }\n\n function emitPrefundTooLow(UserOpInfo memory opInfo) internal virtual {\n emit UserOperationPrefundTooLow(\n opInfo.userOpHash,\n opInfo.mUserOp.sender,\n opInfo.mUserOp.nonce\n );\n }\n\n /// @inheritdoc IEntryPoint\n function handleOps(\n PackedUserOperation[] calldata ops,\n address payable beneficiary\n ) public nonReentrant {\n uint256 opslen = ops.length;\n UserOpInfo[] memory opInfos = new UserOpInfo[](opslen);\n\n unchecked {\n for (uint256 i = 0; i < opslen; i++) {\n UserOpInfo memory opInfo = opInfos[i];\n (\n uint256 validationData,\n uint256 pmValidationData\n ) = _validatePrepayment(i, ops[i], opInfo);\n _validateAccountAndPaymasterValidationData(\n i,\n validationData,\n pmValidationData,\n address(0)\n );\n }\n\n uint256 collected = 0;\n emit BeforeExecution();\n\n for (uint256 i = 0; i < opslen; i++) {\n collected += _executeUserOp(i, ops[i], opInfos[i]);\n }\n\n _compensate(beneficiary, collected);\n }\n }\n\n /// @inheritdoc IEntryPoint\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) public nonReentrant {\n\n uint256 opasLen = opsPerAggregator.length;\n uint256 totalOps = 0;\n for (uint256 i = 0; i < opasLen; i++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[i];\n PackedUserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n //address(1) is special marker of \"signature error\"\n require(\n address(aggregator) != address(1),\n \"AA96 invalid aggregator\"\n );\n\n if (address(aggregator) != address(0)) {\n // solhint-disable-next-line no-empty-blocks\n try aggregator.validateSignatures(ops, opa.signature) {} catch {\n revert SignatureValidationFailed(address(aggregator));\n }\n }\n\n totalOps += ops.length;\n }\n\n UserOpInfo[] memory opInfos = new UserOpInfo[](totalOps);\n\n uint256 opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n PackedUserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n uint256 opslen = ops.length;\n for (uint256 i = 0; i < opslen; i++) {\n UserOpInfo memory opInfo = opInfos[opIndex];\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(opIndex, ops[i], opInfo);\n _validateAccountAndPaymasterValidationData(\n i,\n validationData,\n paymasterValidationData,\n address(aggregator)\n );\n opIndex++;\n }\n }\n\n emit BeforeExecution();\n\n uint256 collected = 0;\n opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n emit SignatureAggregatorChanged(address(opa.aggregator));\n PackedUserOperation[] calldata ops = opa.userOps;\n uint256 opslen = ops.length;\n\n for (uint256 i = 0; i < opslen; i++) {\n collected += _executeUserOp(opIndex, ops[i], opInfos[opIndex]);\n opIndex++;\n }\n }\n emit SignatureAggregatorChanged(address(0));\n\n _compensate(beneficiary, collected);\n }\n\n /**\n * A memory copy of UserOp static fields only.\n * Excluding: callData, initCode and signature. Replacing paymasterAndData with paymaster.\n */\n struct MemoryUserOp {\n address sender;\n uint256 nonce;\n uint256 verificationGasLimit;\n uint256 callGasLimit;\n uint256 paymasterVerificationGasLimit;\n uint256 paymasterPostOpGasLimit;\n uint256 preVerificationGas;\n address paymaster;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n }\n\n struct UserOpInfo {\n MemoryUserOp mUserOp;\n bytes32 userOpHash;\n uint256 prefund;\n uint256 contextOffset;\n uint256 preOpGas;\n }\n\n /**\n * Inner function to handle a UserOperation.\n * Must be declared \"external\" to open a call context, but it can only be called by handleOps.\n * @param callData - The callData to execute.\n * @param opInfo - The UserOpInfo struct.\n * @param context - The context bytes.\n * @return actualGasCost - the actual cost in eth this UserOperation paid for gas\n */\n function innerHandleOp(\n bytes memory callData,\n UserOpInfo memory opInfo,\n bytes calldata context\n ) external returns (uint256 actualGasCost) {\n uint256 preGas = gasleft();\n require(msg.sender == address(this), \"AA92 internal call only\");\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n\n uint256 callGasLimit = mUserOp.callGasLimit;\n unchecked {\n // handleOps was called with gas limit too low. abort entire bundle.\n if (\n gasleft() * 63 / 64 <\n callGasLimit +\n mUserOp.paymasterPostOpGasLimit +\n INNER_GAS_OVERHEAD\n ) {\n assembly (\"memory-safe\") {\n mstore(0, INNER_OUT_OF_GAS)\n revert(0, 32)\n }\n }\n }\n\n IPaymaster.PostOpMode mode = IPaymaster.PostOpMode.opSucceeded;\n if (callData.length > 0) {\n bool success = Exec.call(mUserOp.sender, 0, callData, callGasLimit);\n if (!success) {\n bytes memory result = Exec.getReturnData(REVERT_REASON_MAX_LEN);\n if (result.length > 0) {\n emit UserOperationRevertReason(\n opInfo.userOpHash,\n mUserOp.sender,\n mUserOp.nonce,\n result\n );\n }\n mode = IPaymaster.PostOpMode.opReverted;\n }\n }\n\n unchecked {\n uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;\n return _postExecution(mode, opInfo, context, actualGas);\n }\n }\n\n /// @inheritdoc IEntryPoint\n function getUserOpHash(\n PackedUserOperation calldata userOp\n ) public view returns (bytes32) {\n return\n keccak256(abi.encode(userOp.hash(), address(this), block.chainid));\n }\n\n /**\n * Copy general fields from userOp into the memory opInfo structure.\n * @param userOp - The user operation.\n * @param mUserOp - The memory user operation.\n */\n function _copyUserOpToMemory(\n PackedUserOperation calldata userOp,\n MemoryUserOp memory mUserOp\n ) internal pure {\n mUserOp.sender = userOp.sender;\n mUserOp.nonce = userOp.nonce;\n (mUserOp.verificationGasLimit, mUserOp.callGasLimit) = UserOperationLib.unpackUints(userOp.accountGasLimits);\n mUserOp.preVerificationGas = userOp.preVerificationGas;\n (mUserOp.maxPriorityFeePerGas, mUserOp.maxFeePerGas) = UserOperationLib.unpackUints(userOp.gasFees);\n bytes calldata paymasterAndData = userOp.paymasterAndData;\n if (paymasterAndData.length > 0) {\n require(\n paymasterAndData.length >= UserOperationLib.PAYMASTER_DATA_OFFSET,\n \"AA93 invalid paymasterAndData\"\n );\n (mUserOp.paymaster, mUserOp.paymasterVerificationGasLimit, mUserOp.paymasterPostOpGasLimit) = UserOperationLib.unpackPaymasterStaticFields(paymasterAndData);\n } else {\n mUserOp.paymaster = address(0);\n mUserOp.paymasterVerificationGasLimit = 0;\n mUserOp.paymasterPostOpGasLimit = 0;\n }\n }\n\n /**\n * Get the required prefunded gas fee amount for an operation.\n * @param mUserOp - The user operation in memory.\n */\n function _getRequiredPrefund(\n MemoryUserOp memory mUserOp\n ) internal pure returns (uint256 requiredPrefund) {\n unchecked {\n uint256 requiredGas = mUserOp.verificationGasLimit +\n mUserOp.callGasLimit +\n mUserOp.paymasterVerificationGasLimit +\n mUserOp.paymasterPostOpGasLimit +\n mUserOp.preVerificationGas;\n\n requiredPrefund = requiredGas * mUserOp.maxFeePerGas;\n }\n }\n\n /**\n * Create sender smart contract account if init code is provided.\n * @param opIndex - The operation index.\n * @param opInfo - The operation info.\n * @param initCode - The init code for the smart contract account.\n */\n function _createSenderIfNeeded(\n uint256 opIndex,\n UserOpInfo memory opInfo,\n bytes calldata initCode\n ) internal {\n if (initCode.length != 0) {\n address sender = opInfo.mUserOp.sender;\n if (sender.code.length != 0)\n revert FailedOp(opIndex, \"AA10 sender already constructed\");\n address sender1 = senderCreator().createSender{\n gas: opInfo.mUserOp.verificationGasLimit\n }(initCode);\n if (sender1 == address(0))\n revert FailedOp(opIndex, \"AA13 initCode failed or OOG\");\n if (sender1 != sender)\n revert FailedOp(opIndex, \"AA14 initCode must return sender\");\n if (sender1.code.length == 0)\n revert FailedOp(opIndex, \"AA15 initCode must create sender\");\n address factory = address(bytes20(initCode[0:20]));\n emit AccountDeployed(\n opInfo.userOpHash,\n sender,\n factory,\n opInfo.mUserOp.paymaster\n );\n }\n }\n\n /// @inheritdoc IEntryPoint\n function getSenderAddress(bytes calldata initCode) public {\n address sender = senderCreator().createSender(initCode);\n revert SenderAddressResult(sender);\n }\n\n /**\n * Call account.validateUserOp.\n * Revert (with FailedOp) in case validateUserOp reverts, or account didn't send required prefund.\n * Decrement account's deposit if needed.\n * @param opIndex - The operation index.\n * @param op - The user operation.\n * @param opInfo - The operation info.\n * @param requiredPrefund - The required prefund amount.\n */\n function _validateAccountPrepayment(\n uint256 opIndex,\n PackedUserOperation calldata op,\n UserOpInfo memory opInfo,\n uint256 requiredPrefund,\n uint256 verificationGasLimit\n )\n internal\n returns (\n uint256 validationData\n )\n {\n unchecked {\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n address sender = mUserOp.sender;\n _createSenderIfNeeded(opIndex, opInfo, op.initCode);\n address paymaster = mUserOp.paymaster;\n uint256 missingAccountFunds = 0;\n if (paymaster == address(0)) {\n uint256 bal = balanceOf(sender);\n missingAccountFunds = bal > requiredPrefund\n ? 0\n : requiredPrefund - bal;\n }\n try\n IAccount(sender).validateUserOp{\n gas: verificationGasLimit\n }(op, opInfo.userOpHash, missingAccountFunds)\n returns (uint256 _validationData) {\n validationData = _validationData;\n } catch {\n revert FailedOpWithRevert(opIndex, \"AA23 reverted\", Exec.getReturnData(REVERT_REASON_MAX_LEN));\n }\n if (paymaster == address(0)) {\n DepositInfo storage senderInfo = deposits[sender];\n uint256 deposit = senderInfo.deposit;\n if (requiredPrefund > deposit) {\n revert FailedOp(opIndex, \"AA21 didn't pay prefund\");\n }\n senderInfo.deposit = deposit - requiredPrefund;\n }\n }\n }\n\n /**\n * In case the request has a paymaster:\n * - Validate paymaster has enough deposit.\n * - Call paymaster.validatePaymasterUserOp.\n * - Revert with proper FailedOp in case paymaster reverts.\n * - Decrement paymaster's deposit.\n * @param opIndex - The operation index.\n * @param op - The user operation.\n * @param opInfo - The operation info.\n * @param requiredPreFund - The required prefund amount.\n */\n function _validatePaymasterPrepayment(\n uint256 opIndex,\n PackedUserOperation calldata op,\n UserOpInfo memory opInfo,\n uint256 requiredPreFund\n ) internal returns (bytes memory context, uint256 validationData) {\n unchecked {\n uint256 preGas = gasleft();\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n address paymaster = mUserOp.paymaster;\n DepositInfo storage paymasterInfo = deposits[paymaster];\n uint256 deposit = paymasterInfo.deposit;\n if (deposit < requiredPreFund) {\n revert FailedOp(opIndex, \"AA31 paymaster deposit too low\");\n }\n paymasterInfo.deposit = deposit - requiredPreFund;\n uint256 pmVerificationGasLimit = mUserOp.paymasterVerificationGasLimit;\n try\n IPaymaster(paymaster).validatePaymasterUserOp{gas: pmVerificationGasLimit}(\n op,\n opInfo.userOpHash,\n requiredPreFund\n )\n returns (bytes memory _context, uint256 _validationData) {\n context = _context;\n validationData = _validationData;\n } catch {\n revert FailedOpWithRevert(opIndex, \"AA33 reverted\", Exec.getReturnData(REVERT_REASON_MAX_LEN));\n }\n if (preGas - gasleft() > pmVerificationGasLimit) {\n revert FailedOp(opIndex, \"AA36 over paymasterVerificationGasLimit\");\n }\n }\n }\n\n /**\n * Revert if either account validationData or paymaster validationData is expired.\n * @param opIndex - The operation index.\n * @param validationData - The account validationData.\n * @param paymasterValidationData - The paymaster validationData.\n * @param expectedAggregator - The expected aggregator.\n */\n function _validateAccountAndPaymasterValidationData(\n uint256 opIndex,\n uint256 validationData,\n uint256 paymasterValidationData,\n address expectedAggregator\n ) internal view {\n (address aggregator, bool outOfTimeRange) = _getValidationData(\n validationData\n );\n if (expectedAggregator != aggregator) {\n revert FailedOp(opIndex, \"AA24 signature error\");\n }\n if (outOfTimeRange) {\n revert FailedOp(opIndex, \"AA22 expired or not due\");\n }\n // pmAggregator is not a real signature aggregator: we don't have logic to handle it as address.\n // Non-zero address means that the paymaster fails due to some signature check (which is ok only during estimation).\n address pmAggregator;\n (pmAggregator, outOfTimeRange) = _getValidationData(\n paymasterValidationData\n );\n if (pmAggregator != address(0)) {\n revert FailedOp(opIndex, \"AA34 signature error\");\n }\n if (outOfTimeRange) {\n revert FailedOp(opIndex, \"AA32 paymaster expired or not due\");\n }\n }\n\n /**\n * Parse validationData into its components.\n * @param validationData - The packed validation data (sigFailed, validAfter, validUntil).\n * @return aggregator the aggregator of the validationData\n * @return outOfTimeRange true if current time is outside the time range of this validationData.\n */\n function _getValidationData(\n uint256 validationData\n ) internal view returns (address aggregator, bool outOfTimeRange) {\n if (validationData == 0) {\n return (address(0), false);\n }\n ValidationData memory data = _parseValidationData(validationData);\n // solhint-disable-next-line not-rely-on-time\n outOfTimeRange = block.timestamp > data.validUntil || block.timestamp < data.validAfter;\n aggregator = data.aggregator;\n }\n\n /**\n * Validate account and paymaster (if defined) and\n * also make sure total validation doesn't exceed verificationGasLimit.\n * This method is called off-chain (simulateValidation()) and on-chain (from handleOps)\n * @param opIndex - The index of this userOp into the \"opInfos\" array.\n * @param userOp - The userOp to validate.\n */\n function _validatePrepayment(\n uint256 opIndex,\n PackedUserOperation calldata userOp,\n UserOpInfo memory outOpInfo\n )\n internal\n returns (uint256 validationData, uint256 paymasterValidationData)\n {\n uint256 preGas = gasleft();\n MemoryUserOp memory mUserOp = outOpInfo.mUserOp;\n _copyUserOpToMemory(userOp, mUserOp);\n outOpInfo.userOpHash = getUserOpHash(userOp);\n\n // Validate all numeric values in userOp are well below 128 bit, so they can safely be added\n // and multiplied without causing overflow.\n uint256 verificationGasLimit = mUserOp.verificationGasLimit;\n uint256 maxGasValues = mUserOp.preVerificationGas |\n verificationGasLimit |\n mUserOp.callGasLimit |\n mUserOp.paymasterVerificationGasLimit |\n mUserOp.paymasterPostOpGasLimit |\n mUserOp.maxFeePerGas |\n mUserOp.maxPriorityFeePerGas;\n require(maxGasValues <= type(uint120).max, \"AA94 gas values overflow\");\n\n uint256 requiredPreFund = _getRequiredPrefund(mUserOp);\n validationData = _validateAccountPrepayment(\n opIndex,\n userOp,\n outOpInfo,\n requiredPreFund,\n verificationGasLimit\n );\n\n if (!_validateAndUpdateNonce(mUserOp.sender, mUserOp.nonce)) {\n revert FailedOp(opIndex, \"AA25 invalid account nonce\");\n }\n\n unchecked {\n if (preGas - gasleft() > verificationGasLimit) {\n revert FailedOp(opIndex, \"AA26 over verificationGasLimit\");\n }\n }\n\n bytes memory context;\n if (mUserOp.paymaster != address(0)) {\n (context, paymasterValidationData) = _validatePaymasterPrepayment(\n opIndex,\n userOp,\n outOpInfo,\n requiredPreFund\n );\n }\n unchecked {\n outOpInfo.prefund = requiredPreFund;\n outOpInfo.contextOffset = getOffsetOfMemoryBytes(context);\n outOpInfo.preOpGas = preGas - gasleft() + userOp.preVerificationGas;\n }\n }\n\n /**\n * Process post-operation, called just after the callData is executed.\n * If a paymaster is defined and its validation returned a non-empty context, its postOp is called.\n * The excess amount is refunded to the account (or paymaster - if it was used in the request).\n * @param mode - Whether is called from innerHandleOp, or outside (postOpReverted).\n * @param opInfo - UserOp fields and info collected during validation.\n * @param context - The context returned in validatePaymasterUserOp.\n * @param actualGas - The gas used so far by this user operation.\n */\n function _postExecution(\n IPaymaster.PostOpMode mode,\n UserOpInfo memory opInfo,\n bytes memory context,\n uint256 actualGas\n ) private returns (uint256 actualGasCost) {\n uint256 preGas = gasleft();\n unchecked {\n address refundAddress;\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n uint256 gasPrice = getUserOpGasPrice(mUserOp);\n\n address paymaster = mUserOp.paymaster;\n if (paymaster == address(0)) {\n refundAddress = mUserOp.sender;\n } else {\n refundAddress = paymaster;\n if (context.length > 0) {\n actualGasCost = actualGas * gasPrice;\n if (mode != IPaymaster.PostOpMode.postOpReverted) {\n try IPaymaster(paymaster).postOp{\n gas: mUserOp.paymasterPostOpGasLimit\n }(mode, context, actualGasCost, gasPrice)\n // solhint-disable-next-line no-empty-blocks\n {} catch {\n bytes memory reason = Exec.getReturnData(REVERT_REASON_MAX_LEN);\n revert PostOpReverted(reason);\n }\n }\n }\n }\n actualGas += preGas - gasleft();\n\n // Calculating a penalty for unused execution gas\n {\n uint256 executionGasLimit = mUserOp.callGasLimit + mUserOp.paymasterPostOpGasLimit;\n uint256 executionGasUsed = actualGas - opInfo.preOpGas;\n // this check is required for the gas used within EntryPoint and not covered by explicit gas limits\n if (executionGasLimit > executionGasUsed) {\n uint256 unusedGas = executionGasLimit - executionGasUsed;\n uint256 unusedGasPenalty = (unusedGas * PENALTY_PERCENT) / 100;\n actualGas += unusedGasPenalty;\n }\n }\n\n actualGasCost = actualGas * gasPrice;\n uint256 prefund = opInfo.prefund;\n if (prefund < actualGasCost) {\n if (mode == IPaymaster.PostOpMode.postOpReverted) {\n actualGasCost = prefund;\n emitPrefundTooLow(opInfo);\n emitUserOperationEvent(opInfo, false, actualGasCost, actualGas);\n } else {\n assembly (\"memory-safe\") {\n mstore(0, INNER_REVERT_LOW_PREFUND)\n revert(0, 32)\n }\n }\n } else {\n uint256 refund = prefund - actualGasCost;\n _incrementDeposit(refundAddress, refund);\n bool success = mode == IPaymaster.PostOpMode.opSucceeded;\n emitUserOperationEvent(opInfo, success, actualGasCost, actualGas);\n }\n } // unchecked\n }\n\n /**\n * The gas price this UserOp agrees to pay.\n * Relayer/block builder might submit the TX with higher priorityFee, but the user should not.\n * @param mUserOp - The userOp to get the gas price from.\n */\n function getUserOpGasPrice(\n MemoryUserOp memory mUserOp\n ) internal view returns (uint256) {\n unchecked {\n uint256 maxFeePerGas = mUserOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = mUserOp.maxPriorityFeePerGas;\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n /**\n * The offset of the given bytes in memory.\n * @param data - The bytes to get the offset of.\n */\n function getOffsetOfMemoryBytes(\n bytes memory data\n ) internal pure returns (uint256 offset) {\n assembly {\n offset := data\n }\n }\n\n /**\n * The bytes in memory at the given offset.\n * @param offset - The offset to get the bytes from.\n */\n function getMemoryBytesFromOffset(\n uint256 offset\n ) internal pure returns (bytes memory data) {\n assembly (\"memory-safe\") {\n data := offset\n }\n }\n\n /// @inheritdoc IEntryPoint\n function delegateAndRevert(address target, bytes calldata data) external {\n (bool success, bytes memory ret) = target.delegatecall(data);\n revert DelegateAndRevert(success, ret);\n }\n}\n"
|
|
236
|
+
},
|
|
237
|
+
"project/contracts/core/EntryPointSimulations.sol": {
|
|
238
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n\nimport \"./EntryPoint.sol\";\nimport \"../interfaces/IEntryPointSimulations.sol\";\n\n/*\n * This contract inherits the EntryPoint and extends it with the view-only methods that are executed by\n * the bundler in order to check UserOperation validity and estimate its gas consumption.\n * This contract should never be deployed on-chain and is only used as a parameter for the \"eth_call\" request.\n */\ncontract EntryPointSimulations is EntryPoint, IEntryPointSimulations {\n // solhint-disable-next-line var-name-mixedcase\n AggregatorStakeInfo private NOT_AGGREGATED = AggregatorStakeInfo(address(0), StakeInfo(0, 0));\n\n SenderCreator private _senderCreator;\n\n function initSenderCreator() internal virtual {\n //this is the address of the first contract created with CREATE by this address.\n address createdObj = address(uint160(uint256(keccak256(abi.encodePacked(hex\"d694\", address(this), hex\"01\")))));\n _senderCreator = SenderCreator(createdObj);\n }\n\n function senderCreator() internal view virtual override returns (SenderCreator) {\n // return the same senderCreator as real EntryPoint.\n // this call is slightly (100) more expensive than EntryPoint's access to immutable member\n return _senderCreator;\n }\n\n /**\n * simulation contract should not be deployed, and specifically, accounts should not trust\n * it as entrypoint, since the simulation functions don't check the signatures\n */\n constructor() {\n require(block.number < 100, \"should not be deployed\");\n }\n\n /// @inheritdoc IEntryPointSimulations\n function simulateValidation(\n PackedUserOperation calldata userOp\n )\n external\n returns (\n ValidationResult memory\n ){\n UserOpInfo memory outOpInfo;\n\n _simulationOnlyValidations(userOp);\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(0, userOp, outOpInfo);\n StakeInfo memory paymasterInfo = _getStakeInfo(\n outOpInfo.mUserOp.paymaster\n );\n StakeInfo memory senderInfo = _getStakeInfo(outOpInfo.mUserOp.sender);\n StakeInfo memory factoryInfo;\n {\n bytes calldata initCode = userOp.initCode;\n address factory = initCode.length >= 20\n ? address(bytes20(initCode[0 : 20]))\n : address(0);\n factoryInfo = _getStakeInfo(factory);\n }\n\n address aggregator = address(uint160(validationData));\n ReturnInfo memory returnInfo = ReturnInfo(\n outOpInfo.preOpGas,\n outOpInfo.prefund,\n validationData,\n paymasterValidationData,\n getMemoryBytesFromOffset(outOpInfo.contextOffset)\n );\n\n AggregatorStakeInfo memory aggregatorInfo = NOT_AGGREGATED;\n if (uint160(aggregator) != SIG_VALIDATION_SUCCESS && uint160(aggregator) != SIG_VALIDATION_FAILED) {\n aggregatorInfo = AggregatorStakeInfo(\n aggregator,\n _getStakeInfo(aggregator)\n );\n }\n return ValidationResult(\n returnInfo,\n senderInfo,\n factoryInfo,\n paymasterInfo,\n aggregatorInfo\n );\n }\n\n /// @inheritdoc IEntryPointSimulations\n function simulateHandleOp(\n PackedUserOperation calldata op,\n address target,\n bytes calldata targetCallData\n )\n external nonReentrant\n returns (\n ExecutionResult memory\n ){\n UserOpInfo memory opInfo;\n _simulationOnlyValidations(op);\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(0, op, opInfo);\n\n uint256 paid = _executeUserOp(0, op, opInfo);\n bool targetSuccess;\n bytes memory targetResult;\n if (target != address(0)) {\n (targetSuccess, targetResult) = target.call(targetCallData);\n }\n return ExecutionResult(\n opInfo.preOpGas,\n paid,\n validationData,\n paymasterValidationData,\n targetSuccess,\n targetResult\n );\n }\n\n function _simulationOnlyValidations(\n PackedUserOperation calldata userOp\n )\n internal\n {\n //initialize senderCreator(). we can't rely on constructor\n initSenderCreator();\n\n try\n this._validateSenderAndPaymaster(\n userOp.initCode,\n userOp.sender,\n userOp.paymasterAndData\n )\n // solhint-disable-next-line no-empty-blocks\n {} catch Error(string memory revertReason) {\n if (bytes(revertReason).length != 0) {\n revert FailedOp(0, revertReason);\n }\n }\n }\n\n /**\n * Called only during simulation.\n * This function always reverts to prevent warm/cold storage differentiation in simulation vs execution.\n * @param initCode - The smart account constructor code.\n * @param sender - The sender address.\n * @param paymasterAndData - The paymaster address (followed by other params, ignored by this method)\n */\n function _validateSenderAndPaymaster(\n bytes calldata initCode,\n address sender,\n bytes calldata paymasterAndData\n ) external view {\n if (initCode.length == 0 && sender.code.length == 0) {\n // it would revert anyway. but give a meaningful message\n revert(\"AA20 account not deployed\");\n }\n if (paymasterAndData.length >= 20) {\n address paymaster = address(bytes20(paymasterAndData[0 : 20]));\n if (paymaster.code.length == 0) {\n // It would revert anyway. but give a meaningful message.\n revert(\"AA30 paymaster not deployed\");\n }\n }\n // always revert\n revert(\"\");\n }\n\n //make sure depositTo cost is more than normal EntryPoint's cost,\n // to mitigate DoS vector on the bundler\n // empiric test showed that without this wrapper, simulation depositTo costs less..\n function depositTo(address account) public override(IStakeManager, StakeManager) payable {\n unchecked{\n // silly code, to waste some gas to make sure depositTo is always little more\n // expensive than on-chain call\n uint256 x = 1;\n while (x < 5) {\n x++;\n }\n StakeManager.depositTo(account);\n }\n }\n}\n"
|
|
239
|
+
},
|
|
240
|
+
"project/contracts/core/Groth16Verifier.sol": {
|
|
241
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\n/*\n Copyright 2021 0KIMS association.\n\n This file is generated with [snarkJS](https://github.com/iden3/snarkjs).\n\n snarkJS is a free software: you can redistribute it and/or modify it\n under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n snarkJS is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n License for more details.\n\n You should have received a copy of the GNU General Public License\n along with snarkJS. If not, see <https://www.gnu.org/licenses/>.\n*/\n\npragma solidity >=0.7.0 <0.9.0;\n\ncontract Groth16Verifier {\n // Scalar field size\n uint256 constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617;\n // Base field size\n uint256 constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;\n\n // Verification Key data\n uint256 constant alphax = 20396493642238579758497721505148539042719441132402193746287399619071242634608;\n uint256 constant alphay = 7295007995347143667582973730506287210907071422113243815553656658304744729021;\n uint256 constant betax1 = 19050840322060529390183866805073705699504202620454688652212508629821014524871;\n uint256 constant betax2 = 5961258190680478424601055953709257780519819054079089291828847135260443117128;\n uint256 constant betay1 = 4609056975648107915902198160028539506036014756924256482196484152258613635603;\n uint256 constant betay2 = 5700732091224152835152445003693667282388980380965901636624656897581878384165;\n uint256 constant gammax1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634;\n uint256 constant gammax2 = 10857046999023057135944570762232829481370756359578518086990519993285655852781;\n uint256 constant gammay1 = 4082367875863433681332203403145435568316851327593401208105741076214120093531;\n uint256 constant gammay2 = 8495653923123431417604973247489272438418190587263600148770280649306958101930;\n uint256 constant deltax1 = 3441840347218546202379600957899493945205218492567533192994966892153155542674;\n uint256 constant deltax2 = 21768888160338532749815176053809831482220943831691268841017458780703024467326;\n uint256 constant deltay1 = 4584282635419766590930555611103237780056888237088764659948909011306147809530;\n uint256 constant deltay2 = 14916362441930274739352093178730575131091795411763836722235924250670166558303;\n\n \n uint256 constant IC0x = 7689405769227637795618004838082824577203124428929101729615511227333216858067;\n uint256 constant IC0y = 8665887760829951128026598650187385727542887331726588340384472427438751257384;\n \n uint256 constant IC1x = 6913147170368466411234620920571126202642368409004464125020030251966943946236;\n uint256 constant IC1y = 2382454749574689101220120303082215470013158451245489481875467746651649536102;\n \n uint256 constant IC2x = 20926734531244703068204303459669058608234214660577238782124505893010077149385;\n uint256 constant IC2y = 12300294966247142135163464257755206321873876200694574614417391554262883622847;\n \n uint256 constant IC3x = 19851353316477660697514063614441950614086555306037127226001918435993753794396;\n uint256 constant IC3y = 8867498007347692347081626533418821699083539224188615857513493502272113957684;\n \n uint256 constant IC4x = 8455008333181567938588803681417463896377959743957043440913486429392251894606;\n uint256 constant IC4y = 5416087942707647048417938497433032650836864229951444545443736637108771038058;\n \n uint256 constant IC5x = 20320669127643659843685554706224611176669830701900669063326762686569841881407;\n uint256 constant IC5y = 10803277031432333542135637650675530025687500741898118642451472931911417336485;\n \n uint256 constant IC6x = 7031414605874222535255840482245289977632656720549831858355295120329120820081;\n uint256 constant IC6y = 13193976585886217430045798246905541177752204526563399335176734309189690451376;\n \n \n // Memory data\n uint16 constant pVk = 0;\n uint16 constant pPairing = 128;\n\n uint16 constant pLastMem = 896;\n\n function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[6] calldata _pubSignals) public view returns (bool) {\n assembly {\n function checkField(v) {\n if iszero(lt(v, r)) {\n mstore(0, 0)\n return(0, 0x20)\n }\n }\n \n // G1 function to multiply a G1 value(x,y) to value in an address\n function g1_mulAccC(pR, x, y, s) {\n let success\n let mIn := mload(0x40)\n mstore(mIn, x)\n mstore(add(mIn, 32), y)\n mstore(add(mIn, 64), s)\n\n success := staticcall(sub(gas(), 2000), 7, mIn, 96, mIn, 64)\n\n if iszero(success) {\n mstore(0, 0)\n return(0, 0x20)\n }\n\n mstore(add(mIn, 64), mload(pR))\n mstore(add(mIn, 96), mload(add(pR, 32)))\n\n success := staticcall(sub(gas(), 2000), 6, mIn, 128, pR, 64)\n\n if iszero(success) {\n mstore(0, 0)\n return(0, 0x20)\n }\n }\n\n function checkPairing(pA, pB, pC, pubSignals, pMem) -> isOk {\n let _pPairing := add(pMem, pPairing)\n let _pVk := add(pMem, pVk)\n\n mstore(_pVk, IC0x)\n mstore(add(_pVk, 32), IC0y)\n\n // Compute the linear combination vk_x\n \n g1_mulAccC(_pVk, IC1x, IC1y, calldataload(add(pubSignals, 0)))\n \n g1_mulAccC(_pVk, IC2x, IC2y, calldataload(add(pubSignals, 32)))\n \n g1_mulAccC(_pVk, IC3x, IC3y, calldataload(add(pubSignals, 64)))\n \n g1_mulAccC(_pVk, IC4x, IC4y, calldataload(add(pubSignals, 96)))\n \n g1_mulAccC(_pVk, IC5x, IC5y, calldataload(add(pubSignals, 128)))\n \n g1_mulAccC(_pVk, IC6x, IC6y, calldataload(add(pubSignals, 160)))\n \n\n // -A\n mstore(_pPairing, calldataload(pA))\n mstore(add(_pPairing, 32), mod(sub(q, calldataload(add(pA, 32))), q))\n\n // B\n mstore(add(_pPairing, 64), calldataload(pB))\n mstore(add(_pPairing, 96), calldataload(add(pB, 32)))\n mstore(add(_pPairing, 128), calldataload(add(pB, 64)))\n mstore(add(_pPairing, 160), calldataload(add(pB, 96)))\n\n // alpha1\n mstore(add(_pPairing, 192), alphax)\n mstore(add(_pPairing, 224), alphay)\n\n // beta2\n mstore(add(_pPairing, 256), betax1)\n mstore(add(_pPairing, 288), betax2)\n mstore(add(_pPairing, 320), betay1)\n mstore(add(_pPairing, 352), betay2)\n\n // vk_x\n mstore(add(_pPairing, 384), mload(add(pMem, pVk)))\n mstore(add(_pPairing, 416), mload(add(pMem, add(pVk, 32))))\n\n\n // gamma2\n mstore(add(_pPairing, 448), gammax1)\n mstore(add(_pPairing, 480), gammax2)\n mstore(add(_pPairing, 512), gammay1)\n mstore(add(_pPairing, 544), gammay2)\n\n // C\n mstore(add(_pPairing, 576), calldataload(pC))\n mstore(add(_pPairing, 608), calldataload(add(pC, 32)))\n\n // delta2\n mstore(add(_pPairing, 640), deltax1)\n mstore(add(_pPairing, 672), deltax2)\n mstore(add(_pPairing, 704), deltay1)\n mstore(add(_pPairing, 736), deltay2)\n\n\n let success := staticcall(sub(gas(), 2000), 8, _pPairing, 768, _pPairing, 0x20)\n\n isOk := and(success, mload(_pPairing))\n }\n\n let pMem := mload(0x40)\n mstore(0x40, add(pMem, pLastMem))\n\n // Validate that all evaluations ∈ F\n \n checkField(calldataload(add(_pubSignals, 0)))\n \n checkField(calldataload(add(_pubSignals, 32)))\n \n checkField(calldataload(add(_pubSignals, 64)))\n \n checkField(calldataload(add(_pubSignals, 96)))\n \n checkField(calldataload(add(_pubSignals, 128)))\n \n checkField(calldataload(add(_pubSignals, 160)))\n \n\n // Validate all evaluations\n let isValid := checkPairing(_pA, _pB, _pC, _pubSignals, pMem)\n\n mstore(0, isValid)\n return(0, 0x20)\n }\n }\n }\n"
|
|
242
|
+
},
|
|
243
|
+
"project/contracts/core/Helpers.sol": {
|
|
244
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable no-inline-assembly */\n\n\n /*\n * For simulation purposes, validateUserOp (and validatePaymasterUserOp)\n * must return this value in case of signature failure, instead of revert.\n */\nuint256 constant SIG_VALIDATION_FAILED = 1;\n\n\n/*\n * For simulation purposes, validateUserOp (and validatePaymasterUserOp)\n * return this value on success.\n */\nuint256 constant SIG_VALIDATION_SUCCESS = 0;\n\n\n/**\n * Returned data from validateUserOp.\n * validateUserOp returns a uint256, which is created by `_packedValidationData` and\n * parsed by `_parseValidationData`.\n * @param aggregator - address(0) - The account validated the signature by itself.\n * address(1) - The account failed to validate the signature.\n * otherwise - This is an address of a signature aggregator that must\n * be used to validate the signature.\n * @param validAfter - This UserOp is valid only after this timestamp.\n * @param validaUntil - This UserOp is valid only up to this timestamp.\n */\nstruct ValidationData {\n address aggregator;\n uint48 validAfter;\n uint48 validUntil;\n}\n\n/**\n * Extract sigFailed, validAfter, validUntil.\n * Also convert zero validUntil to type(uint48).max.\n * @param validationData - The packed validation data.\n */\nfunction _parseValidationData(\n uint256 validationData\n) pure returns (ValidationData memory data) {\n address aggregator = address(uint160(validationData));\n uint48 validUntil = uint48(validationData >> 160);\n if (validUntil == 0) {\n validUntil = type(uint48).max;\n }\n uint48 validAfter = uint48(validationData >> (48 + 160));\n return ValidationData(aggregator, validAfter, validUntil);\n}\n\n/**\n * Helper to pack the return value for validateUserOp.\n * @param data - The ValidationData to pack.\n */\nfunction _packValidationData(\n ValidationData memory data\n) pure returns (uint256) {\n return\n uint160(data.aggregator) |\n (uint256(data.validUntil) << 160) |\n (uint256(data.validAfter) << (160 + 48));\n}\n\n/**\n * Helper to pack the return value for validateUserOp, when not using an aggregator.\n * @param sigFailed - True for signature failure, false for success.\n * @param validUntil - Last timestamp this UserOperation is valid (or zero for infinite).\n * @param validAfter - First timestamp this UserOperation is valid.\n */\nfunction _packValidationData(\n bool sigFailed,\n uint48 validUntil,\n uint48 validAfter\n) pure returns (uint256) {\n return\n (sigFailed ? 1 : 0) |\n (uint256(validUntil) << 160) |\n (uint256(validAfter) << (160 + 48));\n}\n\n/**\n * keccak function over calldata.\n * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.\n */\n function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {\n assembly (\"memory-safe\") {\n let mem := mload(0x40)\n let len := data.length\n calldatacopy(mem, data.offset, len)\n ret := keccak256(mem, len)\n }\n }\n\n\n/**\n * The minimum of two numbers.\n * @param a - First number.\n * @param b - Second number.\n */\n function min(uint256 a, uint256 b) pure returns (uint256) {\n return a < b ? a : b;\n }\n"
|
|
245
|
+
},
|
|
246
|
+
"project/contracts/core/LinealDeployer.sol": {
|
|
247
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\ncontract LinealDeployer {\r\n\r\n event Deployed(address addr);\r\n\r\n function deploy(\r\n bytes memory bytecode,\r\n bytes32 salt\r\n ) external returns (address addr) {\r\n\r\n assembly {\r\n addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\r\n if iszero(extcodesize(addr)) {\r\n revert(0, 0)\r\n }\r\n }\r\n emit Deployed(addr);\r\n }\r\n}"
|
|
248
|
+
},
|
|
249
|
+
"project/contracts/core/NonceManager.sol": {
|
|
250
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\nimport \"../interfaces/INonceManager.sol\";\n\n/**\n * nonce management functionality\n */\nabstract contract NonceManager is INonceManager {\n\n /**\n * The next valid sequence number for a given nonce key.\n */\n mapping(address => mapping(uint192 => uint256)) public nonceSequenceNumber;\n\n /// @inheritdoc INonceManager\n function getNonce(address sender, uint192 key)\n public view override returns (uint256 nonce) {\n return nonceSequenceNumber[sender][key] | (uint256(key) << 64);\n }\n\n // allow an account to manually increment its own nonce.\n // (mainly so that during construction nonce can be made non-zero,\n // to \"absorb\" the gas cost of first nonce increment to 1st transaction (construction),\n // not to 2nd transaction)\n function incrementNonce(uint192 key) public override {\n nonceSequenceNumber[msg.sender][key]++;\n }\n\n /**\n * validate nonce uniqueness for this account.\n * called just after validateUserOp()\n * @return true if the nonce was incremented successfully.\n * false if the current nonce doesn't match the given one.\n */\n function _validateAndUpdateNonce(address sender, uint256 nonce) internal returns (bool) {\n\n uint192 key = uint192(nonce >> 64);\n uint64 seq = uint64(nonce);\n return nonceSequenceNumber[sender][key]++ == seq;\n }\n\n}\n"
|
|
251
|
+
},
|
|
252
|
+
"project/contracts/core/SenderCreator.sol": {
|
|
253
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/**\n * Helper contract for EntryPoint, to call userOp.initCode from a \"neutral\" address,\n * which is explicitly not the entryPoint itself.\n */\ncontract SenderCreator {\n /**\n * Call the \"initCode\" factory to create and return the sender account address.\n * @param initCode - The initCode value from a UserOp. contains 20 bytes of factory address,\n * followed by calldata.\n * @return sender - The returned address of the created account, or zero address on failure.\n */\n function createSender(\n bytes calldata initCode\n ) external returns (address sender) {\n address factory = address(bytes20(initCode[0:20]));\n bytes memory initCallData = initCode[20:];\n bool success;\n /* solhint-disable no-inline-assembly */\n assembly (\"memory-safe\") {\n success := call(\n gas(),\n factory,\n 0,\n add(initCallData, 0x20),\n mload(initCallData),\n 0,\n 32\n )\n sender := mload(0)\n }\n if (!success) {\n sender = address(0);\n }\n }\n}\n"
|
|
254
|
+
},
|
|
255
|
+
"project/contracts/core/StakeManager.sol": {
|
|
256
|
+
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.23;\n\nimport \"../interfaces/IStakeManager.sol\";\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable not-rely-on-time */\n\n/**\n * Manage deposits and stakes.\n * Deposit is just a balance used to pay for UserOperations (either by a paymaster or an account).\n * Stake is value locked for at least \"unstakeDelay\" by a paymaster.\n */\nabstract contract StakeManager is IStakeManager {\n /// maps paymaster to their deposits and stakes\n mapping(address => DepositInfo) public deposits;\n\n /// @inheritdoc IStakeManager\n function getDepositInfo(\n address account\n ) public view returns (DepositInfo memory info) {\n return deposits[account];\n }\n\n /**\n * Internal method to return just the stake info.\n * @param addr - The account to query.\n */\n function _getStakeInfo(\n address addr\n ) internal view returns (StakeInfo memory info) {\n DepositInfo storage depositInfo = deposits[addr];\n info.stake = depositInfo.stake;\n info.unstakeDelaySec = depositInfo.unstakeDelaySec;\n }\n\n /// @inheritdoc IStakeManager\n function balanceOf(address account) public view returns (uint256) {\n return deposits[account].deposit;\n }\n\n receive() external payable {\n depositTo(msg.sender);\n }\n\n /**\n * Increments an account's deposit.\n * @param account - The account to increment.\n * @param amount - The amount to increment by.\n * @return the updated deposit of this account\n */\n function _incrementDeposit(address account, uint256 amount) internal returns (uint256) {\n DepositInfo storage info = deposits[account];\n uint256 newAmount = info.deposit + amount;\n info.deposit = newAmount;\n return newAmount;\n }\n\n /**\n * Add to the deposit of the given account.\n * @param account - The account to add to.\n */\n function depositTo(address account) public virtual payable {\n uint256 newDeposit = _incrementDeposit(account, msg.value);\n emit Deposited(account, newDeposit);\n }\n\n /**\n * Add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param unstakeDelaySec The new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 unstakeDelaySec) public payable {\n DepositInfo storage info = deposits[msg.sender];\n require(unstakeDelaySec > 0, \"must specify unstake delay\");\n require(\n unstakeDelaySec >= info.unstakeDelaySec,\n \"cannot decrease unstake time\"\n );\n uint256 stake = info.stake + msg.value;\n require(stake > 0, \"no stake specified\");\n require(stake <= type(uint112).max, \"stake overflow\");\n deposits[msg.sender] = DepositInfo(\n info.deposit,\n true,\n uint112(stake),\n unstakeDelaySec,\n 0\n );\n emit StakeLocked(msg.sender, stake, unstakeDelaySec);\n }\n\n /**\n * Attempt to unlock the stake.\n * The value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external {\n DepositInfo storage info = deposits[msg.sender];\n require(info.unstakeDelaySec != 0, \"not staked\");\n require(info.staked, \"already unstaking\");\n uint48 withdrawTime = uint48(block.timestamp) + info.unstakeDelaySec;\n info.withdrawTime = withdrawTime;\n info.staked = false;\n emit StakeUnlocked(msg.sender, withdrawTime);\n }\n\n /**\n * Withdraw from the (unlocked) stake.\n * Must first call unlockStake and wait for the unstakeDelay to pass.\n * @param withdrawAddress - The address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external {\n DepositInfo storage info = deposits[msg.sender];\n uint256 stake = info.stake;\n require(stake > 0, \"No stake to withdraw\");\n require(info.withdrawTime > 0, \"must call unlockStake() first\");\n require(\n info.withdrawTime <= block.timestamp,\n \"Stake withdrawal is not due\"\n );\n info.unstakeDelaySec = 0;\n info.withdrawTime = 0;\n info.stake = 0;\n emit StakeWithdrawn(msg.sender, withdrawAddress, stake);\n (bool success,) = withdrawAddress.call{value: stake}(\"\");\n require(success, \"failed to withdraw stake\");\n }\n\n /**\n * Withdraw from the deposit.\n * @param withdrawAddress - The address to send withdrawn value.\n * @param withdrawAmount - The amount to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 withdrawAmount\n ) external {\n DepositInfo storage info = deposits[msg.sender];\n require(withdrawAmount <= info.deposit, \"Withdraw amount too large\");\n info.deposit = info.deposit - withdrawAmount;\n emit Withdrawn(msg.sender, withdrawAddress, withdrawAmount);\n (bool success,) = withdrawAddress.call{value: withdrawAmount}(\"\");\n require(success, \"failed to withdraw\");\n }\n}\n"
|
|
257
|
+
},
|
|
258
|
+
"project/contracts/core/UserOperationLib.sol": {
|
|
259
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable no-inline-assembly */\n\nimport \"../interfaces/PackedUserOperation.sol\";\nimport {calldataKeccak, min} from \"./Helpers.sol\";\n\n/**\n * Utility functions helpful when working with UserOperation structs.\n */\nlibrary UserOperationLib {\n\n uint256 public constant PAYMASTER_VALIDATION_GAS_OFFSET = 20;\n uint256 public constant PAYMASTER_POSTOP_GAS_OFFSET = 36;\n uint256 public constant PAYMASTER_DATA_OFFSET = 52;\n /**\n * Get sender from user operation data.\n * @param userOp - The user operation data.\n */\n function getSender(\n PackedUserOperation calldata userOp\n ) internal pure returns (address) {\n address data;\n //read sender from userOp, which is first userOp member (saves 800 gas...)\n assembly {\n data := calldataload(userOp)\n }\n return address(uint160(data));\n }\n\n /**\n * Relayer/block builder might submit the TX with higher priorityFee,\n * but the user should not pay above what he signed for.\n * @param userOp - The user operation data.\n */\n function gasPrice(\n PackedUserOperation calldata userOp\n ) internal view returns (uint256) {\n unchecked {\n (uint256 maxPriorityFeePerGas, uint256 maxFeePerGas) = unpackUints(userOp.gasFees);\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n /**\n * Pack the user operation data into bytes for hashing.\n * @param userOp - The user operation data.\n */\n function encode(\n PackedUserOperation calldata userOp\n ) internal pure returns (bytes memory ret) {\n address sender = getSender(userOp);\n uint256 nonce = userOp.nonce;\n bytes32 hashInitCode = calldataKeccak(userOp.initCode);\n bytes32 hashCallData = calldataKeccak(userOp.callData);\n bytes32 accountGasLimits = userOp.accountGasLimits;\n uint256 preVerificationGas = userOp.preVerificationGas;\n bytes32 gasFees = userOp.gasFees;\n bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);\n\n return abi.encode(\n sender, nonce,\n hashInitCode, hashCallData,\n accountGasLimits, preVerificationGas, gasFees,\n hashPaymasterAndData\n );\n }\n\n function unpackUints(\n bytes32 packed\n ) internal pure returns (uint256 high128, uint256 low128) {\n return (uint128(bytes16(packed)), uint128(uint256(packed)));\n }\n\n //unpack just the high 128-bits from a packed value\n function unpackHigh128(bytes32 packed) internal pure returns (uint256) {\n return uint256(packed) >> 128;\n }\n\n // unpack just the low 128-bits from a packed value\n function unpackLow128(bytes32 packed) internal pure returns (uint256) {\n return uint128(uint256(packed));\n }\n\n function unpackMaxPriorityFeePerGas(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return unpackHigh128(userOp.gasFees);\n }\n\n function unpackMaxFeePerGas(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return unpackLow128(userOp.gasFees);\n }\n\n function unpackVerificationGasLimit(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return unpackHigh128(userOp.accountGasLimits);\n }\n\n function unpackCallGasLimit(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return unpackLow128(userOp.accountGasLimits);\n }\n\n function unpackPaymasterVerificationGasLimit(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return uint128(bytes16(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_POSTOP_GAS_OFFSET]));\n }\n\n function unpackPostOpGasLimit(PackedUserOperation calldata userOp)\n internal pure returns (uint256) {\n return uint128(bytes16(userOp.paymasterAndData[PAYMASTER_POSTOP_GAS_OFFSET : PAYMASTER_DATA_OFFSET]));\n }\n\n function unpackPaymasterStaticFields(\n bytes calldata paymasterAndData\n ) internal pure returns (address paymaster, uint256 validationGasLimit, uint256 postOpGasLimit) {\n return (\n address(bytes20(paymasterAndData[: PAYMASTER_VALIDATION_GAS_OFFSET])),\n uint128(bytes16(paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_POSTOP_GAS_OFFSET])),\n uint128(bytes16(paymasterAndData[PAYMASTER_POSTOP_GAS_OFFSET : PAYMASTER_DATA_OFFSET]))\n );\n }\n\n /**\n * Hash the user operation data.\n * @param userOp - The user operation data.\n */\n function hash(\n PackedUserOperation calldata userOp\n ) internal pure returns (bytes32) {\n return keccak256(encode(userOp));\n }\n}\n"
|
|
260
|
+
},
|
|
261
|
+
"project/contracts/Counter.sol": {
|
|
262
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.28;\r\n\r\ncontract Counter {\r\n uint public x;\r\n\r\n event Increment(uint by);\r\n\r\n function inc() public {\r\n x++;\r\n emit Increment(1);\r\n }\r\n\r\n function incBy(uint by) public {\r\n require(by > 0, \"incBy: increment should be positive\");\r\n x += by;\r\n emit Increment(by);\r\n }\r\n}\r\n"
|
|
263
|
+
},
|
|
264
|
+
"project/contracts/economy/accounts/callback/TokenCallbackHandler.sol": {
|
|
265
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable no-empty-blocks */\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\n\n/**\n * Token callback handler.\n * Handles supported tokens' callbacks, allowing account receiving these tokens.\n */\nabstract contract TokenCallbackHandler is IERC721Receiver, IERC1155Receiver {\n\n function onERC721Received(\n address,\n address,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC721Receiver.onERC721Received.selector;\n }\n\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155Receiver.onERC1155Received.selector;\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata,\n uint256[] calldata,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155Receiver.onERC1155BatchReceived.selector;\n }\n\n function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {\n return\n interfaceId == type(IERC721Receiver).interfaceId ||\n interfaceId == type(IERC1155Receiver).interfaceId ||\n interfaceId == type(IERC165).interfaceId;\n }\n}\n"
|
|
266
|
+
},
|
|
267
|
+
"project/contracts/economy/accounts/LinealAccount.sol": {
|
|
268
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol\";\nimport \"../../core/BaseAccount.sol\";\nimport \"../../core/Helpers.sol\";\nimport \"./callback/TokenCallbackHandler.sol\";\n\n/**\n * minimal account.\n * this is sample minimal account.\n * has execute, eth handling methods\n * has a single signer that can send requests through the entryPoint.\n */\ncontract LinealAccount is BaseAccount, TokenCallbackHandler, UUPSUpgradeable, Initializable {\n address public owner;\n\n IEntryPoint private immutable _entryPoint;\n\n event SimpleAccountInitialized(IEntryPoint indexed entryPoint, address indexed owner);\n\n modifier onlyOwner() {\n _onlyOwner();\n _;\n }\n\n /// @inheritdoc BaseAccount\n function entryPoint() public view virtual override returns (IEntryPoint) {\n return _entryPoint;\n }\n\n // solhint-disable-next-line no-empty-blocks\n receive() external payable {}\n\n constructor(IEntryPoint anEntryPoint) {\n _entryPoint = anEntryPoint;\n _disableInitializers();\n }\n\n function _onlyOwner() internal view {\n //directly from EOA owner, or through the account itself (which gets redirected through execute())\n require(msg.sender == owner || msg.sender == address(this), \"only owner\");\n }\n\n /**\n * execute a transaction (called directly from owner, or by entryPoint)\n * @param dest destination address to call\n * @param value the value to pass in this call\n * @param func the calldata to pass in this call\n */\n function execute(address dest, uint256 value, bytes calldata func) external {\n _requireFromEntryPointOrOwner();\n _call(dest, value, func);\n }\n\n /**\n * execute a sequence of transactions\n * @dev to reduce gas consumption for trivial case (no value), use a zero-length array to mean zero value\n * @param dest an array of destination addresses\n * @param value an array of values to pass to each call. can be zero-length for no-value calls\n * @param func an array of calldata to pass to each call\n */\n function executeBatch(address[] calldata dest, uint256[] calldata value, bytes[] calldata func) external {\n _requireFromEntryPointOrOwner();\n require(dest.length == func.length && (value.length == 0 || value.length == func.length), \"wrong array lengths\");\n if (value.length == 0) {\n for (uint256 i = 0; i < dest.length; i++) {\n _call(dest[i], 0, func[i]);\n }\n } else {\n for (uint256 i = 0; i < dest.length; i++) {\n _call(dest[i], value[i], func[i]);\n }\n }\n }\n\n /**\n * @dev The _entryPoint member is immutable, to reduce gas consumption. To upgrade EntryPoint,\n * a new implementation of SimpleAccount must be deployed with the new EntryPoint address, then upgrading\n * the implementation by calling `upgradeTo()`\n * @param anOwner the owner (signer) of this account\n */\n function initialize(address anOwner) public virtual initializer {\n _initialize(anOwner);\n }\n\n function _initialize(address anOwner) internal virtual {\n owner = anOwner;\n emit SimpleAccountInitialized(_entryPoint, owner);\n }\n\n // Require the function call went through EntryPoint or owner\n function _requireFromEntryPointOrOwner() internal view {\n require(msg.sender == address(entryPoint()) || msg.sender == owner, \"account: not Owner or EntryPoint\");\n }\n\n /// implement template method of BaseAccount\n function _validateSignature(PackedUserOperation calldata userOp, bytes32 userOpHash)\n internal override virtual returns (uint256 validationData) {\n bytes32 hash = MessageHashUtils.toEthSignedMessageHash(userOpHash);\n if (owner != ECDSA.recover(hash, userOp.signature))\n return SIG_VALIDATION_FAILED;\n return SIG_VALIDATION_SUCCESS;\n }\n\n function _call(address target, uint256 value, bytes memory data) internal {\n (bool success, bytes memory result) = target.call{value: value}(data);\n if (!success) {\n assembly {\n revert(add(result, 32), mload(result))\n }\n }\n }\n\n /**\n * check current account deposit in the entryPoint\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint().balanceOf(address(this));\n }\n\n /**\n * deposit more funds for this account in the entryPoint\n */\n function addDeposit() public payable {\n entryPoint().depositTo{value: msg.value}(address(this));\n }\n\n /**\n * withdraw value from the account's deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(address payable withdrawAddress, uint256 amount) public onlyOwner {\n entryPoint().withdrawTo(withdrawAddress, amount);\n }\n\n function _authorizeUpgrade(address newImplementation) internal view override {\n (newImplementation);\n _onlyOwner();\n }\n}\n\n"
|
|
269
|
+
},
|
|
270
|
+
"project/contracts/economy/accounts/LinealAccountFactory.sol": {
|
|
271
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\nimport \"@openzeppelin/contracts/utils/Create2.sol\";\nimport \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\";\n\nimport \"./LinealAccount.sol\";\n\n/**\n * A sample factory contract for LinealAccount\n * A UserOperations \"initCode\" holds the address of the factory, and a method call (to createAccount, in this sample factory).\n * The factory's createAccount returns the target account address even if it is already installed.\n * This way, the entryPoint.getSenderAddress() can be called either before or after the account is created.\n */\ncontract LinealAccountFactory {\n LinealAccount public immutable accountImplementation;\n\n constructor(IEntryPoint _entryPoint) {\n accountImplementation = new LinealAccount(_entryPoint);\n }\n\n /**\n * create an account, and return its address.\n * returns the address even if the account is already deployed.\n * Note that during UserOperation execution, this method is called only if the account is not deployed.\n * This method returns an existing account address so that entryPoint.getSenderAddress() would work even after account creation\n */\n function createAccount(address owner,uint256 salt) public returns (LinealAccount ret) {\n address addr = getAddress(owner, salt);\n uint256 codeSize = addr.code.length;\n if (codeSize > 0) {\n return LinealAccount(payable(addr));\n }\n ret = LinealAccount(payable(new ERC1967Proxy{salt : bytes32(salt)}(\n address(accountImplementation),\n abi.encodeCall(LinealAccount.initialize, (owner))\n )));\n }\n\n /**\n * calculate the counterfactual address of this account as it would be returned by createAccount()\n */\n function getAddress(address owner,uint256 salt) public view returns (address) {\n return Create2.computeAddress(bytes32(salt), keccak256(abi.encodePacked(\n type(ERC1967Proxy).creationCode,\n abi.encode(\n address(accountImplementation),\n abi.encodeCall(LinealAccount.initialize, (owner))\n )\n )));\n }\n}\n"
|
|
272
|
+
},
|
|
273
|
+
"project/contracts/economy/banks/LinealBank.sol": {
|
|
274
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\r\nimport \"../token/LinealToken.sol\";\r\n\r\n/**\r\n * @title LinealBank\r\n * @author NeoQuor - Lineal Qorum Protocol\r\n * @notice Custodia de VARIOS tokens ERC20 por subcuentas para una Institución.\r\n * Cada subcuenta lleva un saldo independiente por token.\r\n * Cada transferencia interna paga un fee (en bps) que se acredita a la subcuenta de rewards,\r\n * en el mismo token que se transfiere.\r\n * Las cuentas personales de ciudadanos solo pueden ser movidas por su dueño.\r\n *\r\n * @dev Solo se aceptan DEPÓSITOS de tokens habilitados por la Institución (lista blanca).\r\n * Deshabilitar un token bloquea depósitos nuevos, pero NO bloquea retiros ni transferencias:\r\n * los saldos existentes siempre se pueden mover. Evita habilitar tokens con rebase,\r\n * con callbacks (ERC777) o que puedan pausar/bloquear transferencias a voluntad.\r\n */\r\ncontract LinealBank is Ownable, ReentrancyGuard {\r\n using SafeERC20 for IERC20;\r\n\r\n uint256 public constant BPS_DENOMINATOR = 10000;\r\n\r\n // Institución dueña de este banco\r\n address public immutable institutionAddress;\r\n\r\n // Porcentaje de fee sobre cada transferencia interna (basis points, base 10000)\r\n uint256 public immutable rewardsBps;\r\n\r\n // Subcuenta que recibe el fee de rewards\r\n bytes32 public rewardsAccountId;\r\n\r\n // accountId => token => balance en unidades del token\r\n mapping(bytes32 => mapping(address => uint256)) public accountBalances;\r\n\r\n // Tokens habilitados para depósito\r\n mapping(address => bool) public supportedToken;\r\n mapping(address => bool) private _listed;\r\n address[] private _tokenList;\r\n\r\n mapping(bytes32 => bool) public activeSubAccounts;\r\n bytes32[] public subAccountIds;\r\n\r\n // accountId => true si es la cuenta personal de un ciudadano (la directiva no puede moverla)\r\n mapping(bytes32 => bool) public personalAccount;\r\n\r\n address public transactionManager;\r\n\r\n event TokenSupportChanged(address indexed token, bool supported);\r\n event TokenDeposited(bytes32 indexed accountId, address indexed depositor, address indexed token, uint256 amount);\r\n event RewardsFeeCharged(bytes32 indexed fromAccount, bytes32 indexed rewardsAccount, address indexed token, uint256 fee);\r\n event RewardsAccountSet(bytes32 indexed accountId);\r\n event TokenReleased(bytes32 indexed accountId, address caller, address indexed to, address indexed token, uint256 amount, bytes32 reason);\r\n event InternalTransfer(bytes32 indexed fromAccount, bytes32 indexed toAccount, address indexed token, uint256 amount);\r\n event SubAccountCreated(bytes32 indexed accountId, string accountName);\r\n event PersonalAccountCreated(bytes32 indexed accountId);\r\n event TransactionManagerSet(address indexed manager);\r\n event CitizenTransfer(\r\n address indexed citizen,\r\n bytes32 indexed fromAccount,\r\n bytes32 indexed toAccount,\r\n address token,\r\n uint256 amount\r\n );\r\n event BankTransfer(\r\n bytes32 indexed fromAccount,\r\n address indexed destBank,\r\n bytes32 indexed toAccount,\r\n address token,\r\n uint256 amount,\r\n uint256 fee\r\n );\r\n\r\n error InvalidSubAccount();\r\n error Bank_Unauthorized();\r\n error Bank_InvalidAccount();\r\n error Bank_InvalidAddress();\r\n error Bank_InvalidToken();\r\n error Bank_InvalidBps();\r\n error Bank_ZeroAmount();\r\n error Bank_InsufficientBalance();\r\n error Bank_TransactionNotExecuted();\r\n error Bank_IdentityNotLinked();\r\n error Bank_NoAccount();\r\n error Bank_PersonalAccount();\r\n error Bank_TokenNotSupported();\r\n\r\n /**\r\n * @param _institutionAddress Dueño del banco.\r\n * @param _rewardsBps Fee de rewards por transferencia interna (ej. 100 = 1%).\r\n */\r\n constructor(\r\n address _institutionAddress,\r\n uint256 _rewardsBps\r\n ) Ownable(_institutionAddress) {\r\n if (_institutionAddress == address(0)) revert Bank_InvalidAddress();\r\n if (_rewardsBps > BPS_DENOMINATOR) revert Bank_InvalidBps();\r\n\r\n institutionAddress = _institutionAddress;\r\n rewardsBps = _rewardsBps;\r\n\r\n // Subcuenta de rewards creada junto con el banco\r\n bytes32 id = _createSubAccount(\"Rewards\");\r\n rewardsAccountId = id;\r\n emit RewardsAccountSet(id);\r\n }\r\n\r\n // ───────────── Tokens soportados ─────────────\r\n\r\n /// @notice Habilita o deshabilita depósitos de un token. Los saldos existentes no se afectan.\r\n function setTokenSupport(address tokenAddr, bool supported) external onlyOwner {\r\n _setTokenSupport(tokenAddr, supported);\r\n }\r\n\r\n function _setTokenSupport(address tokenAddr, bool supported) internal {\r\n if (tokenAddr == address(0)) revert Bank_InvalidToken();\r\n supportedToken[tokenAddr] = supported;\r\n if (!_listed[tokenAddr]) {\r\n _listed[tokenAddr] = true;\r\n _tokenList.push(tokenAddr);\r\n }\r\n emit TokenSupportChanged(tokenAddr, supported);\r\n }\r\n\r\n /// @notice Para otros bancos: indica si este banco acepta depósitos de ese token.\r\n function isTokenSupported(address tokenAddr) external view returns (bool) {\r\n return supportedToken[tokenAddr];\r\n }\r\n\r\n // ───────────── Creación de cuentas ─────────────\r\n\r\n /// @notice Crea una subcuenta de la institución (movible por el quórum).\r\n function createSubAccount(string calldata accountName) external onlyOwner returns (bytes32 accountId) {\r\n return _createSubAccount(accountName);\r\n }\r\n\r\n /// @notice Crea la cuenta personal de un ciudadano (solo su dueño puede moverla).\r\n function createCitizenAccount(string calldata accountName) external onlyOwner returns (bytes32 accountId) {\r\n accountId = _createSubAccount(accountName);\r\n personalAccount[accountId] = true;\r\n emit PersonalAccountCreated(accountId);\r\n }\r\n\r\n function _createSubAccount(string memory accountName) internal returns (bytes32 accountId) {\r\n accountId = keccak256(\r\n abi.encodePacked(accountName, address(this), block.timestamp, subAccountIds.length)\r\n );\r\n require(!activeSubAccounts[accountId], \"Account ID collision\");\r\n activeSubAccounts[accountId] = true;\r\n subAccountIds.push(accountId);\r\n emit SubAccountCreated(accountId, accountName);\r\n }\r\n\r\n // ───────────── Configuración ─────────────\r\n\r\n /**\r\n * @notice Cambia la subcuenta que recibe los rewards (debe existir y no ser personal).\r\n */\r\n function setRewardsAccount(bytes32 accountId) external onlyOwner {\r\n if (!activeSubAccounts[accountId]) revert InvalidSubAccount();\r\n if (personalAccount[accountId]) revert Bank_PersonalAccount();\r\n rewardsAccountId = accountId;\r\n emit RewardsAccountSet(accountId);\r\n }\r\n\r\n function setTransactionManager(address _manager) external onlyOwner {\r\n if (_manager == address(0)) revert Bank_InvalidAddress();\r\n transactionManager = _manager;\r\n emit TransactionManagerSet(_manager);\r\n }\r\n\r\n // ───────────── Depósitos ─────────────\r\n\r\n /**\r\n * @notice Deposita un token ERC20 habilitado en una subcuenta del banco.\r\n * @dev El depositante debe haber hecho `approve` previamente a este contrato.\r\n * Se acredita la cantidad realmente recibida (soporta tokens con comisión por transferencia).\r\n * No cobra fee de rewards.\r\n */\r\n function deposit(bytes32 accountId, address tokenAddr, uint256 amount) external nonReentrant {\r\n if (!activeSubAccounts[accountId]) revert InvalidSubAccount();\r\n if (!supportedToken[tokenAddr]) revert Bank_TokenNotSupported();\r\n if (amount == 0) revert Bank_ZeroAmount();\r\n\r\n IERC20 t = IERC20(tokenAddr);\r\n uint256 balanceBefore = t.balanceOf(address(this));\r\n t.safeTransferFrom(msg.sender, address(this), amount);\r\n uint256 received = t.balanceOf(address(this)) - balanceBefore;\r\n\r\n if (received == 0) revert Bank_ZeroAmount();\r\n\r\n accountBalances[accountId][tokenAddr] += received;\r\n emit TokenDeposited(accountId, msg.sender, tokenAddr, received);\r\n }\r\n\r\n // ───────────── Retiros ─────────────\r\n\r\n /**\r\n * @notice Libera tokens de una subcuenta de la institución hacia el exterior.\r\n * El quórum ya se valida en LinealInstitution.releaseFromBank.\r\n * No puede usarse sobre cuentas personales de ciudadanos.\r\n */\r\n function release(\r\n bytes32 accountId,\r\n address tokenAddr,\r\n address to,\r\n uint256 amount,\r\n bytes32 reason\r\n ) external onlyOwner nonReentrant {\r\n if (!activeSubAccounts[accountId]) revert InvalidSubAccount();\r\n if (personalAccount[accountId]) revert Bank_PersonalAccount();\r\n _release(accountId, tokenAddr, to, amount, reason);\r\n }\r\n\r\n /// @notice El ciudadano retira un token desde SU subcuenta hacia cualquier address.\r\n function releaseFromMyAccount(address tokenAddr, address to, uint256 amount) external nonReentrant {\r\n bytes32 accountId = accountOf(msg.sender);\r\n _release(accountId, tokenAddr, to, amount, bytes32(\"citizen\"));\r\n }\r\n\r\n function _release(\r\n bytes32 accountId,\r\n address tokenAddr,\r\n address to,\r\n uint256 amount,\r\n bytes32 reason\r\n ) internal {\r\n if (to == address(0)) revert Bank_InvalidAddress();\r\n if (amount == 0) revert Bank_ZeroAmount();\r\n if (accountBalances[accountId][tokenAddr] < amount) revert Bank_InsufficientBalance();\r\n\r\n accountBalances[accountId][tokenAddr] -= amount;\r\n\r\n IERC20(tokenAddr).safeTransfer(to, amount);\r\n\r\n emit TokenReleased(accountId, msg.sender, to, tokenAddr, amount, reason);\r\n }\r\n\r\n // ───────────── Transferencias internas ─────────────\r\n\r\n /**\r\n * @notice Mueve tokens entre dos subcuentas, ordenado por la Institución (multisig).\r\n * @dev Cobra `rewardsBps` sobre `amount`: la cuenta destino recibe `amount - fee` y la\r\n * cuenta de rewards recibe `fee`, ambos en el mismo token. No se cobra fee si origen o destino\r\n * es la cuenta de rewards. El origen no puede ser una cuenta personal.\r\n */\r\n function internalTransfer(\r\n bytes32 fromAccount,\r\n bytes32 toAccount,\r\n address tokenAddr,\r\n uint256 amount\r\n ) external onlyOwner {\r\n if (personalAccount[fromAccount]) revert Bank_PersonalAccount();\r\n _internalTransfer(fromAccount, toAccount, tokenAddr, amount);\r\n }\r\n\r\n function zeroFeeInternalTransfer(\r\n bytes32 fromAccount,\r\n bytes32 toAccount,\r\n address tokenAddr,\r\n uint256 amount\r\n ) external onlyOwner {\r\n if (personalAccount[fromAccount]) revert Bank_PersonalAccount();\r\n _zeroFeeInternalTransfer(fromAccount, toAccount, tokenAddr, amount);\r\n }\r\n\r\n /**\r\n * @notice El ciudadano mueve fondos desde SU subcuenta (la de su perfil NFT).\r\n * @dev Aplica el mismo fee de rewards que `internalTransfer`.\r\n */\r\n function moveFromMyAccount(bytes32 toAccount, address tokenAddr, uint256 amount) external nonReentrant {\r\n bytes32 fromAccount = accountOf(msg.sender);\r\n _internalTransfer(fromAccount, toAccount, tokenAddr, amount);\r\n emit CitizenTransfer(msg.sender, fromAccount, toAccount, tokenAddr, amount);\r\n }\r\n\r\n /// @notice Subcuenta del perfil de `wallet`, leída desde LinealCitizens.\r\n function accountOf(address wallet) public view returns (bytes32) {\r\n address identity = IInstitutionIdentity(institutionAddress).getIdentity();\r\n if (identity == address(0)) revert Bank_IdentityNotLinked();\r\n bytes32 id = ICitizensAccounts(identity).subAccountOf(wallet);\r\n if (id == bytes32(0)) revert Bank_NoAccount();\r\n return id;\r\n }\r\n\r\n function _internalTransfer(\r\n bytes32 fromAccount,\r\n bytes32 toAccount,\r\n address tokenAddr,\r\n uint256 amount\r\n ) internal {\r\n if (!activeSubAccounts[fromAccount] || !activeSubAccounts[toAccount]) revert InvalidSubAccount();\r\n require(fromAccount != toAccount, \"ReserveBank: same account\");\r\n if (amount == 0) revert Bank_ZeroAmount();\r\n if (accountBalances[fromAccount][tokenAddr] < amount) revert Bank_InsufficientBalance();\r\n\r\n uint256 fee = 0;\r\n if (fromAccount != rewardsAccountId && toAccount != rewardsAccountId) {\r\n fee = (amount * rewardsBps) / BPS_DENOMINATOR;\r\n }\r\n\r\n accountBalances[fromAccount][tokenAddr] -= amount;\r\n accountBalances[toAccount][tokenAddr] += amount - fee;\r\n\r\n if (fee > 0) {\r\n accountBalances[rewardsAccountId][tokenAddr] += fee;\r\n emit RewardsFeeCharged(fromAccount, rewardsAccountId, tokenAddr, fee);\r\n }\r\n\r\n emit InternalTransfer(fromAccount, toAccount, tokenAddr, amount);\r\n }\r\n\r\n function _zeroFeeInternalTransfer(\r\n bytes32 fromAccount,\r\n bytes32 toAccount,\r\n address tokenAddr,\r\n uint256 amount\r\n ) internal {\r\n if (!activeSubAccounts[fromAccount] || !activeSubAccounts[toAccount]) revert InvalidSubAccount();\r\n require(fromAccount != toAccount, \"ReserveBank: same account\");\r\n if (amount == 0) revert Bank_ZeroAmount();\r\n if (accountBalances[fromAccount][tokenAddr] < amount) revert Bank_InsufficientBalance();\r\n\r\n accountBalances[fromAccount][tokenAddr] -= amount;\r\n accountBalances[toAccount][tokenAddr] += amount;\r\n\r\n emit InternalTransfer(fromAccount, toAccount, tokenAddr, amount);\r\n }\r\n // ───────────── Transferencias entre bancos ─────────────\r\n\r\n /**\r\n * @notice Envía fondos de una subcuenta de ESTE banco a una subcuenta de OTRO banco.\r\n * @dev Ordenado por la Institución (multisig). El banco destino debe tener habilitado el token.\r\n * Se cobra el mismo fee de rewards que en una transferencia interna (queda en este banco);\r\n * el banco destino recibe `amount - fee` mediante su `deposit`, que acredita lo realmente\r\n * recibido. El origen no puede ser una cuenta personal.\r\n * @param fromAccount Subcuenta de origen en este banco.\r\n * @param destBank Dirección del contrato LinealBank destino.\r\n * @param toAccount Subcuenta de destino en `destBank`.\r\n * @param tokenAddr Token a enviar.\r\n * @param amount Monto bruto a debitar de `fromAccount`.\r\n */\r\n function transferToBank(\r\n bytes32 fromAccount,\r\n address destBank,\r\n bytes32 toAccount,\r\n address tokenAddr,\r\n uint256 amount\r\n ) external onlyOwner nonReentrant {\r\n if (destBank == address(0) || destBank == address(this)) revert Bank_InvalidAddress();\r\n if (!activeSubAccounts[fromAccount]) revert InvalidSubAccount();\r\n if (personalAccount[fromAccount]) revert Bank_PersonalAccount();\r\n if (amount == 0) revert Bank_ZeroAmount();\r\n if (accountBalances[fromAccount][tokenAddr] < amount) revert Bank_InsufficientBalance();\r\n if (!IBankDeposit(destBank).isTokenSupported(tokenAddr)) revert Bank_TokenNotSupported();\r\n\r\n uint256 fee = 0;\r\n if (fromAccount != rewardsAccountId) {\r\n fee = (amount * rewardsBps) / BPS_DENOMINATOR;\r\n }\r\n uint256 net = amount - fee;\r\n if (net == 0) revert Bank_ZeroAmount();\r\n\r\n // Efectos primero\r\n accountBalances[fromAccount][tokenAddr] -= amount;\r\n if (fee > 0) {\r\n accountBalances[rewardsAccountId][tokenAddr] += fee;\r\n emit RewardsFeeCharged(fromAccount, rewardsAccountId, tokenAddr, fee);\r\n }\r\n\r\n // Interacción: aprobar solo `net`, depositar en el banco destino y limpiar la aprobación\r\n IERC20 t = IERC20(tokenAddr);\r\n t.forceApprove(destBank, net);\r\n IBankDeposit(destBank).deposit(toAccount, tokenAddr, net);\r\n t.forceApprove(destBank, 0);\r\n\r\n emit BankTransfer(fromAccount, destBank, toAccount, tokenAddr, amount, fee);\r\n }\r\n\r\n // ───────────── Gestor de transacciones ─────────────\r\n\r\n /**\r\n * @notice Ejecuta la liberación basada en una transacción validada por el gestor.\r\n * Solo puede ser llamada por el transactionManager.\r\n * No puede mover fondos de cuentas personales.\r\n */\r\n function executeTransactionRelease(bytes32 txId) external nonReentrant {\r\n if (msg.sender != transactionManager) revert Bank_Unauthorized();\r\n\r\n (address to, address tokenAddr, uint256 amount, bool executed, bytes32 fromAccount) =\r\n ILinealTransactions(transactionManager).getTransactionForBank(txId);\r\n\r\n if (!executed) revert Bank_TransactionNotExecuted();\r\n if (personalAccount[fromAccount]) revert Bank_PersonalAccount();\r\n if (to == address(0)) revert Bank_InvalidAddress();\r\n if (accountBalances[fromAccount][tokenAddr] < amount) revert Bank_InsufficientBalance();\r\n\r\n accountBalances[fromAccount][tokenAddr] -= amount;\r\n\r\n IERC20(tokenAddr).safeTransfer(to, amount);\r\n\r\n emit TokenReleased(fromAccount, msg.sender, to, tokenAddr, amount, txId);\r\n }\r\n\r\n // ───────────── Vistas ─────────────\r\n\r\n function accountBalance(bytes32 accountId, address tokenAddr) external view returns (uint256) {\r\n return accountBalances[accountId][tokenAddr];\r\n }\r\n\r\n /// @notice Saldos de una subcuenta en todos los tokens registrados (para paneles y apps).\r\n function accountBalancesAll(bytes32 accountId)\r\n external\r\n view\r\n returns (address[] memory tokens, uint256[] memory balances)\r\n {\r\n uint256 n = _tokenList.length;\r\n tokens = new address[](n);\r\n balances = new uint256[](n);\r\n for (uint256 i; i < n; i++) {\r\n tokens[i] = _tokenList[i];\r\n balances[i] = accountBalances[accountId][_tokenList[i]];\r\n }\r\n }\r\n\r\n /// @notice Tokens registrados (habilitados o no); consulta `supportedToken` para el estado.\r\n function tokenList() external view returns (address[] memory) {\r\n return _tokenList;\r\n }\r\n\r\n /// @notice Total de un token que custodia el banco.\r\n function totalReserveBalance(address tokenAddr) external view returns (uint256) {\r\n return IERC20(tokenAddr).balanceOf(address(this));\r\n }\r\n}\r\n\r\ninterface ILinealTransactions {\r\n function getTransactionForBank(bytes32 txId) external view returns (\r\n address to,\r\n address token,\r\n uint256 amount,\r\n bool executed,\r\n bytes32 fromAccount\r\n );\r\n}\r\n\r\n/// @notice Mínima interfaz de LinealInstitution para resolver la identidad vinculada.\r\ninterface IInstitutionIdentity {\r\n function getIdentity() external view returns (address);\r\n}\r\n\r\n/// @notice Mínima interfaz de LinealCitizens para resolver la subcuenta de un perfil.\r\ninterface ICitizensAccounts {\r\n function subAccountOf(address wallet) external view returns (bytes32);\r\n}\r\n\r\n/// @notice Mínima interfaz de otro LinealBank para recibir fondos.\r\ninterface IBankDeposit {\r\n function isTokenSupported(address token) external view returns (bool);\r\n function deposit(bytes32 accountId, address token, uint256 amount) external;\r\n}\r\n"
|
|
275
|
+
},
|
|
276
|
+
"project/contracts/economy/banks/LinealQantum.sol": {
|
|
277
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"../../core/Groth16Verifier.sol\";\r\n\r\nabstract contract LinealQantum {\r\n\r\n address[] public signers;\r\n uint256 public requiredSignatures;\r\n address public guardian;\r\n\r\n mapping(bytes32 => mapping(address => bool)) public isConfirmed;\r\n mapping(bytes32 => uint256) public confirmationCount;\r\n mapping(bytes32 => bool) public isExecuted;\r\n\r\n mapping(address => bytes32) public quantumCommitments;\r\n mapping(bytes32 => bool) public usedNullifiers;\r\n\r\n struct RecoveryProposal {\r\n address[] newSigners;\r\n uint256 newRequired;\r\n uint256 proposedAt;\r\n uint256 confirmations;\r\n bool executed;\r\n mapping(address => bool) confirmedBy;\r\n }\r\n\r\n mapping(bytes32 => RecoveryProposal) private _recoveryProposals;\r\n uint256 public recoveryQuorum;\r\n uint256 public constant RECOVERY_DELAY = 2 hours;\r\n\r\n struct ZKProof {\r\n uint[2] pA;\r\n uint[2][2] pB;\r\n uint[2] pC;\r\n // Orden exacto que produce snarkJS para SecretVerifier():\r\n // output primero, luego inputs públicos en orden de declaración del component main\r\n // [0] nullifier ← output\r\n // [1] commitment ← public input (declarado 1º en component main)\r\n // [2] txHash ← public input (declarado 2º)\r\n // [3] contractAddress ← public input (declarado 3º)\r\n // [4] chainId ← public input (declarado 4º)\r\n // [5] signerAddress ← public input (declarado 5º)\r\n uint[6] pubSignals;\r\n }\r\n\r\n Groth16Verifier public zkVerifier;\r\n\r\n event ActionProposed(bytes32 indexed txHash, address indexed proposer, string actionType);\r\n event ActionConfirmed(bytes32 indexed txHash, address indexed signer);\r\n event ActionExecuted(bytes32 indexed txHash);\r\n event SignersRotated(address[] newSigners, uint256 newRequired);\r\n event GuardianUpdated(address newGuardian);\r\n event QuantumCommitmentUpdated(address indexed signer, bytes32 commitment);\r\n event RecoveryProposed(bytes32 indexed recoveryHash, address indexed proposer);\r\n event RecoveryConfirmed(bytes32 indexed recoveryHash, address indexed confirmer, uint256 confirmations);\r\n event RecoveryExecuted(bytes32 indexed recoveryHash);\r\n\r\n modifier onlySigner() {\r\n require(_isSigner(msg.sender), \"MultiSig: caller is not a signer\");\r\n _;\r\n }\r\n\r\n modifier onlyGuardian() {\r\n require(msg.sender == guardian, \"MultiSig: only guardian\");\r\n _;\r\n }\r\n\r\n constructor(\r\n address[] memory _signers,\r\n uint256 _required,\r\n address _guardian,\r\n address _zkVerifier,\r\n uint256 _recoveryQuorum\r\n ) {\r\n require(_signers.length >= _required, \"MultiSig: signers < required\");\r\n require(_required > 0, \"MultiSig: required must be > 0\");\r\n require(_guardian != address(0), \"MultiSig: invalid guardian\");\r\n require(_zkVerifier != address(0), \"MultiSig: invalid zkVerifier\");\r\n require(_recoveryQuorum > 0, \"MultiSig: recoveryQuorum must be > 0\");\r\n\r\n for (uint256 i = 0; i < _signers.length; i++) {\r\n require(_signers[i] != address(0), \"MultiSig: invalid signer\");\r\n for (uint256 j = 0; j < i; j++) {\r\n require(_signers[i] != _signers[j], \"MultiSig: duplicate signer\");\r\n }\r\n signers.push(_signers[i]);\r\n }\r\n\r\n requiredSignatures = _required;\r\n guardian = _guardian;\r\n zkVerifier = Groth16Verifier(_zkVerifier);\r\n recoveryQuorum = _recoveryQuorum;\r\n }\r\n\r\n // ═══════════════════════════════════════════════════════════\r\n // BLOQUE H — RECOVERY\r\n // ═══════════════════════════════════════════════════════════\r\n\r\n function proposeRecovery(\r\n address[] memory _newSigners,\r\n uint256 _newRequired\r\n ) external onlyGuardian returns (bytes32 recoveryHash) {\r\n require(_newSigners.length >= _newRequired, \"MultiSig: signers < required\");\r\n require(_newRequired > 0, \"MultiSig: required > 0\");\r\n\r\n for (uint256 i = 0; i < _newSigners.length; i++) {\r\n require(_newSigners[i] != address(0), \"MultiSig: invalid signer\");\r\n for (uint256 j = 0; j < i; j++) {\r\n require(_newSigners[i] != _newSigners[j], \"MultiSig: duplicate signer\");\r\n }\r\n }\r\n\r\n recoveryHash = keccak256(abi.encode(\r\n _newSigners,\r\n _newRequired,\r\n block.timestamp,\r\n address(this),\r\n block.chainid\r\n ));\r\n\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt == 0, \"MultiSig: proposal already exists\");\r\n\r\n proposal.newSigners = _newSigners;\r\n proposal.newRequired = _newRequired;\r\n proposal.proposedAt = block.timestamp;\r\n proposal.confirmations = 1;\r\n proposal.confirmedBy[msg.sender] = true;\r\n\r\n emit RecoveryProposed(recoveryHash, msg.sender);\r\n emit RecoveryConfirmed(recoveryHash, msg.sender, 1);\r\n }\r\n\r\n function confirmRecovery(bytes32 recoveryHash) external onlyGuardian {\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt != 0, \"MultiSig: proposal not found\");\r\n require(!proposal.executed, \"MultiSig: already executed\");\r\n require(!proposal.confirmedBy[msg.sender], \"MultiSig: already confirmed\");\r\n\r\n proposal.confirmedBy[msg.sender] = true;\r\n proposal.confirmations++;\r\n\r\n emit RecoveryConfirmed(recoveryHash, msg.sender, proposal.confirmations);\r\n }\r\n\r\n function executeRecovery(bytes32 recoveryHash) external onlyGuardian {\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt != 0, \"MultiSig: proposal not found\");\r\n require(!proposal.executed, \"MultiSig: already executed\");\r\n require(\r\n proposal.confirmations >= recoveryQuorum,\r\n \"MultiSig: insufficient recovery confirmations\"\r\n );\r\n require(\r\n block.timestamp >= proposal.proposedAt + RECOVERY_DELAY,\r\n \"MultiSig: recovery delay not elapsed\"\r\n );\r\n\r\n proposal.executed = true;\r\n signers = proposal.newSigners;\r\n requiredSignatures = proposal.newRequired;\r\n\r\n emit SignersRotated(proposal.newSigners, proposal.newRequired);\r\n emit RecoveryExecuted(recoveryHash);\r\n }\r\n\r\n function setGuardian(address _newGuardian) external onlyGuardian {\r\n require(_newGuardian != address(0), \"MultiSig: invalid guardian\");\r\n guardian = _newGuardian;\r\n emit GuardianUpdated(_newGuardian);\r\n }\r\n\r\n // ═══════════════════════════════════════════════\r\n // CORE ZK\r\n // ═══════════════════════════════════════════════\r\n\r\n function _isSigner(address account) public view returns (bool) {\r\n for (uint256 i = 0; i < signers.length; i++) {\r\n if (signers[i] == account) return true;\r\n }\r\n return false;\r\n }\r\n\r\n function setQuantumCommitment(bytes32 _hash) external onlySigner {\r\n require(_hash != bytes32(0), \"MultiSig: invalid hash\");\r\n quantumCommitments[msg.sender] = _hash;\r\n emit QuantumCommitmentUpdated(msg.sender, _hash);\r\n }\r\n\r\n function confirmWithZK(\r\n bytes32 txHash,\r\n string memory actionType,\r\n ZKProof memory proof\r\n ) internal returns (bool) {\r\n return _confirmWithZKFor(txHash, msg.sender, actionType, proof);\r\n }\r\n\r\n function _confirmWithZKFor(\r\n bytes32 txHash,\r\n address signer,\r\n string memory actionType,\r\n ZKProof memory proof\r\n ) internal returns (bool) {\r\n // BLOQUE G: guard temprano\r\n require(!isExecuted[txHash], \"ZK: action already executed\");\r\n\r\n require(_isSigner(signer), \"ZK: not a signer\");\r\n require(quantumCommitments[signer] != bytes32(0), \"ZK: commitment required\");\r\n\r\n // [0] nullifier — anti-replay\r\n require(!usedNullifiers[bytes32(proof.pubSignals[0])], \"ZK: nullifier already used\");\r\n\r\n // [1] commitment — binding al secreto registrado on-chain\r\n require(\r\n quantumCommitments[signer] == bytes32(proof.pubSignals[1]),\r\n \"ZK: commitment mismatch\"\r\n );\r\n\r\n // [2] txHash — binding a la acción concreta\r\n require(\r\n txHash == bytes32(proof.pubSignals[2]),\r\n \"ZK: txHash mismatch\"\r\n );\r\n\r\n // [3] contractAddress — domain separation (CORREGIDO: era [4])\r\n require(\r\n address(this) == address(uint160(proof.pubSignals[3])),\r\n \"ZK: contract mismatch\"\r\n );\r\n\r\n // [4] chainId — domain separation (CORREGIDO: era [5])\r\n require(\r\n block.chainid == proof.pubSignals[4],\r\n \"ZK: chainId mismatch\"\r\n );\r\n\r\n // [5] signerAddress — identity binding (CORREGIDO: era [3])\r\n require(\r\n signer == address(uint160(proof.pubSignals[5])),\r\n \"ZK: signer mismatch\"\r\n );\r\n\r\n // Verificación ZK al final — operación más costosa\r\n require(\r\n zkVerifier.verifyProof(proof.pA, proof.pB, proof.pC, proof.pubSignals),\r\n \"ZK: Invalid proof\"\r\n );\r\n\r\n // Quemar nullifier después de verificación exitosa\r\n usedNullifiers[bytes32(proof.pubSignals[0])] = true;\r\n\r\n return _confirmActionFor(txHash, signer, actionType);\r\n }\r\n\r\n mapping(string => uint256) public actionNonce;\r\n\r\n function getActionNonce(string memory actionType) public view returns (uint256) {\r\n return actionNonce[actionType];\r\n }\r\n\r\n function _computeActionHash(\r\n string memory actionType,\r\n bytes memory params\r\n ) internal view returns (bytes32) {\r\n return keccak256(abi.encode(\r\n keccak256(bytes(actionType)),\r\n address(this),\r\n block.chainid,\r\n params,\r\n keccak256(params),\r\n actionNonce[actionType]\r\n ));\r\n }\r\n\r\n function _confirmActionFor(\r\n bytes32 txHash,\r\n address signer,\r\n string memory actionType\r\n ) internal returns (bool) {\r\n require(!isExecuted[txHash], \"MultiSig: action already executed\");\r\n require(!isConfirmed[txHash][signer], \"MultiSig: already confirmed\");\r\n\r\n isConfirmed[txHash][signer] = true;\r\n confirmationCount[txHash]++;\r\n\r\n if (confirmationCount[txHash] == 1) {\r\n emit ActionProposed(txHash, signer, actionType);\r\n }\r\n\r\n emit ActionConfirmed(txHash, signer);\r\n\r\n if (confirmationCount[txHash] >= requiredSignatures) {\r\n isExecuted[txHash] = true;\r\n actionNonce[actionType]++;\r\n emit ActionExecuted(txHash);\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n}"
|
|
278
|
+
},
|
|
279
|
+
"project/contracts/economy/banks/LinealTransaction.sol": {
|
|
280
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"./LinealQantum.sol\";\r\n\r\n/**\r\n * @title AdministrativeAuthorizationTransferContract\r\n * @notice Contrato con MultiSig estático (heredado) + MultiSig dinámico (autorizadores administrativos)\r\n *\r\n * FLUJO:\r\n * 1. Operador CREA transacción (NO firma, solo ingresa data) + define 3 wallets autorizadoras\r\n * 2. MultiSig DINÁMICO: 3/3 autorizadores administrativos deben firmar\r\n * 3. MultiSig ESTÁTICO: Signers institucionales/quorum firman (heredado de MultiSigBase)\r\n * 4. EJECUCIÓN: Cuando ambos MultiSig completos → ejecuta\r\n */\r\ninterface ILinealBank {\r\n function executeTransactionRelease(bytes32 txId) external;\r\n}\r\n\r\ncontract LinealTransactions is LinealQantum {\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // ESTRUCTURAS\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n struct TransactionMetadata {\r\n string recipientName;\r\n string motivo;\r\n string documento;\r\n string mensaje;\r\n string tipo;\r\n }\r\n\r\n struct QorumTransaction {\r\n address to;\r\n uint256 amount;\r\n bytes32 referenceHash;\r\n address createdBy;\r\n uint256 timestamp;\r\n uint256 expiresAt;\r\n bool executed;\r\n bool cancelled;\r\n\r\n address fromAccount;\r\n address tokenAddress;\r\n\r\n // Metadatos Institucionales\r\n TransactionMetadata meta;\r\n\r\n // MultiSig Dinámico\r\n address[3] administrativeAuthorizers;\r\n mapping(address => bool) hasAuthorized;\r\n uint256 adminSignatures;\r\n\r\n bool staticMultiSigCompleted;\r\n }\r\n\r\n uint256 public txCounter;\r\n mapping(bytes32 => bool) public referenceHashUsed;\r\n\r\n address public bankAddress;\r\n\r\n function setBankAddress(address _bank) external onlyGuardian {\r\n bankAddress = _bank;\r\n }\r\n\r\n // DEPRECATED: RolesContract removido del sistema\r\n // RolesContract public rolesContract;\r\n\r\n // Transacciones administrativas\r\n mapping(bytes32 => QorumTransaction) public transactions;\r\n bytes32[] public transactionIds;\r\n\r\n // Historial de transacciones ejecutadas\r\n struct ExecutedTransfer {\r\n address to;\r\n uint256 amount;\r\n bytes32 referenceHash;\r\n address createdBy;\r\n uint256 timestamp;\r\n TransactionMetadata meta;\r\n }\r\n ExecutedTransfer[] public transferHistory;\r\n\r\n // Balance simulado\r\n mapping(address => uint256) public entityBalance;\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // EVENTOS\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n event TransactionCreated(\r\n bytes32 indexed txId,\r\n address indexed to,\r\n uint256 amount,\r\n bytes32 referenceHash,\r\n address createdBy,\r\n string recipientName,\r\n string tipo\r\n );\r\n\r\n event TransactionCancelled(bytes32 indexed txId);\r\n\r\n event AdministrativeAuthorized(\r\n bytes32 indexed txId,\r\n address indexed authorizer,\r\n uint256 adminSignatures\r\n );\r\n\r\n event StaticMultiSigCompleted(\r\n bytes32 indexed txId\r\n );\r\n\r\n event TransactionExecuted(\r\n bytes32 indexed txId,\r\n address indexed to,\r\n uint256 amount,\r\n bytes32 referenceHash\r\n );\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // CONSTRUCTOR\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n constructor(\r\n address[] memory _signers,\r\n uint256 _required,\r\n address _guardian,\r\n address _zkVerifier,\r\n uint256 recoveryQorum\r\n ) LinealQantum(_signers, _required, _guardian, _zkVerifier, recoveryQorum) {}\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // FASE 1: CREACIÓN (Operador NO firma, solo crea)\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n /**\r\n * @notice Operador crea transacción y define 3 autorizadores administrativos\r\n * @param _to Destinatario\r\n * @param _amount Monto\r\n * @param _referenceHash Hash de referencia\r\n * @param _administrativeAuthorizers [3] Wallets que deben autorizar (MultiSig dinámico)\r\n * @return txId ID de la transacción\r\n */\r\n function createTransaction(\r\n address _to,\r\n uint256 _amount,\r\n bytes32 _referenceHash,\r\n address[3] memory _administrativeAuthorizers,\r\n address _fromAccount,\r\n address _tokenAddress,\r\n TransactionMetadata memory _meta\r\n ) external onlySigner returns (bytes32 txId) {\r\n require(_to != address(0), \"AAC: invalid recipient\");\r\n require(_amount > 0, \"AAC: invalid amount\");\r\n require(_referenceHash != bytes32(0), \"AAC: reference required\");\r\n require(!referenceHashUsed[_referenceHash], \"AAC: reference already used\");\r\n\r\n // Validar autorizadores administrativos y separación de deberes\r\n for (uint256 i = 0; i < 3; i++) {\r\n require(_administrativeAuthorizers[i] != address(0), \"AAC: invalid authorizer\");\r\n require(!_isSigner(_administrativeAuthorizers[i]), \"AAC: authorizer cannot be static signer\");\r\n for (uint256 j = 0; j < i; j++) {\r\n require(_administrativeAuthorizers[i] != _administrativeAuthorizers[j], \"AAC: duplicate authorizer\");\r\n }\r\n }\r\n\r\n // Generar ID único con contador y encode\r\n txId = keccak256(abi.encode(\r\n _to,\r\n _amount,\r\n _referenceHash,\r\n msg.sender,\r\n block.timestamp,\r\n txCounter++\r\n ));\r\n\r\n require(transactions[txId].timestamp == 0, \"AAC: txId collision\");\r\n\r\n // Crear transacción\r\n transactions[txId].to = _to;\r\n transactions[txId].amount = _amount;\r\n transactions[txId].referenceHash = _referenceHash;\r\n transactions[txId].createdBy = msg.sender;\r\n transactions[txId].timestamp = block.timestamp;\r\n transactions[txId].expiresAt = block.timestamp + 3 days;\r\n transactions[txId].administrativeAuthorizers = _administrativeAuthorizers;\r\n transactions[txId].fromAccount = _fromAccount;\r\n transactions[txId].tokenAddress = _tokenAddress;\r\n transactions[txId].meta = _meta;\r\n\r\n transactionIds.push(txId);\r\n referenceHashUsed[_referenceHash] = true;\r\n\r\n emit TransactionCreated(\r\n txId,\r\n _to,\r\n _amount,\r\n _referenceHash,\r\n msg.sender,\r\n _meta.recipientName,\r\n _meta.tipo\r\n );\r\n\r\n return txId;\r\n }\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // FASE 2: AUTORIZACIÓN (TODO pasa por MultiSig heredado)\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n /**\r\n * @notice Agregador de Consenso 9/9\r\n * Procesa 3 firmas humanas y 6 pruebas ZK de servidores en una sola transacción.\r\n */\r\n function aggregateConsensus(\r\n bytes32 txId,\r\n bytes[3] calldata humanSignatures,\r\n ZKProof[6] calldata serverProofs,\r\n address[6] calldata serverAddresses\r\n ) external {\r\n QorumTransaction storage txn = transactions[txId];\r\n require(txn.timestamp > 0, \"AAC: not found\");\r\n require(!txn.executed, \"AAC: already executed\");\r\n\r\n // 1. Validar Capa Humana (3/3 Administrativos)\r\n // El hash debe ser el txId firmado por el operador\r\n bytes32 ethHash = keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", txId));\r\n for (uint256 i = 0; i < 3; i++) {\r\n address authorizer = txn.administrativeAuthorizers[i];\r\n require(!txn.hasAuthorized[authorizer], \"AAC: human already authorized\");\r\n\r\n address signer = _recoverSigner(ethHash, humanSignatures[i]);\r\n require(signer == authorizer, \"AAC: invalid human signature\");\r\n\r\n txn.hasAuthorized[authorizer] = true;\r\n txn.adminSignatures++;\r\n }\r\n\r\n // 2. Validar Capa de Servidores (6/6 Institucionales)\r\n // Usamos el hash de acción estándar del contrato\r\n bytes32 actionHash = keccak256(abi.encode(\"authorizeTransaction\", txId));\r\n for (uint256 i = 0; i < 6; i++) {\r\n require(_confirmWithZKFor(actionHash, serverAddresses[i], \"authorizeTransaction\", serverProofs[i]), \"AAC: ZK validation failed\");\r\n }\r\n\r\n // 3. Verificación de Quorum Estático\r\n if (confirmationCount[actionHash] >= requiredSignatures) {\r\n txn.staticMultiSigCompleted = true;\r\n emit StaticMultiSigCompleted(txId);\r\n }\r\n\r\n // 4. Intento de Ejecución Automática\r\n _tryExecute(txId);\r\n }\r\n\r\n /**\r\n * @notice Función de consulta para el banco\r\n */\r\n function getTransactionForBank(bytes32 txId) external view returns (\r\n address to,\r\n uint256 amount,\r\n bool executed,\r\n address fromAccount,\r\n address tokenAddress\r\n ) {\r\n QorumTransaction storage txn = transactions[txId];\r\n return (txn.to, txn.amount, txn.executed, txn.fromAccount, txn.tokenAddress);\r\n }\r\n\r\n function _recoverSigner(bytes32 _hash, bytes memory _signature) internal pure returns (address) {\r\n if (_signature.length != 65) return address(0);\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n r := mload(add(_signature, 32))\r\n s := mload(add(_signature, 64))\r\n v := byte(0, mload(add(_signature, 96)))\r\n }\r\n return ecrecover(_hash, v, r, s);\r\n }\r\n\r\n /**\r\n * @notice Autoriza transacción (SIEMPRE a través de MultiSig heredado)\r\n * @dev Valida que caller sea signer de red O autorizador humano definido\r\n * @param txId ID de la transacción\r\n */\r\n function authorizeTransaction(bytes32 txId) external {\r\n QorumTransaction storage txn = transactions[txId];\r\n\r\n require(txn.timestamp > 0, \"AAC: transaction not found\");\r\n require(!txn.executed, \"AAC: already executed\");\r\n require(!txn.cancelled, \"AAC: cancelled\");\r\n require(block.timestamp <= txn.expiresAt, \"AAC: expired\");\r\n\r\n bool isStaticSigner = _isSigner(msg.sender);\r\n bool isHumanAuthorizer = false;\r\n\r\n for (uint256 i = 0; i < 3; i++) {\r\n if (txn.administrativeAuthorizers[i] == msg.sender) {\r\n isHumanAuthorizer = true;\r\n break;\r\n }\r\n }\r\n\r\n require(\r\n isStaticSigner || isHumanAuthorizer,\r\n \"AAC: unauthorized\"\r\n );\r\n\r\n // BLOQUE C: Generar hash robusto con abi.encode y domain separation\r\n bytes32 actionHash = _computeActionHash(\r\n \"authorizeTransaction\",\r\n abi.encode(txId)\r\n );\r\n\r\n if (isStaticSigner) {\r\n // Usamos el hash único basado en txId para que cada tx tenga su propio ciclo de firmas\r\n if (_confirmActionFor(actionHash, msg.sender, \"authorizeTransaction\")) {\r\n txn.staticMultiSigCompleted = true;\r\n emit StaticMultiSigCompleted(txId);\r\n }\r\n }\r\n\r\n if (isHumanAuthorizer && !txn.hasAuthorized[msg.sender]) {\r\n txn.hasAuthorized[msg.sender] = true;\r\n txn.adminSignatures++;\r\n emit AdministrativeAuthorized(txId, msg.sender, txn.adminSignatures);\r\n }\r\n\r\n _tryExecute(txId);\r\n }\r\n\r\n /**\r\n * @notice Cancela una transacción. Solo por el creador o por MultiSig.\r\n */\r\n function cancelTransaction(bytes32 txId) external onlySigner {\r\n QorumTransaction storage txn = transactions[txId];\r\n require(txn.timestamp > 0, \"AAC: not found\");\r\n require(!txn.executed, \"AAC: already executed\");\r\n\r\n bool isCreator = (msg.sender == txn.createdBy);\r\n bool isMultiSig = false;\r\n\r\n // BLOQUE C: Generar hash robusto con abi.encode y domain separation\r\n bytes32 actionHash = _computeActionHash(\r\n \"cancelTransaction\",\r\n abi.encode(txId)\r\n );\r\n if (!_confirmActionFor(actionHash, msg.sender, \"cancelTransaction\")) return;\r\n\r\n if (isCreator) {\r\n txn.cancelled = true;\r\n emit TransactionCancelled(txId);\r\n }\r\n }\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // FASE 3: EJECUCIÓN (Ambos contadores completos)\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n /**\r\n * @notice Intenta ejecutar si ambos thresholds alcanzados\r\n * @dev 3/3 humanos + threshold de red (ambos a través de MultiSig heredado)\r\n */\r\n function _tryExecute(bytes32 txId) private {\r\n QorumTransaction storage txn = transactions[txId];\r\n\r\n if (txn.executed || txn.cancelled) return;\r\n\r\n // VALIDAR: 3/3 autorizadores humanos\r\n bool humanAuthorizersComplete = (txn.adminSignatures == 3);\r\n\r\n // VALIDAR: MultiSig de red completo (threshold alcanzado)\r\n bool networkMultiSigComplete = txn.staticMultiSigCompleted;\r\n\r\n // EJECUTAR solo si AMBOS completos\r\n if (humanAuthorizersComplete && networkMultiSigComplete) {\r\n txn.executed = true;\r\n\r\n // Registrar en historial\r\n transferHistory.push(ExecutedTransfer({\r\n to: txn.to,\r\n amount: txn.amount,\r\n referenceHash: txn.referenceHash,\r\n createdBy: txn.createdBy,\r\n timestamp: block.timestamp,\r\n meta: txn.meta\r\n }));\r\n\r\n // EJECUCIÓN REAL EN EL BANCO\r\n if (bankAddress != address(0)) {\r\n ILinealBank(bankAddress).executeTransactionRelease(txId);\r\n }\r\n\r\n emit TransactionExecuted(\r\n txId,\r\n txn.to,\r\n txn.amount,\r\n txn.referenceHash\r\n );\r\n }\r\n }\r\n\r\n // ═════════════════════════════════════════════════════════════════════════\r\n // FUNCIONES DE CONSULTA\r\n // ═════════════════════════════════════════════════════════════════════════\r\n\r\n function getTransactionStatus(bytes32 txId) external view returns (\r\n bool exists,\r\n bool executed,\r\n uint256 adminSignatures,\r\n bool adminMultiSigComplete,\r\n bool staticMultiSigComplete,\r\n bool canExecute,\r\n address to,\r\n uint256 amount\r\n ) {\r\n QorumTransaction storage txn = transactions[txId];\r\n bool adminComplete = (txn.adminSignatures == 3);\r\n\r\n return (\r\n txn.timestamp > 0,\r\n txn.executed,\r\n txn.adminSignatures,\r\n adminComplete,\r\n txn.staticMultiSigCompleted,\r\n adminComplete && txn.staticMultiSigCompleted,\r\n txn.to,\r\n txn.amount\r\n );\r\n }\r\n\r\n function getAdministrativeAuthorizers(bytes32 txId) external view returns (address[3] memory) {\r\n return transactions[txId].administrativeAuthorizers;\r\n }\r\n\r\n function hasUserAuthorized(bytes32 txId, address user) external view returns (bool) {\r\n return transactions[txId].hasAuthorized[user];\r\n }\r\n\r\n function getTransactionIds(uint256 from, uint256 to) external view returns (bytes32[] memory) {\r\n require(from <= to && to < transactionIds.length, \"AAC: invalid range\");\r\n uint256 size = to - from + 1;\r\n bytes32[] memory result = new bytes32[](size);\r\n for (uint256 i = 0; i < size; i++) {\r\n result[i] = transactionIds[from + i];\r\n }\r\n return result;\r\n }\r\n\r\n function getTransferHistory(uint256 from, uint256 to) external view returns (ExecutedTransfer[] memory) {\r\n require(from <= to && to < transferHistory.length, \"AAC: invalid range\");\r\n uint256 size = to - from + 1;\r\n ExecutedTransfer[] memory result = new ExecutedTransfer[](size);\r\n for (uint256 i = 0; i < size; i++) {\r\n result[i] = transferHistory[from + i];\r\n }\r\n return result;\r\n }\r\n\r\n function getTransactionCount() external view returns (uint256) {\r\n return transactionIds.length;\r\n }\r\n\r\n function getExecutedTransferCount() external view returns (uint256) {\r\n return transferHistory.length;\r\n }\r\n}\r\n"
|
|
281
|
+
},
|
|
282
|
+
"project/contracts/economy/interfaces/ICLPStablecoin.sol": {
|
|
283
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n\r\n/**\r\n * @title ICLPStablecoin\r\n * @notice Interfaz para la stablecoin CLP (Peso Chileno) regulada.\r\n * \r\n * CUMPLIMIENTO REGULATORIO:\r\n * - KYC/AML obligatorio mediante whitelist\r\n * - Blacklist para direcciones sancionadas\r\n * - Límites de transacción diarios\r\n * - Pausabilidad para emergencias\r\n * - Auditoría completa con trazabilidad\r\n * - Recuperación de fondos en casos de fraude\r\n * \r\n * MODELO DE CIRCULACIÓN:\r\n * - Mint: Se acuñan tokens cuando se deposita CLP fiat verificado\r\n * - Burn: Se queman tokens cuando se retira CLP fiat\r\n * - 1 Token CLP = 1 Peso Chileno en reserva bancaria\r\n */\r\ninterface ICLPStablecoin is IERC20 {\r\n \r\n // === MINT & BURN ===\r\n \r\n /**\r\n * @notice Acuña nuevos tokens CLP respaldados por depósito fiat verificado.\r\n * @param to Destinatario de los tokens (debe estar en whitelist).\r\n * @param amount Cantidad de tokens a acuñar.\r\n * @param depositReference Hash de referencia del depósito bancario.\r\n * @param _secret Secreto post-cuántico para validación multisig.\r\n */\r\n function mint(\r\n address to,\r\n uint256 amount,\r\n bytes32 depositReference,\r\n string memory _secret\r\n ) external;\r\n \r\n /**\r\n * @notice Quema tokens CLP cuando se retira dinero fiat.\r\n * @param from Dirección desde donde quemar tokens.\r\n * @param amount Cantidad de tokens a quemar.\r\n * @param withdrawalReference Hash de referencia del retiro bancario.\r\n * @param _secret Secreto post-cuántico para validación multisig.\r\n */\r\n function burn(\r\n address from,\r\n uint256 amount,\r\n bytes32 withdrawalReference,\r\n string memory _secret\r\n ) external;\r\n \r\n // === COMPLIANCE ===\r\n \r\n /**\r\n * @notice Agrega o remueve una dirección de la whitelist (KYC).\r\n * @param account Dirección a modificar.\r\n * @param status true para agregar, false para remover.\r\n * @param _secret Secreto post-cuántico.\r\n */\r\n function setWhitelist(address account, bool status, string memory _secret) external;\r\n \r\n /**\r\n * @notice Agrega o remueve una dirección de la blacklist (sanciones).\r\n * @param account Dirección a modificar.\r\n * @param status true para blacklist, false para remover.\r\n * @param _secret Secreto post-cuántico.\r\n */\r\n function setBlacklist(address account, bool status, string memory _secret) external;\r\n \r\n /**\r\n * @notice Pausa todas las operaciones del token.\r\n * @param _secret Secreto post-cuántico.\r\n */\r\n function pause(string memory _secret) external;\r\n \r\n /**\r\n * @notice Reanuda las operaciones del token.\r\n * @param _secret Secreto post-cuántico.\r\n */\r\n function unpause(string memory _secret) external;\r\n \r\n /**\r\n * @notice Recupera fondos en caso de fraude comprobado.\r\n * @param from Dirección origen.\r\n * @param to Dirección destino (debe estar en whitelist).\r\n * @param amount Cantidad a recuperar.\r\n * @param reason Razón legal de la recuperación.\r\n * @param _secret Secreto post-cuántico.\r\n */\r\n function recoverFunds(\r\n address from,\r\n address to,\r\n uint256 amount,\r\n string memory reason,\r\n string memory _secret\r\n ) external;\r\n \r\n // === VIEW FUNCTIONS ===\r\n \r\n /**\r\n * @notice Devuelve la dirección del ReserveBank.\r\n * @return Dirección del banco de reserva.\r\n */\r\n function reserveBank() external view returns (address);\r\n \r\n /**\r\n * @notice Devuelve si una dirección está en la whitelist.\r\n * @param account Dirección a consultar.\r\n * @return true si está en whitelist.\r\n */\r\n function isWhitelisted(address account) external view returns (bool);\r\n \r\n /**\r\n * @notice Devuelve si una dirección está en la blacklist.\r\n * @param account Dirección a consultar.\r\n * @return true si está en blacklist.\r\n */\r\n function isBlacklisted(address account) external view returns (bool);\r\n \r\n /**\r\n * @notice Devuelve la cantidad total de tokens en circulación.\r\n * @return Total supply de tokens CLP.\r\n */\r\n function getCirculatingSupply() external view returns (uint256);\r\n \r\n /**\r\n * @notice Devuelve el volumen transferido hoy por una dirección.\r\n * @param account Dirección a consultar.\r\n * @return Volumen transferido en el día actual.\r\n */\r\n function getDailyTransferVolume(address account) external view returns (uint256);\r\n \r\n /**\r\n * @notice Devuelve el volumen de mint y burn del día actual.\r\n * @return minted Volumen acuñado hoy.\r\n * @return burned Volumen quemado hoy.\r\n */\r\n function getDailyMintBurnVolume() external view returns (uint256 minted, uint256 burned);\r\n}\r\n"
|
|
284
|
+
},
|
|
285
|
+
"project/contracts/economy/interfaces/IDEXRouter.sol": {
|
|
286
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\ninterface IDEXRouter {\r\n function swapExactTokensForTokens(\r\n uint256 amountIn,\r\n uint256 amountOutMin,\r\n address[] calldata path,\r\n address to,\r\n uint256 deadline\r\n ) external returns (uint256[] memory amounts);\r\n\r\n function addLiquidity(\r\n address tokenA,\r\n address tokenB,\r\n uint256 amountA, // Parámetro de entrada\r\n uint256 amountB, // Parámetro de entrada\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n address to,\r\n uint256 deadline\r\n ) external returns (uint256, uint256, uint256); \r\n}"
|
|
287
|
+
},
|
|
288
|
+
"project/contracts/economy/interfaces/IFeeSplitter.sol": {
|
|
289
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\n/**\r\n * @title IFeeSplitter\r\n * @notice Interfaz para que otros contratos (como VaultFactory) interactúen\r\n * con el FeeSplitter, exponiendo solo las funciones necesarias.\r\n */\r\ninterface IFeeSplitter {\r\n\r\n /**\r\n * @notice Otorga el rol de PRODUCT_SENDER a la dirección de un nuevo Vault.\r\n * @param _sender Dirección del contrato al que se le otorga el rol.\r\n */\r\n function grantProductSenderRole(address _sender) external;\r\n\r\n /**\r\n * @notice Función principal para la recolección y distribución de tarifas.\r\n * @param amount La cantidad de tokens a procesar.\r\n */\r\n function collectAndRouteFees(uint256 amount) external;\r\n}"
|
|
290
|
+
},
|
|
291
|
+
"project/contracts/economy/interfaces/IIncomeToken.sol": {
|
|
292
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\ninterface IIncomeToken is IERC20 {}\r\n"
|
|
293
|
+
},
|
|
294
|
+
"project/contracts/economy/interfaces/ILinealIdentity.sol": {
|
|
295
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\n/**\r\n * @title ILinealIdentity\r\n * @notice Interfaz mínima de LinealIdentity para consumo externo.\r\n * Expone únicamente las funciones de lectura necesarias para\r\n * verificar grado y titularidad de perfiles.\r\n */\r\ninterface ILinealIdentity {\r\n /// @notice Score global del token (0 – 10 000).\r\n function overallScore(uint256 tokenId) external view returns (uint256);\r\n\r\n /// @notice Devuelve el tokenId asociado a una wallet.\r\n function walletToToken(address wallet) external view returns (uint256);\r\n\r\n /// @notice Devuelve la wallet propietaria de un tokenId.\r\n function tokenToWallet(uint256 tokenId) external view returns (address);\r\n\r\n /// @notice Indica si una wallet tiene perfil activo.\r\n function hasProfile(address wallet) external view returns (bool);\r\n}\r\n"
|
|
296
|
+
},
|
|
297
|
+
"project/contracts/economy/interfaces/IMetricsAdapter.sol": {
|
|
298
|
+
"content": "\r\n// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\ninterface IMetricsAdapter {\r\n function getMetrics() external view returns (uint256 alpha, uint256 idp);\r\n}"
|
|
299
|
+
},
|
|
300
|
+
"project/contracts/economy/interfaces/IQorumsToken.sol": {
|
|
301
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n\r\n/**\r\n * @title IPopcornsToken\r\n * @notice Interfaz para el token POPCORNS con supply fijo de 1B.\r\n * \r\n * MODELO DE CIRCULACIÓN:\r\n * - Supply Total: 1,000,000,000 POPCORNS (FIJO, NUNCA CAMBIA)\r\n * - \"Liberar\" = Transferir desde RESERVA → Circulación\r\n * - \"Retornar\" = Transferir desde Circulación → RESERVA\r\n * \r\n * NO HAY MINT NI BURN REAL - Solo transferencias desde/hacia la reserva.\r\n */\r\ninterface IQorumsToken is IERC20 {\r\n /**\r\n * @notice Libera tokens desde la reserva hacia un destinatario.\r\n * @param to Destinatario de los tokens.\r\n * @param amount Cantidad de tokens a liberar.\r\n */\r\n function releaseFromReserve(address to, uint256 amount) external;\r\n \r\n /**\r\n * @notice Retorna tokens a la reserva (simula \"burn\" retirando de circulación).\r\n * @param amount Cantidad de tokens a retornar a la reserva.\r\n */\r\n function returnToReserve(uint256 amount) external;\r\n \r\n /**\r\n * @notice Devuelve la dirección de la wallet de reserva.\r\n * @return Dirección de la reserva.\r\n */\r\n function reserve() external view returns (address);\r\n \r\n /**\r\n * @notice Devuelve la cantidad de tokens en la reserva (fuera de circulación).\r\n * @return Balance de la wallet de reserva.\r\n */\r\n function getReserveBalance() external view returns (uint256);\r\n \r\n /**\r\n * @notice Devuelve la cantidad de tokens en circulación.\r\n * @return Total supply menos balance de reserva.\r\n */\r\n function getCirculatingSupply() external view returns (uint256);\r\n}"
|
|
302
|
+
},
|
|
303
|
+
"project/contracts/economy/Liquidity/LinealDex.sol": {
|
|
304
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\r\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\n\r\n/// Mock AMM de producto constante (x*y=k) con un solo par INCOME_TOKEN/TOKEN.\r\ncontract LinealDex is ReentrancyGuard {\r\n using SafeERC20 for IERC20;\r\n\r\n address public immutable TOKEN;\r\n address public immutable INCOME_TOKEN;\r\n\r\n uint256 public reserveToken;\r\n uint256 public reserveIncome;\r\n\r\n // TWAP (acumulador de precio estilo Uniswap V2)\r\n uint256 public priceCumulativeLast; // INCOME por TOKEN (1e18) * segundos\r\n uint256 public blockTimestampLast;\r\n\r\n uint256 public constant FEE_BPS = 30; // 0.3%, queda en el pool y sube k\r\n\r\n // Participación de liquidez (simplificada, sin ERC20 de LP)\r\n uint256 public totalShares;\r\n mapping(address => uint256) public sharesOf;\r\n\r\n event Swap(address indexed to, address tokenIn, uint256 amountIn, uint256 amountOut);\r\n event LiquidityAdded(address indexed to, uint256 amountIncome, uint256 amountToken, uint256 shares);\r\n event LiquidityRemoved(address indexed from, uint256 amountIncome, uint256 amountToken, uint256 shares);\r\n\r\n constructor(address _token, address _income) {\r\n TOKEN = _token;\r\n INCOME_TOKEN = _income;\r\n }\r\n\r\n // ───────────── Vistas ─────────────\r\n\r\n /// Cantidad de salida según reservas y fee (la fórmula de Uniswap V2).\r\n function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)\r\n public pure returns (uint256)\r\n {\r\n require(amountIn > 0, \"Mock: zero input\");\r\n require(reserveIn > 0 && reserveOut > 0, \"Mock: no liquidity\");\r\n uint256 inWithFee = amountIn * (10_000 - FEE_BPS);\r\n return (inWithFee * reserveOut) / (reserveIn * 10_000 + inWithFee);\r\n }\r\n\r\n /// Precio spot: unidades de TOKEN por 1 unidad de INCOME_TOKEN (escala 1e18).\r\n function spotPrice() external view returns (uint256) {\r\n require(reserveIncome > 0, \"Mock: no liquidity\");\r\n return (reserveToken * 1e18) / reserveIncome;\r\n }\r\n\r\n function getAmountsOut(uint256 amountIn, address[] calldata path)\r\n external view returns (uint256[] memory amounts)\r\n {\r\n require(path.length == 2, \"Mock: invalid path\");\r\n (uint256 rIn, uint256 rOut) = _reservesFor(path[0], path[1]);\r\n amounts = new uint256[](2);\r\n amounts[0] = amountIn;\r\n amounts[1] = getAmountOut(amountIn, rIn, rOut);\r\n }\r\n\r\n // ───────────── Swap ─────────────\r\n\r\n function swapExactTokensForTokens(\r\n uint256 amountIn,\r\n uint256 amountOutMin,\r\n address[] calldata path,\r\n address to,\r\n uint256 deadline\r\n ) external nonReentrant returns (uint256[] memory amounts) {\r\n require(block.timestamp <= deadline, \"Mock: expired\");\r\n require(path.length == 2, \"Mock: invalid path\");\r\n\r\n (uint256 rIn, uint256 rOut) = _reservesFor(path[0], path[1]);\r\n uint256 amountOut = getAmountOut(amountIn, rIn, rOut);\r\n require(amountOut >= amountOutMin, \"Mock: Swap failed (slippage)\");\r\n _update(); // <-- aquí también\r\n IERC20(path[0]).safeTransferFrom(msg.sender, address(this), amountIn);\r\n IERC20(path[1]).safeTransfer(to, amountOut);\r\n\r\n // Actualiza reservas: el precio se mueve aquí\r\n if (path[0] == INCOME_TOKEN) {\r\n reserveIncome += amountIn;\r\n reserveToken -= amountOut;\r\n } else {\r\n reserveToken += amountIn;\r\n reserveIncome -= amountOut;\r\n }\r\n\r\n amounts = new uint256[](2);\r\n amounts[0] = amountIn;\r\n amounts[1] = amountOut;\r\n emit Swap(to, path[0], amountIn, amountOut);\r\n }\r\n\r\n // ───────────── Liquidez ─────────────\r\n\r\n function addLiquidity(\r\n address tokenA,\r\n address tokenB,\r\n uint256 amountADesired,\r\n uint256 amountBDesired,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n address to,\r\n uint256 deadline\r\n ) external nonReentrant returns (uint256 amountA, uint256 amountB, uint256 liquidity) {\r\n require(block.timestamp <= deadline, \"Mock: expired\");\r\n require(\r\n (tokenA == INCOME_TOKEN && tokenB == TOKEN) || (tokenA == TOKEN && tokenB == INCOME_TOKEN),\r\n \"Mock: invalid pair\"\r\n );\r\n _update(); // <-- aquí también\r\n // Normaliza a (income, token)\r\n bool aIsIncome = tokenA == INCOME_TOKEN;\r\n uint256 dIncome = aIsIncome ? amountADesired : amountBDesired;\r\n uint256 dToken = aIsIncome ? amountBDesired : amountADesired;\r\n uint256 minIncome = aIsIncome ? amountAMin : amountBMin;\r\n uint256 minToken = aIsIncome ? amountBMin : amountAMin;\r\n\r\n uint256 aIncome;\r\n uint256 aToken;\r\n if (reserveIncome == 0 && reserveToken == 0) {\r\n // Primer depósito: fija el precio inicial\r\n (aIncome, aToken) = (dIncome, dToken);\r\n } else {\r\n // Respeta la proporción actual para no mover el precio\r\n uint256 optToken = (dIncome * reserveToken) / reserveIncome;\r\n if (optToken <= dToken) {\r\n require(optToken >= minToken, \"Mock: insufficient token amount\");\r\n (aIncome, aToken) = (dIncome, optToken);\r\n } else {\r\n uint256 optIncome = (dToken * reserveIncome) / reserveToken;\r\n require(optIncome <= dIncome && optIncome >= minIncome, \"Mock: insufficient income amount\");\r\n (aIncome, aToken) = (optIncome, dToken);\r\n }\r\n }\r\n\r\n IERC20(INCOME_TOKEN).safeTransferFrom(msg.sender, address(this), aIncome);\r\n IERC20(TOKEN).safeTransferFrom(msg.sender, address(this), aToken);\r\n\r\n if (totalShares == 0) {\r\n liquidity = _sqrt(aIncome * aToken);\r\n } else {\r\n uint256 s1 = (aIncome * totalShares) / reserveIncome;\r\n uint256 s2 = (aToken * totalShares) / reserveToken;\r\n liquidity = s1 < s2 ? s1 : s2;\r\n }\r\n require(liquidity > 0, \"Mock: zero liquidity\");\r\n\r\n reserveIncome += aIncome;\r\n reserveToken += aToken;\r\n totalShares += liquidity;\r\n sharesOf[to] += liquidity;\r\n\r\n (amountA, amountB) = aIsIncome ? (aIncome, aToken) : (aToken, aIncome);\r\n emit LiquidityAdded(to, aIncome, aToken, liquidity);\r\n }\r\n\r\n /// Extra para tests: retirar liquidez.\r\n function _reservesFor(address tokenIn, address tokenOut)\r\n internal view returns (uint256 rIn, uint256 rOut)\r\n {\r\n if (tokenIn == INCOME_TOKEN && tokenOut == TOKEN) return (reserveIncome, reserveToken);\r\n if (tokenIn == TOKEN && tokenOut == INCOME_TOKEN) return (reserveToken, reserveIncome);\r\n revert(\"Mock: Invalid path\");\r\n }\r\n\r\n function _sqrt(uint256 y) internal pure returns (uint256 z) {\r\n if (y > 3) {\r\n z = y;\r\n uint256 x = y / 2 + 1;\r\n while (x < z) { z = x; x = (y / x + x) / 2; }\r\n } else if (y != 0) {\r\n z = 1;\r\n }\r\n }\r\n\r\n /// Liquidez total del pool: reservas de cada token y participaciones emitidas.\r\n /// Valor total del pool expresado en INCOME_TOKEN.\r\n /// Al precio spot, ambos lados valen lo mismo, así que el total es 2 * reserveIncome.\r\n function getTotalLiquidity()\r\n external\r\n view\r\n returns (\r\n uint256 ingreso,\r\n uint256 token,\r\n uint256 participaciones\r\n )\r\n {\r\n return (reserveIncome, reserveToken, totalShares);\r\n }\r\n\r\n function getTotalLiquidityInIncome()\r\n external\r\n view\r\n returns (uint256)\r\n {\r\n return reserveIncome * 2;\r\n }\r\n function _update() private {\r\n uint256 dt = block.timestamp - blockTimestampLast;\r\n if (dt > 0 && reserveToken > 0 && reserveIncome > 0) {\r\n priceCumulativeLast += (reserveIncome * 1e18 / reserveToken) * dt;\r\n }\r\n blockTimestampLast = block.timestamp;\r\n }\r\n\r\n /// Acumulador al instante actual, sin necesidad de que alguien opere.\r\n function currentPriceCumulative() public view returns (uint256 cumulative, uint256 timestamp) {\r\n cumulative = priceCumulativeLast;\r\n uint256 dt = block.timestamp - blockTimestampLast;\r\n if (dt > 0 && reserveToken > 0 && reserveIncome > 0) {\r\n cumulative += (reserveIncome * 1e18 / reserveToken) * dt;\r\n }\r\n timestamp = block.timestamp;\r\n }\r\n}"
|
|
305
|
+
},
|
|
306
|
+
"project/contracts/economy/Liquidity/LinealLiquidity.sol": {
|
|
307
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/utils/Pausable.sol\";\r\nimport \"../../governance/LinealQorum.sol\";\r\nimport \"../token/LinealToken.sol\";\r\nimport \"../paymasters/LinealRouter.sol\";\r\nimport \"./LinealMilestones.sol\";\r\nimport \"./LinealDex.sol\";\r\nimport \"../../institution/LinealInstitution.sol\";\r\nimport \"./LinealSeed.sol\";\r\nimport {LinealBank} from \"../banks/LinealBank.sol\";\r\n\r\n/**\r\n * @title Lineal Liquidity by Lineal Qorum Protocol\r\n * @notice\r\n */\r\ncontract LinealLiquidity is LinealQorum, Pausable {\r\n\r\n LinealToken public immutable qorumToken;\r\n LinealBank public immutable institutionalBank;\r\n LinealInstitution public immutable institutionAddress;\r\n bool public isSeedLaunched = false;\r\n\r\n event UnlockExecuted(uint256 amount, uint256 alpha, uint256 idp);\r\n event BuybackAndBurn(uint256 incomeSpent, uint256 qorumsBurned);\r\n\r\n constructor(\r\n address _institutionAddress,\r\n address _bankAddress,\r\n address[] memory _machines,\r\n address[] memory _institutions,\r\n address[] memory _humans,\r\n uint256 _requiredMachines,\r\n uint256 _requiredInstitutions,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryQuorum) {\r\n institutionalBank = LinealBank(_bankAddress);\r\n institutionAddress = LinealInstitution(_institutionAddress);\r\n }\r\n\r\n // --- FUNCIONES DE SEGURIDAD Y ADMINISTRACIÓN ---\r\n\r\n function pause() public onlyQorum {\r\n bytes32 txHash = _computeActionHash(\"pause\", abi.encode(\"\"));\r\n if (!confirmServers(txHash, \"pause\")) return;\r\n _pause();\r\n }\r\n\r\n function unpause() public onlyQorum {\r\n bytes32 txHash = _computeActionHash(\"pause\", abi.encode(\"\"));\r\n if (!confirmServers(txHash, \"pause\")) return;\r\n _unpause();\r\n }\r\n\r\n function launchSeed(address _linealToken,\r\n address _linealSeed\r\n ) external onlyServers {\r\n require(isSeedLaunched == false, \"Launched\");\r\n bytes32 txHash = _computeActionHash(\"launchSeed\",\r\n abi.encode(\r\n _linealToken,\r\n _linealSeed\r\n ));\r\n if (!confirmServers(txHash, \"launchSeed\")) return;\r\n bytes32 institutionalId = institutionAddress.institutionAccountId();\r\n institutionalBank.deposit(institutionalId, _linealToken, 26_250_000 * 1e18);\r\n LinealToken(_linealToken).approve(_linealSeed, 24_000_000 * 1e18);\r\n LinealToken(_linealToken).transfer(_linealSeed, 24_000_000 * 1e18);\r\n isSeedLaunched = true;\r\n }\r\n\r\n function withdrawUnsoldTokens(address _linealSeed) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\"withdrawUnsoldTokens\", abi.encode(_linealSeed));\r\n if (!confirmServers(txHash, \"withdrawUnsoldTokens\")) return;\r\n LinealToken saleToken = LinealSeed(_linealSeed).saleToken();\r\n LinealSeed(_linealSeed).withdrawUnsoldTokens();\r\n uint256 balance = saleToken.balanceOf(address (this));\r\n bytes32 id = institutionAddress.institutionAccountId();\r\n institutionalBank.deposit(id, address(saleToken), balance);\r\n }\r\n // --- LÓGICA CENTRAL LCL/IDP (CALCULADORA) ---\r\n\r\n /**\r\n * @notice Implementa la lógica LCL/IDP del documento técnico.\r\n * @param _alpha Índice Alpha.\r\n * @param _idp Índice IDP.\r\n */\r\n function _calculateUnlock(uint256 _alpha, uint256 _idp)\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n // 1. Componente IDP (Porcentaje Base de Desbloqueo)\r\n uint256 idpBasePercent;\r\n\r\n // IDP >= 100 -> 75% | IDP > 66 -> 30% | else -> 0%\r\n if (_idp >= 100) {\r\n idpBasePercent = 75;\r\n } else if (_idp > 66) {\r\n idpBasePercent = 30;\r\n } else {\r\n idpBasePercent = 0;\r\n }\r\n\r\n // 2. Componente LCL (Factor de Ajuste: 0.8x o 1.0x)\r\n uint256 lclAdjustment;\r\n\r\n // Alpha < 100 (0.8x) | Alpha >= 100 (1.0x)\r\n if (_alpha < 93) {\r\n lclAdjustment = 50; // 0.8x\r\n } else if (_alpha >= 12) {\r\n lclAdjustment = 110; // 1.0x\r\n }\r\n\r\n // Cálculo Final: FinalUnlock = MaxUnlock * (IDP %) * (LCL Adjust)\r\n\r\n // Aplica el factor IDP (dividiendo por 100)\r\n uint256 rawUnlock = (idpBasePercent) / 100;\r\n\r\n // Aplica el factor LCL (dividiendo por 100)\r\n uint256 finalUnlock = (rawUnlock * lclAdjustment) / 100;\r\n\r\n return finalUnlock;\r\n }\r\n\r\n /**\r\n * @notice Ejecuta el cálculo, desbloquea y acuña tokens al destinatario.\r\n * @dev Requiere validación del LinealQorum Multisig\r\n */\r\n function unlockAndMint(address payable _recipient, uint256 _token, address _tokenAddress, address _milestoneAddress,\r\n address _linealSwap)\r\n public\r\n onlyServers\r\n whenNotPaused\r\n {\r\n bytes32 txHash = _computeActionHash(\"unlockAndMint\", abi.encode(_recipient, _token));\r\n if (!confirmServers(txHash, \"unlockAndMint\")) return;\r\n\r\n uint256 _alpha = _calculateAlpha(_linealSwap, _tokenAddress);\r\n uint256 _idp = LinealMilestones(_milestoneAddress).idp();\r\n\r\n // 2. Aplicar validación de emisión (Condición LCL)\r\n require(_alpha >= 93, \"LCL: Liquidez insuficiente (alpha < 0.93).\");\r\n // 3. Aplicar validación de desbloqueo (Condición IDP)\r\n require(_idp >= 66, \"IDP: Desempeno bajo (IDP < 0.66).\");\r\n\r\n // 4. Calcular el monto final de desbloqueo\r\n uint256 unlockAmount = _calculateUnlock(_alpha, _idp);\r\n\r\n // Asegurar que no se exceda el suministro restante\r\n\r\n // 5. Liberar tokens desde la reserva\r\n if (unlockAmount > 0) {\r\n LinealToken(_tokenAddress).mint(_recipient, unlockAmount);\r\n LinealRouter(_recipient).distributeRevenue(unlockAmount);\r\n }\r\n\r\n emit UnlockExecuted(unlockAmount, _alpha, _idp);\r\n }\r\n\r\n\r\n /**\r\n * @dev Compra tokens QORUMS y los quema (Buyback & Burn).\r\n */\r\n function _executeBuybackAndBurn(uint256 incomeAmount, address _tokenAddress, address dexRouter, address\r\n _incomeToken)\r\n internal {\r\n address[] memory path = new address[](2);\r\n path[0] = address(_incomeToken);\r\n path[1] = address(_tokenAddress);\r\n\r\n uint256[] memory amounts = LinealDex(dexRouter).swapExactTokensForTokens(\r\n incomeAmount,\r\n 1, // amountOutMin (tolerancia de deslizamiento baja para MVP — revisar antes de producción)\r\n path,\r\n address(this),\r\n block.timestamp\r\n );\r\n\r\n uint256 qorumsToReturn = amounts[amounts.length - 1];\r\n\r\n if (qorumsToReturn > 0) {\r\n LinealToken(_tokenAddress).burn(address(this), qorumsToReturn);\r\n emit BuybackAndBurn(incomeAmount, qorumsToReturn);\r\n }\r\n }\r\n\r\n\r\n function _calculateAlpha(\r\n address _linealSwap,\r\n address _linealToken\r\n ) internal view returns (uint256 _alpha) {\r\n (\r\n uint256 reserveIncome,\r\n uint256 reserveToken,\r\n uint256 totalShares\r\n ) = LinealDex(_linealSwap).getTotalLiquidity();\r\n\r\n (\r\n uint256 cumulative,\r\n uint256 timestamp\r\n ) = LinealDex(_linealSwap).currentPriceCumulative();\r\n\r\n uint256 circulatingSupply =\r\n LinealToken(_linealToken).getCirculatingSupply();\r\n\r\n // Evitar divisiones por cero.\r\n if (\r\n circulatingSupply == 0 ||\r\n cumulative == 0 ||\r\n reserveIncome == 0 ||\r\n reserveToken == 0\r\n ) {\r\n return 0;\r\n }\r\n\r\n // No calcular alpha con un acumulador TWAP sin un periodo\r\n // de observación definido.\r\n timestamp;\r\n\r\n uint256 spotPrice =\r\n (reserveIncome * 1e18) / reserveToken;\r\n\r\n _alpha = (reserveIncome * 1e18) / circulatingSupply;\r\n\r\n // Variables recuperadas para mantener explícita la interfaz.\r\n totalShares;\r\n cumulative;\r\n spotPrice;\r\n }\r\n}"
|
|
308
|
+
},
|
|
309
|
+
"project/contracts/economy/Liquidity/LinealMilestones.sol": {
|
|
310
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"../../governance/LinealQorum.sol\";\r\n\r\n/// Interfaz mínima de LinealCitizens (NFT soulbound, un perfil por wallet).\r\ninterface ILinealCitizens {\r\n function walletToToken(address wallet) external view returns (uint256); // 0 si no tiene perfil\r\n function tokenCounter() external view returns (uint256); // tokenIds secuenciales, nunca se reutilizan\r\n}\r\n\r\n/**\r\n * @title LinealMilestones - NeoQuor\r\n * @notice Hitos del proyecto validados por votación de los ciudadanos.\r\n * El IDP (índice de desempeño) es la suma de los pesos de los hitos aprobados (0-100).\r\n * Un ciudadano = un voto. El padrón se congela al abrir cada hito.\r\n */\r\ncontract LinealMilestones is LinealQorum {\r\n\r\n enum Status { None, Voting, Approved, Rejected, Cancelled }\r\n\r\n struct Milestone {\r\n uint8 weight; // puntos que aporta al IDP\r\n uint64 start;\r\n uint64 end;\r\n uint32 votesFor;\r\n uint32 votesAgainst;\r\n uint32 citizensAtStart; // padrón congelado (tokenCounter al abrir)\r\n Status status;\r\n }\r\n\r\n ILinealCitizens public immutable citizens;\r\n\r\n uint256 public constant MIN_PARTICIPATION_BPS = 2_000; // 20% del padrón\r\n uint256 public constant MIN_APPROVAL_BPS = 6_600; // 66% de los votos emitidos\r\n uint64 public constant MIN_DURATION = 3 days;\r\n uint64 public constant MAX_DURATION = 30 days;\r\n\r\n /// Peso comprometido: hitos en votación + aprobados. Nunca supera 100.\r\n uint256 public totalWeight;\r\n /// Peso de los hitos aprobados = IDP actual.\r\n uint256 public approvedWeight;\r\n\r\n Milestone[] public milestones;\r\n mapping(uint256 => mapping(address => bool)) public hasVoted;\r\n\r\n event MilestoneCreated(uint256 indexed id, uint8 weight, uint64 start, uint64 end, uint32 citizensAtStart);\r\n event Voted(uint256 indexed id, address indexed voter, bool support);\r\n event MilestoneFinalized(uint256 indexed id, Status status, uint32 votesFor, uint32 votesAgainst);\r\n event MilestoneCancelled(uint256 indexed id);\r\n\r\n constructor(\r\n address _citizens,\r\n address[] memory _machines,\r\n address[] memory _institutions,\r\n address[] memory _humans,\r\n uint256 _requiredMachines,\r\n uint256 _requiredInstitutions,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryQuorum\r\n ) {\r\n require(_citizens != address(0), \"Invalid citizens\");\r\n citizens = ILinealCitizens(_citizens);\r\n }\r\n\r\n // ───────────── Gobernanza (quórum) ─────────────\r\n\r\n /// @notice Abre la votación de un nuevo hito. Requiere confirmación del quórum.\r\n function createMilestone(uint8 weight, uint64 duration) external onlyServers {\r\n require(weight > 0, \"Weight = 0\");\r\n require(duration >= MIN_DURATION && duration <= MAX_DURATION, \"Bad duration\");\r\n require(totalWeight + weight <= 100, \"Weights > 100\");\r\n\r\n // El id del hito va en el hash: cada hito necesita su propia confirmación\r\n bytes32 txHash = _computeActionHash(\r\n \"createMilestone\",\r\n abi.encode(weight, duration, milestones.length)\r\n );\r\n if (!confirmServers(txHash, \"createMilestone\")) return;\r\n\r\n uint256 snapshot = citizens.tokenCounter();\r\n require(snapshot > 0, \"No citizens\");\r\n\r\n totalWeight += weight;\r\n\r\n uint256 id = milestones.length;\r\n uint64 start = uint64(block.timestamp);\r\n uint64 end = start + duration;\r\n\r\n milestones.push(Milestone({\r\n weight: weight,\r\n start: start,\r\n end: end,\r\n votesFor: 0,\r\n votesAgainst: 0,\r\n citizensAtStart: uint32(snapshot),\r\n status: Status.Voting\r\n }));\r\n\r\n emit MilestoneCreated(id, weight, start, end, uint32(snapshot));\r\n }\r\n\r\n /// @notice Freno de emergencia: el quórum puede cancelar una votación abierta.\r\n function cancelMilestone(uint256 id) external onlyQorum {\r\n Milestone storage m = milestones[id];\r\n require(m.status == Status.Voting, \"Not voting\");\r\n\r\n bytes32 txHash = _computeActionHash(\"cancelMilestone\", abi.encode(id));\r\n if (!confirmServers(txHash, \"cancelMilestone\")) return;\r\n\r\n m.status = Status.Cancelled;\r\n totalWeight -= m.weight; // libera el peso para volver a proponerlo\r\n\r\n emit MilestoneCancelled(id);\r\n }\r\n\r\n // ───────────── Votación (ciudadanos) ─────────────\r\n\r\n /// @notice Vota un hito. Elegible: perfil de LinealCitizens emitido antes de abrir el hito.\r\n function vote(uint256 id, bool support) external {\r\n Milestone storage m = milestones[id];\r\n require(m.status == Status.Voting && block.timestamp <= m.end, \"Not open\");\r\n\r\n uint256 tokenId = citizens.walletToToken(msg.sender);\r\n require(tokenId != 0 && tokenId <= m.citizensAtStart, \"Not eligible\");\r\n require(!hasVoted[id][msg.sender], \"Already voted\");\r\n\r\n hasVoted[id][msg.sender] = true;\r\n\r\n if (support) {\r\n m.votesFor++;\r\n } else {\r\n m.votesAgainst++;\r\n }\r\n\r\n emit Voted(id, msg.sender, support);\r\n }\r\n\r\n /// @notice Cierra la votación al vencer el plazo. Cualquiera puede llamarla.\r\n function finalize(uint256 id) external {\r\n Milestone storage m = milestones[id];\r\n require(m.status == Status.Voting && block.timestamp > m.end, \"Not ready\");\r\n\r\n uint256 votes = uint256(m.votesFor) + m.votesAgainst;\r\n bool participated = votes * 10_000 >= uint256(m.citizensAtStart) * MIN_PARTICIPATION_BPS;\r\n bool approved = votes > 0 && uint256(m.votesFor) * 10_000 >= votes * MIN_APPROVAL_BPS;\r\n\r\n if (participated && approved) {\r\n m.status = Status.Approved;\r\n approvedWeight += m.weight;\r\n } else {\r\n m.status = Status.Rejected;\r\n totalWeight -= m.weight; // libera el peso: el hito puede volver a proponerse\r\n }\r\n\r\n emit MilestoneFinalized(id, m.status, m.votesFor, m.votesAgainst);\r\n }\r\n\r\n // ───────────── Vistas ─────────────\r\n\r\n /// @notice Índice de desempeño: suma de pesos de hitos aprobados (0-100). O(1).\r\n function idp() external view returns (uint256) {\r\n return approvedWeight;\r\n }\r\n\r\n function milestonesCount() external view returns (uint256) {\r\n return milestones.length;\r\n }\r\n}\r\n"
|
|
311
|
+
},
|
|
312
|
+
"project/contracts/economy/Liquidity/LinealSeed.sol": {
|
|
313
|
+
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.24;\r\n\r\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\r\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\nimport {LinealToken} from \"../token/LinealToken.sol\";\r\n\r\n/**\r\n * @title VestedICOERC20\r\n * @notice ICO cuyo pago se realiza en un token ERC20 (ej. USDC/USDT) en vez de ETH.\r\n * Liberación de los tokens vendidos:\r\n * - 20% reclamable apenas se finaliza la venta (TGE)\r\n * - 80% reclamable tras un cliff de 6 meses desde el TGE\r\n * (70% pedido + 10% restante asumido; ajustar CLIFF_BPS si corresponde)\r\n * @dev El owner debe transferir al contrato los tokens a vender\r\n * (hardCap * rate) antes de iniciar la venta.\r\n * Los compradores deben hacer `approve` del paymentToken antes de `buy()`.\r\n */\r\ncontract LinealSeed is Ownable, ReentrancyGuard {\r\n using SafeERC20 for IERC20;\r\n\r\n // ---------------------------------------------------------------------\r\n // Parámetros de vesting (en basis points, 10_000 = 100%)\r\n // ---------------------------------------------------------------------\r\n uint256 public constant BPS = 10_000;\r\n uint256 public constant IMMEDIATE_BPS = 2_000; // 20%\r\n uint256 public constant CLIFF_BPS = 8_000; // 80% (70% + 10% restante)\r\n uint256 public constant CLIFF_DURATION = 180 days; // ~6 meses\r\n\r\n // ---------------------------------------------------------------------\r\n // Configuración de la venta\r\n // ---------------------------------------------------------------------\r\n LinealToken public saleToken;\r\n IERC20 public immutable paymentToken; // token con el que se paga (USDC, USDT, etc.)\r\n\r\n /// @dev unidades mínimas de saleToken por 1 unidad mínima de paymentToken.\r\n /// Ej: paymentToken USDC (6 dec), saleToken 18 dec, precio 0.05 USDC por token\r\n /// => 1 USDC compra 20 tokens => rate = 20 * 1e18 / 1e6 = 20e12.\r\n uint256 public immutable rate;\r\n\r\n uint256 public immutable softCap; // en unidades mínimas de paymentToken\r\n uint256 public immutable hardCap; // en unidades mínimas de paymentToken\r\n uint256 public immutable startTime;\r\n uint256 public immutable endTime;\r\n uint256 public immutable minContribution; // en unidades mínimas de paymentToken\r\n\r\n // ---------------------------------------------------------------------\r\n // Estado\r\n // ---------------------------------------------------------------------\r\n uint256 public totalRaised;\r\n address public linealLiquidity;\r\n uint256 public totalSold; // saleTokens vendidos (unidades mínimas)\r\n uint256 public totalClaimed; // saleTokens ya reclamados por compradores\r\n bool public finalized;\r\n bool public successful;\r\n uint256 public tgeTime;\r\n\r\n mapping(address => uint256) public contributed; // paymentToken aportado\r\n mapping(address => uint256) public purchased; // saleTokens comprados\r\n mapping(address => uint256) public claimed; // saleTokens ya reclamados\r\n\r\n // ---------------------------------------------------------------------\r\n // Eventos\r\n // ---------------------------------------------------------------------\r\n event Purchased(address indexed buyer, uint256 paymentAmount, uint256 tokenAmount);\r\n event Finalized(bool successful, uint256 totalRaised, uint256 tgeTime);\r\n event Claimed(address indexed buyer, uint256 amount);\r\n event SaleTokenSet(address indexed saleToken);\r\n event Refunded(address indexed buyer, uint256 paymentAmount);\r\n event FundsWithdrawn(address indexed to, uint256 amount);\r\n event UnsoldTokensWithdrawn(address indexed to, uint256 amount);\r\n\r\n // ---------------------------------------------------------------------\r\n // Errores\r\n // ---------------------------------------------------------------------\r\n error SaleNotActive();\r\n error SaleTokenNotSet();\r\n error SaleNotEnded();\r\n error AlreadyFinalized();\r\n error NotFinalized();\r\n error BelowMinContribution();\r\n error HardCapExceeded();\r\n error NothingToClaim();\r\n error NotRefundable();\r\n error NotSuccessful();\r\n error InvalidParams();\r\n error FeeOnTransferNotSupported();\r\n\r\n constructor(\r\n address _paymentToken,\r\n address _linealLiquidity,\r\n address _saleToken,\r\n uint256 _rate,\r\n uint256 _softCap,\r\n uint256 _hardCap,\r\n uint256 _startTime,\r\n uint256 _endTime,\r\n uint256 _minContribution\r\n ) Ownable(_linealLiquidity) {\r\n if (\r\n _paymentToken == address(0) ||\r\n _rate == 0 ||\r\n _hardCap == 0 ||\r\n _softCap > _hardCap ||\r\n _startTime < block.timestamp ||\r\n _endTime <= _startTime ||\r\n IMMEDIATE_BPS + CLIFF_BPS != BPS\r\n ) revert InvalidParams();\r\n\r\n paymentToken = IERC20(_paymentToken);\r\n saleToken = LinealToken(_saleToken);\r\n linealLiquidity = _linealLiquidity;\r\n rate = _rate;\r\n softCap = _softCap;\r\n hardCap = _hardCap;\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n minContribution = _minContribution;\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Compra\r\n // ---------------------------------------------------------------------\r\n /// @param paymentAmount Monto en unidades mínimas del paymentToken.\r\n /// Requiere `approve` previo a este contrato.\r\n function buy(uint256 paymentAmount) external nonReentrant {\r\n require(address(saleToken) != address(0), \"CLP: Reserve bank not set\");\r\n if (finalized || block.timestamp < startTime || block.timestamp > endTime) {\r\n revert SaleNotActive();\r\n }\r\n if (paymentAmount < minContribution || paymentAmount == 0) {\r\n revert BelowMinContribution();\r\n }\r\n if (totalRaised + paymentAmount > hardCap) revert HardCapExceeded();\r\n\r\n // Se verifica lo realmente recibido para rechazar tokens con comisión por transferencia\r\n uint256 balanceBefore = paymentToken.balanceOf(address(this));\r\n paymentToken.safeTransferFrom(msg.sender, address(this), paymentAmount);\r\n uint256 received = paymentToken.balanceOf(address(this)) - balanceBefore;\r\n if (received != paymentAmount) revert FeeOnTransferNotSupported();\r\n\r\n uint256 tokenAmount = paymentAmount * rate;\r\n\r\n totalRaised += paymentAmount;\r\n totalSold += tokenAmount;\r\n contributed[msg.sender] += paymentAmount;\r\n purchased[msg.sender] += tokenAmount;\r\n\r\n emit Purchased(msg.sender, paymentAmount, tokenAmount);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Finalización\r\n // ---------------------------------------------------------------------\r\n /// @notice Cualquiera puede finalizar al terminar el plazo o al llegar al hardCap.\r\n function finalize() external {\r\n if (finalized) revert AlreadyFinalized();\r\n if (block.timestamp <= endTime && totalRaised < hardCap) revert SaleNotEnded();\r\n\r\n finalized = true;\r\n\r\n if (totalRaised >= softCap) {\r\n successful = true;\r\n tgeTime = block.timestamp;\r\n }\r\n\r\n emit Finalized(successful, totalRaised, tgeTime);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Reclamo de tokens (vesting)\r\n // ---------------------------------------------------------------------\r\n /// @notice saleTokens que el comprador puede reclamar ahora mismo.\r\n function claimable(address buyer) public view returns (uint256) {\r\n if (!finalized || !successful) return 0;\r\n\r\n uint256 total = purchased[buyer];\r\n uint256 unlocked = (total * IMMEDIATE_BPS) / BPS;\r\n\r\n if (block.timestamp >= tgeTime + CLIFF_DURATION) {\r\n unlocked = total; // 20% + 80%\r\n }\r\n\r\n return unlocked - claimed[buyer];\r\n }\r\n\r\n function claim() external nonReentrant {\r\n uint256 amount = claimable(msg.sender);\r\n if (amount == 0) revert NothingToClaim();\r\n\r\n claimed[msg.sender] += amount;\r\n totalClaimed += amount;\r\n LinealToken(address(saleToken)).transfer(msg.sender, amount);\r\n\r\n\r\n emit Claimed(msg.sender, amount);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Reembolso si no se alcanzó el softCap\r\n // ---------------------------------------------------------------------\r\n function refund() external nonReentrant {\r\n if (!finalized || successful) revert NotRefundable();\r\n\r\n uint256 amount = contributed[msg.sender];\r\n if (amount == 0) revert NothingToClaim();\r\n\r\n contributed[msg.sender] = 0;\r\n purchased[msg.sender] = 0;\r\n\r\n LinealToken(address(saleToken)).transfer(msg.sender, amount);\r\n\r\n emit Refunded(msg.sender, amount);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Administración\r\n // ---------------------------------------------------------------------\r\n /// @notice Retira el paymentToken recaudado (solo si la venta fue exitosa).\r\n function withdrawFunds() external onlyOwner {\r\n if (!finalized) revert NotFinalized();\r\n if (!successful) revert NotSuccessful();\r\n\r\n uint256 balance = paymentToken.balanceOf(address(this));\r\n paymentToken.transfer(linealLiquidity, balance);\r\n emit FundsWithdrawn(linealLiquidity, balance);\r\n }\r\n\r\n /// @notice Retira saleTokens no vendidos (venta exitosa) o todos (venta fallida).\r\n /// Nunca toca los tokens pendientes de reclamo de los compradores.\r\n function withdrawUnsoldTokens() external onlyOwner {\r\n if (!finalized) revert NotFinalized();\r\n\r\n uint256 balance = LinealToken(address(saleToken)).balanceOf(address(this));\r\n uint256 reserved = successful ? (totalSold - totalClaimed) : 0;\r\n uint256 free = balance > reserved ? balance - reserved : 0;\r\n\r\n LinealToken(address(saleToken)).transfer(linealLiquidity, free);\r\n emit UnsoldTokensWithdrawn(linealLiquidity, free);\r\n }\r\n}\r\n"
|
|
314
|
+
},
|
|
315
|
+
"project/contracts/economy/paymasters/LinealPaymaster.sol": {
|
|
316
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable reason-string */\n/* solhint-disable no-inline-assembly */\n\nimport \"../../core/BasePaymaster.sol\";\nimport \"../../core/UserOperationLib.sol\";\nimport \"../../core/Helpers.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\n/**\n * A sample paymaster that uses external service to decide whether to pay for the UserOp.\n * The paymaster trusts an external signer to sign the transaction.\n * The calling user must pass the UserOp to that external signer first, which performs\n * whatever off-chain verification before signing the UserOp.\n * Note that this signature is NOT a replacement for the account-specific signature:\n * - the paymaster checks a signature to agree to PAY for GAS.\n * - the account checks a signature to prove identity and account ownership.\n */\ncontract LinealPaymaster is BasePaymaster {\n\n using UserOperationLib for PackedUserOperation;\n\n address public immutable verifyingSigner;\n\n uint256 private constant VALID_TIMESTAMP_OFFSET = PAYMASTER_DATA_OFFSET;\n\n uint256 private constant SIGNATURE_OFFSET = VALID_TIMESTAMP_OFFSET + 64;\n\n constructor(IEntryPoint _entryPoint, address _verifyingSigner) BasePaymaster(_entryPoint) {\n verifyingSigner = _verifyingSigner;\n }\n\n /**\n * return the hash we're going to sign off-chain (and validate on-chain)\n * this method is called by the off-chain service, to sign the request.\n * it is called on-chain from the validatePaymasterUserOp, to validate the signature.\n * note that this signature covers all fields of the UserOperation, except the \"paymasterAndData\",\n * which will carry the signature itself.\n */\n function getHash(PackedUserOperation calldata userOp, uint48 validUntil, uint48 validAfter)\n public view returns (bytes32) {\n //can't use userOp.hash(), since it contains also the paymasterAndData itself.\n address sender = userOp.getSender();\n return\n keccak256(\n abi.encode(\n sender,\n userOp.nonce,\n keccak256(userOp.initCode),\n keccak256(userOp.callData),\n userOp.accountGasLimits,\n uint256(bytes32(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_DATA_OFFSET])),\n userOp.preVerificationGas,\n userOp.gasFees,\n block.chainid,\n address(this),\n validUntil,\n validAfter\n )\n );\n }\n\n /**\n * verify our external signer signed this request.\n * the \"paymasterAndData\" is expected to be the paymaster and a signature over the entire request params\n * paymasterAndData[:20] : address(this)\n * paymasterAndData[20:84] : abi.encode(validUntil, validAfter)\n * paymasterAndData[84:] : signature\n */\n function _validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 /*userOpHash*/, uint256 requiredPreFund)\n internal view override returns (bytes memory context, uint256 validationData) {\n (requiredPreFund);\n\n (uint48 validUntil, uint48 validAfter, bytes calldata signature) = parsePaymasterAndData(userOp.paymasterAndData);\n //ECDSA library supports both 64 and 65-byte long signatures.\n // we only \"require\" it here so that the revert reason on invalid signature will be of \"VerifyingPaymaster\", and not \"ECDSA\"\n require(signature.length == 64 || signature.length == 65, \"VerifyingPaymaster: invalid signature length in paymasterAndData\");\n bytes32 hash = MessageHashUtils.toEthSignedMessageHash(getHash(userOp, validUntil, validAfter));\n\n //don't revert on signature failure: return SIG_VALIDATION_FAILED\n if (verifyingSigner != ECDSA.recover(hash, signature)) {\n return (\"\", _packValidationData(true, validUntil, validAfter));\n }\n\n //no need for other on-chain validation: entire UserOp should have been checked\n // by the external service prior to signing it.\n return (\"\", _packValidationData(false, validUntil, validAfter));\n }\n\n function parsePaymasterAndData(bytes calldata paymasterAndData) public pure returns (uint48 validUntil, uint48 validAfter, bytes calldata signature) {\n (validUntil, validAfter) = abi.decode(paymasterAndData[VALID_TIMESTAMP_OFFSET :], (uint48, uint48));\n signature = paymasterAndData[SIGNATURE_OFFSET :];\n }\n}\n"
|
|
317
|
+
},
|
|
318
|
+
"project/contracts/economy/paymasters/LinealRouter.sol": {
|
|
319
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/utils/Pausable.sol\";\r\nimport \"../../governance/LinealQorum.sol\";\r\nimport \"../../economy/interfaces/IQorumsToken.sol\";\r\nimport \"../../economy/interfaces/IIncomeToken.sol\";\r\n\r\n/**\r\n * @title PaymentRouter\r\n * @notice Splitter de ingresos genérico y estándar (no ligado a roles fijos).\r\n * El multisig define post-despliegue N destinatarios, cada uno con:\r\n * - un porcentaje (basis points, base 10000)\r\n * - un tipo de acción: TRANSFER (transferencia directa) o BUYBACK_BURN (swap + burn)\r\n * Este contrato debe tener el BURNER_ROLE en QorumsToken.\r\n */\r\ncontract LinealRouter is LinealQorum, Pausable {\r\n\r\n IQorumsToken public immutable QORUMS;\r\n IIncomeToken public immutable INCOME_TOKEN; // Ej. USDC\r\n\r\n address public linealLiquidity; // Contrato autorizado para enviar fondos\r\n\r\n uint256 public constant BPS_DENOMINATOR = 10000;\r\n uint256 public constant MAX_RECIPIENTS = 20; // límite de seguridad para evitar gas-DoS en el loop\r\n\r\n struct Recipient {\r\n address account; // ignorado cuando distType == BUYBACK_BURN\r\n uint256 bps;\r\n string label; // etiqueta legible, informativa (ej. \"Founder\", \"Rewards Pool\", \"Protocol Burn\")\r\n }\r\n\r\n // Tokenomics vigente, 100% configurable por el multisig vía setDistribution()\r\n Recipient[] public recipients;\r\n\r\n event RevenueDistributed(uint256 incomeAmount, uint256 recipientsCount);\r\n event RecipientPaid(uint256 indexed index, address indexed account, uint256 amount);\r\n event DistributionUpdated(uint256 recipientsCount);\r\n\r\n constructor(\r\n address[] memory _machines,\r\n address[] memory _institutions,\r\n address[] memory _humans,\r\n uint256 _requiredMachines,\r\n uint256 _requiredInstitutions,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum,\r\n address _qorumsTokenAddress,\r\n address _incomeTokenAddress\r\n ) LinealQorum(_machines, _requiredMachines, _institutions, _requiredInstitutions, _humans, _requiredHumans, _recoveryQuorum) {\r\n QORUMS = IQorumsToken(_qorumsTokenAddress);\r\n INCOME_TOKEN = IIncomeToken(_incomeTokenAddress);\r\n }\r\n\r\n // --- SEGURIDAD Y ADMINISTRACIÓN MULTISIG ---\r\n\r\n function setFeeSplitter(address _linealLiquidity) public onlyServers {\r\n bytes32 txHash = keccak256(abi.encodePacked(\"setFeeSplitter\", _linealLiquidity,\r\n actionNonce[\"setFeeSplitter\"]));\r\n if (confirmServers(txHash, \"setFeeSplitter\")) {\r\n linealLiquidity = _linealLiquidity;\r\n }\r\n }\r\n\r\n /**\r\n * @notice Redefine por completo el tokenomics de distribución. Estándar y genérico:\r\n * el multisig puede definir cualquier número de destinatarios (hasta MAX_RECIPIENTS),\r\n * cada uno con su propio porcentaje y tipo de acción.\r\n * @dev Los `bps` deben sumar exactamente 10000. Para entradas TRANSFER, `accounts[i]`\r\n * es la dirección destino. Para BUYBACK_BURN, `accounts[i]` se ignora (pasar address(0)).\r\n * Requiere confirmServeración multisig, igual que el resto de funciones administrativas.\r\n */\r\n function setDistribution(\r\n address[] calldata accounts,\r\n uint256[] calldata bpsValues,\r\n string[] calldata labels\r\n ) public onlyServers {\r\n uint256 len = accounts.length;\r\n require(len > 0 && len <= MAX_RECIPIENTS, \"PayMaster: invalid recipients length\");\r\n require(\r\n bpsValues.length == len && labels.length == len,\r\n \"PayMaster: array length mismatch\"\r\n );\r\n\r\n uint256 totalBps;\r\n for (uint256 i = 0; i < len; i++) {\r\n totalBps += bpsValues[i];\r\n }\r\n require(totalBps == BPS_DENOMINATOR, \"PayMaster: bps must sum to 10000\");\r\n\r\n bytes32 txHash = keccak256(\r\n abi.encodePacked(\r\n \"setDistribution\",\r\n keccak256(abi.encode(accounts, bpsValues)),\r\n actionNonce[\"setDistribution\"]\r\n )\r\n );\r\n if (confirmServers(txHash, \"setDistribution\")) {\r\n delete recipients;\r\n for (uint256 i = 0; i < len; i++) {\r\n recipients.push(Recipient(accounts[i], bpsValues[i], labels[i]));\r\n }\r\n emit DistributionUpdated(len);\r\n }\r\n }\r\n\r\n function pause() public onlyServers {\r\n bytes32 txHash = keccak256(abi.encodePacked(\"pause\", actionNonce[\"pause\"]));\r\n if (confirmServers(txHash, \"pause\")) {\r\n _pause();\r\n }\r\n }\r\n\r\n function unpause() public onlyServers {\r\n bytes32 txHash = keccak256(abi.encodePacked(\"unpause\", actionNonce[\"unpause\"]));\r\n if (confirmServers(txHash, \"unpause\")) {\r\n _unpause();\r\n }\r\n }\r\n\r\n // --- LECTURA DE TOKENOMICS ---\r\n\r\n function getRecipientsCount() external view returns (uint256) {\r\n return recipients.length;\r\n }\r\n\r\n function getAllRecipients() external view returns (Recipient[] memory) {\r\n return recipients;\r\n }\r\n\r\n // --- LÓGICA CENTRAL DE DISTRIBUCIÓN ---\r\n\r\n /**\r\n * @notice Recibe una cantidad de tokens de ingreso y la reparte según el array\r\n * `recipients` vigente, 100% definido por el multisig vía setDistribution().\r\n * @dev Asume que los tokens de ingreso ya han sido transferidos al PaymentRouter,\r\n * usualmente desde el FeeSplitter o directamente por el Admin.\r\n */\r\n function distributeRevenue(uint256 incomeAmount) public whenNotPaused {\r\n require(msg.sender == linealLiquidity, \"PaymentRouter: Only authorized FeeSplitter\");\r\n require(INCOME_TOKEN.balanceOf(address(this)) >= incomeAmount, \"Insufficient income balance\");\r\n\r\n uint256 len = recipients.length;\r\n for (uint256 i = 0; i < len; i++) {\r\n Recipient memory r = recipients[i];\r\n uint256 amount = (incomeAmount * r.bps) / BPS_DENOMINATOR;\r\n if (amount == 0) continue;\r\n INCOME_TOKEN.transfer(r.account, amount);\r\n emit RecipientPaid(i, r.account, amount);\r\n }\r\n\r\n emit RevenueDistributed(incomeAmount, len);\r\n }\r\n\r\n receive() external payable {}\r\n}\r\n"
|
|
320
|
+
},
|
|
321
|
+
"project/contracts/economy/token/LinealToken.sol": {
|
|
322
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\r\nimport \"@openzeppelin/contracts/utils/Pausable.sol\";\r\nimport \"../../governance/LinealQorum.sol\";\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\n\r\n/**\r\n * @title LinealToken - NeoQuor\r\n * @notice Stablecoin regulada respaldada 1:1 moneda FIAT\r\n *\r\n * CUMPLIMIENTO REGULATORIO Y COMPLIANCE:\r\n * - Gobernanza MultiSig de 3 capas integrada con LinealQorum\r\n * - Sistema KYC/AML mediante Whitelist y Blacklist\r\n * - Pausabilidad de emergencia\r\n * - Límites de transacción diaria para transferencia, mint y burn\r\n * - Recuperación de fondos por fraude comprobado u orden judicial\r\n * - Trazabilidad y auditoría on-chain (MintRecord / BurnRecord)\r\n */\r\ncontract LinealToken is ERC20, LinealQorum, Pausable {\r\n address public reserveBank;\r\n address public linealLiquidityAddress;\r\n\r\n bool public seedLaunched;\r\n\r\n // === COMPLIANCE & REGULATORY ===\r\n\r\n mapping(address => bool) public isWhitelisted;\r\n mapping(address => bool) public isBlacklisted;\r\n\r\n uint256 public dailyTransferLimit = 10_000_000 * 10**18; // 10M CLP\r\n uint256 public dailyMintLimit = 100_000_000 * 10**18; // 100M CLP\r\n uint256 public dailyBurnLimit = 100_000_000 * 10**18; // 100M CLP\r\n\r\n struct DailyVolume {\r\n uint256 date;\r\n uint256 minted;\r\n uint256 burned;\r\n mapping(address => uint256) transferred;\r\n }\r\n\r\n mapping(uint256 => DailyVolume) private _dailyVolumes;\r\n\r\n // === AUDIT TRAIL ===\r\n\r\n struct MintRecord {\r\n address to;\r\n uint256 amount;\r\n uint256 timestamp;\r\n address authorizedBy;\r\n }\r\n\r\n struct BurnRecord {\r\n address from;\r\n uint256 amount;\r\n uint256 timestamp;\r\n address authorizedBy;\r\n }\r\n\r\n MintRecord[] public mintHistory;\r\n BurnRecord[] public burnHistory;\r\n\r\n // === EVENTS ===\r\n\r\n event Minted(address indexed to, uint256 amount, address indexed authorizedBy, uint256 timestamp);\r\n event Burned(address indexed from, uint256 amount,address indexed authorizedBy, uint256 timestamp);\r\n event ReserveBankSet(address indexed newReserveBank);\r\n event AddressWhitelisted(address indexed account, bool status);\r\n event AddressBlacklisted(address indexed account, bool status);\r\n event DailyLimitsUpdated(uint256 transferLimit, uint256 mintLimit, uint256 burnLimit);\r\n event FundsRecovered(address indexed from, address indexed to, uint256 amount, string reason);\r\n\r\n\r\n constructor(\r\n string memory name,\r\n string memory symbol,\r\n address[] memory _machines,\r\n address[] memory _institutions,\r\n address[] memory _humans,\r\n uint256 _requiredMachines,\r\n uint256 _requiredInstitutions,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(_machines, _requiredMachines, _institutions, _requiredInstitutions, _humans, _requiredHumans, _recoveryQuorum)\r\n ERC20(name, symbol) {\r\n\r\n }\r\n\r\n // === MODIFIERS ===\r\n\r\n modifier onlyWhitelisted(address account) {\r\n require(isWhitelisted[account], \"CLP: Address not whitelisted (KYC required)\");\r\n _;\r\n }\r\n\r\n modifier notBlacklisted(address account) {\r\n require(!isBlacklisted[account], \"CLP: Address is blacklisted\");\r\n _;\r\n }\r\n\r\n // === EMERGENCY CONTROLS ===\r\n\r\n function pause() external onlyQorum {\r\n _pause();\r\n }\r\n\r\n function unpause() external onlyQorum {\r\n _unpause();\r\n }\r\n\r\n // === COMPLIANCE MANAGEMENT ===\r\n\r\n function setWhitelist(address account, bool status) external onlyServers {\r\n\r\n isWhitelisted[account] = status;\r\n emit AddressWhitelisted(account, status);\r\n }\r\n\r\n function setBlacklist(address account, bool status) external onlyServers {\r\n\r\n isBlacklisted[account] = status;\r\n emit AddressBlacklisted(account, status);\r\n }\r\n\r\n function launchSeed(address _linealLiquidity) external onlyServers {\r\n isWhitelisted[_linealLiquidity] = true;\r\n linealLiquidityAddress = _linealLiquidity;\r\n _mint(_linealLiquidity, 50_250_000 * 1e18);\r\n emit AddressWhitelisted(_linealLiquidity, true);\r\n }\r\n\r\n function setDailyLimits(\r\n uint256 _transferLimit,\r\n uint256 _mintLimit,\r\n uint256 _burnLimit\r\n ) external onlyServers {\r\n\r\n dailyTransferLimit = _transferLimit;\r\n dailyMintLimit = _mintLimit;\r\n dailyBurnLimit = _burnLimit;\r\n emit DailyLimitsUpdated(_transferLimit, _mintLimit, _burnLimit);\r\n }\r\n\r\n // === RESERVE BANK MANAGEMENT ===\r\n\r\n function setReserveBank(address _reserveBank) external onlyServers {\r\n require(reserveBank == address(0), \"CLP: Reserve bank already set\");\r\n require(_reserveBank != address(0), \"CLP: Invalid reserve bank address\");\r\n\r\n\r\n reserveBank = _reserveBank;\r\n isWhitelisted[_reserveBank] = true;\r\n emit ReserveBankSet(_reserveBank);\r\n }\r\n\r\n // === MINT & BURN (BACKED BY FIAT) ===\r\n\r\n function mint(\r\n address to,\r\n uint256 amount\r\n ) external whenNotPaused onlyWhitelisted(to) notBlacklisted(to) {\r\n require(reserveBank != address(0), \"CLP: Bank not linked\");\r\n require(msg.sender == linealLiquidityAddress, \"CLP: Sender is not Authorized Bank\");\r\n require(to != address(0), \"CLP: Invalid recipient\");\r\n require(amount > 0, \"CLP: Amount must be > 0\");\r\n\r\n uint256 today = block.timestamp / 1 days;\r\n DailyVolume storage volume = _dailyVolumes[today];\r\n if (volume.date != today) {\r\n volume.date = today;\r\n volume.minted = 0;\r\n }\r\n require(volume.minted + amount <= dailyMintLimit, \"CLP: Daily mint limit exceeded\");\r\n\r\n volume.minted += amount;\r\n\r\n mintHistory.push(MintRecord({\r\n to: to,\r\n amount: amount,\r\n timestamp: block.timestamp,\r\n authorizedBy: msg.sender\r\n }));\r\n\r\n _mint(to, amount);\r\n emit Minted(to, amount, msg.sender, block.timestamp);\r\n }\r\n\r\n function burn(\r\n address from,\r\n uint256 amount\r\n ) external whenNotPaused notBlacklisted(from) {\r\n require(reserveBank != address(0), \"CLP: Reserve bank not set\");\r\n require(msg.sender == linealLiquidityAddress, \"CLP: Sender is not Authorized Bank\");\r\n require(from != address(0), \"CLP: Invalid address\");\r\n require(amount > 0, \"CLP: Amount must be > 0\");\r\n require(balanceOf(from) >= amount, \"CLP: Insufficient balance\");\r\n\r\n uint256 today = block.timestamp / 1 days;\r\n DailyVolume storage volume = _dailyVolumes[today];\r\n if (volume.date != today) {\r\n volume.date = today;\r\n volume.burned = 0;\r\n }\r\n require(volume.burned + amount <= dailyBurnLimit, \"CLP: Daily burn limit exceeded\");\r\n\r\n volume.burned += amount;\r\n\r\n burnHistory.push(BurnRecord({\r\n from: from,\r\n amount: amount,\r\n timestamp: block.timestamp,\r\n authorizedBy: msg.sender\r\n }));\r\n\r\n _burn(from, amount);\r\n emit Burned(from, amount, msg.sender, block.timestamp);\r\n }\r\n\r\n // === FRAUD RECOVERY ===\r\n\r\n function recoverFunds(\r\n address from,\r\n address to,\r\n uint256 amount,\r\n string memory reason\r\n ) external whenNotPaused {\r\n require(from != address(0) && to != address(0), \"CLP: Invalid addresses\");\r\n require(msg.sender == reserveBank, \"CLP: Sender is not Authorized Bank\");\r\n require(amount > 0 && balanceOf(from) >= amount, \"CLP: Invalid amount\");\r\n require(isWhitelisted[to], \"CLP: Recipient must be whitelisted\");\r\n _transfer(from, to, amount);\r\n emit FundsRecovered(from, to, amount, reason);\r\n }\r\n\r\n // === OVERRIDES FOR COMPLIANCE ===\r\n\r\n function transfer(address to, uint256 amount)\r\n public\r\n override\r\n whenNotPaused\r\n onlyWhitelisted(msg.sender)\r\n onlyWhitelisted(to)\r\n notBlacklisted(msg.sender)\r\n notBlacklisted(to)\r\n returns (bool)\r\n {\r\n _checkAndRecordDailyTransfer(msg.sender, amount);\r\n return super.transfer(to, amount);\r\n }\r\n\r\n function transferFrom(address from, address to, uint256 amount)\r\n public\r\n override\r\n whenNotPaused\r\n onlyWhitelisted(from)\r\n onlyWhitelisted(to)\r\n notBlacklisted(from)\r\n notBlacklisted(to)\r\n returns (bool)\r\n {\r\n _checkAndRecordDailyTransfer(from, amount);\r\n return super.transferFrom(from, to, amount);\r\n }\r\n\r\n function _checkAndRecordDailyTransfer(address account, uint256 amount) internal {\r\n uint256 today = block.timestamp / 1 days;\r\n DailyVolume storage volume = _dailyVolumes[today];\r\n\r\n if (volume.date != today) {\r\n volume.date = today;\r\n }\r\n\r\n require(\r\n volume.transferred[account] + amount <= dailyTransferLimit,\r\n \"CLP: Daily transfer limit exceeded\"\r\n );\r\n\r\n volume.transferred[account] += amount;\r\n }\r\n\r\n // === VIEW FUNCTIONS ===\r\n\r\n function getCirculatingSupply() external view returns (uint256) {\r\n return totalSupply();\r\n }\r\n\r\n function getMintHistoryLength() external view returns (uint256) {\r\n return mintHistory.length;\r\n }\r\n\r\n function getBurnHistoryLength() external view returns (uint256) {\r\n return burnHistory.length;\r\n }\r\n\r\n function getDailyTransferVolume(address account) external view returns (uint256) {\r\n uint256 today = block.timestamp / 1 days;\r\n DailyVolume storage volume = _dailyVolumes[today];\r\n return volume.date == today ? volume.transferred[account] : 0;\r\n }\r\n\r\n function getDailyMintBurnVolume() external view returns (uint256 minted, uint256 burned) {\r\n uint256 today = block.timestamp / 1 days;\r\n DailyVolume storage volume = _dailyVolumes[today];\r\n if (volume.date == today) {\r\n return (volume.minted, volume.burned);\r\n }\r\n return (0, 0);\r\n }\r\n}"
|
|
323
|
+
},
|
|
324
|
+
"project/contracts/governance/LinealQorum.sol": {
|
|
325
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nabstract contract LinealQorum {\r\n // 1 = Machine, 2 = Institution, 3 = Human\r\n mapping(address => uint8) public signerType;\r\n\r\n address[] public machines;\r\n address[] public institutions;\r\n address[] public humans;\r\n\r\n uint256 public requiredMachines;\r\n uint256 public requiredInstitutions;\r\n uint256 public requiredHumans;\r\n\r\n address public guardian;\r\n address public identityContract;\r\n\r\n mapping(bytes32 => mapping(address => bool)) public isConfirmed;\r\n mapping(bytes32 => uint256) public confirmationCount;\r\n mapping(bytes32 => bool) public isExecuted;\r\n\r\n mapping(bytes32 => uint256) public machineConfirmations;\r\n mapping(bytes32 => uint256) public institutionConfirmations;\r\n mapping(bytes32 => uint256) public humanConfirmations;\r\n\r\n mapping(string => uint256) public actionNonce;\r\n\r\n uint256 public recoveryQuorum;\r\n uint256 public constant RECOVERY_DELAY = 2 hours;\r\n\r\n struct RecoveryProposal {\r\n address[] newMachines;\r\n address[] newInstitutions;\r\n address[] newHumans;\r\n uint256 newRequiredMachines;\r\n uint256 newRequiredInstitutions;\r\n uint256 newRequiredHumans;\r\n uint256 proposedAt;\r\n uint256 confirmations;\r\n bool executed;\r\n mapping(address => bool) confirmedBy;\r\n }\r\n\r\n mapping(bytes32 => RecoveryProposal) private _recoveryProposals;\r\n\r\n event ActionProposed(bytes32 indexed txHash, address indexed proposer, string actionType);\r\n event ActionConfirmed(bytes32 indexed txHash, address indexed signer);\r\n event ActionExecuted(bytes32 indexed txHash);\r\n event GuardianUpdated(address indexed newGuardian);\r\n event QuantumCommitmentUpdated(address indexed signer, bytes32 commitment);\r\n event RecoveryProposed(bytes32 indexed recoveryHash, address indexed proposer);\r\n event RecoveryConfirmed(bytes32 indexed recoveryHash, address indexed confirmer, uint256 confirmations);\r\n event RecoveryExecuted(bytes32 indexed recoveryHash);\r\n\r\n modifier onlyQorum() {\r\n require(signerType[msg.sender] != 0, \"LQ: not signer\");\r\n _;\r\n }\r\n\r\n modifier onlyServers() {\r\n uint8 sType = signerType[msg.sender];\r\n require(sType == 1 || sType == 2, \"LQ: not a server layer\");\r\n _;\r\n }\r\n\r\n modifier onlyGuardian() {\r\n require(msg.sender == guardian, \"LQ: only guardian\");\r\n _;\r\n }\r\n\r\n constructor(\r\n address[] memory _qorumServers,\r\n uint256 _requiredQorumServers,\r\n address[] memory _institutionsServers,\r\n uint256 _requiredInstitutionsServers,\r\n address[] memory _operators,\r\n uint256 _requiredOperators,\r\n uint256 _recoveryQuorum\r\n ) {\r\n require(_requiredQorumServers > 0 && _qorumServers.length >= _requiredQorumServers, \"LQ: invalid machines req\");\r\n require(_requiredInstitutionsServers > 0 && _institutionsServers.length >= _requiredInstitutionsServers, \"LQ: invalid inst req\");\r\n require(_recoveryQuorum > 0, \"LQ: invalid recovery quorum\");\r\n\r\n requiredMachines = _requiredQorumServers;\r\n requiredInstitutions = _requiredInstitutionsServers;\r\n recoveryQuorum = _recoveryQuorum;\r\n\r\n if (_operators.length > 0) {\r\n require(_requiredOperators > 0 && _operators.length >= _requiredOperators, \"LQ: invalid humans req\");\r\n requiredHumans = _requiredOperators;\r\n }\r\n\r\n _addSigners(_qorumServers, 1, machines);\r\n _addSigners(_institutionsServers, 2, institutions);\r\n _addSigners(_operators, 3, humans);\r\n }\r\n\r\n function proposeRecovery(\r\n address[] memory _newMachines,\r\n uint256 _newRequiredMachines,\r\n address[] memory _newInstitutions,\r\n uint256 _newRequiredInstitutions,\r\n address[] memory _newHumans,\r\n uint256 _newRequiredHumans\r\n ) external onlyQorum returns (bytes32 recoveryHash) {\r\n require(_newRequiredMachines > 0 && _newMachines.length >= _newRequiredMachines, \"LQ: invalid machines\");\r\n require(_newRequiredInstitutions > 0 && _newInstitutions.length >= _newRequiredInstitutions, \"LQ: invalid inst\");\r\n require(_newRequiredHumans > 0 && _newHumans.length >= _newRequiredHumans, \"LQ: invalid humans\");\r\n\r\n _validateAddresses(_newMachines);\r\n _validateAddresses(_newInstitutions);\r\n _validateAddresses(_newHumans);\r\n\r\n recoveryHash = keccak256(abi.encode(\r\n _newMachines,\r\n _newRequiredMachines,\r\n _newInstitutions,\r\n _newRequiredInstitutions,\r\n _newHumans,\r\n _newRequiredHumans,\r\n address(this),\r\n block.chainid\r\n ));\r\n\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt == 0, \"LQ: proposal exists\");\r\n\r\n proposal.newMachines = _newMachines;\r\n proposal.newInstitutions = _newInstitutions;\r\n proposal.newHumans = _newHumans;\r\n proposal.newRequiredMachines = _newRequiredMachines;\r\n proposal.newRequiredInstitutions = _newRequiredInstitutions;\r\n proposal.newRequiredHumans = _newRequiredHumans;\r\n proposal.proposedAt = block.timestamp;\r\n proposal.confirmations = 1;\r\n proposal.confirmedBy[msg.sender] = true;\r\n\r\n emit RecoveryProposed(recoveryHash, msg.sender);\r\n emit RecoveryConfirmed(recoveryHash, msg.sender, 1);\r\n }\r\n\r\n function confirmRecovery(bytes32 recoveryHash) external onlyQorum {\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt != 0, \"LQ: proposal not found\");\r\n require(!proposal.executed, \"LQ: already executed\");\r\n require(!proposal.confirmedBy[msg.sender], \"LQ: already confirmed\");\r\n\r\n proposal.confirmedBy[msg.sender] = true;\r\n proposal.confirmations++;\r\n\r\n emit RecoveryConfirmed(recoveryHash, msg.sender, proposal.confirmations);\r\n }\r\n\r\n function executeRecovery(bytes32 recoveryHash) external onlyQorum {\r\n RecoveryProposal storage proposal = _recoveryProposals[recoveryHash];\r\n require(proposal.proposedAt != 0, \"LQ: not found\");\r\n require(!proposal.executed, \"LQ: already executed\");\r\n require(proposal.confirmations >= recoveryQuorum, \"LQ: insufficient confirmations\");\r\n require(block.timestamp >= proposal.proposedAt + RECOVERY_DELAY, \"LQ: delay not passed\");\r\n\r\n proposal.executed = true;\r\n\r\n _clearSigners(machines);\r\n _clearSigners(institutions);\r\n _clearSigners(humans);\r\n\r\n _addSigners(proposal.newMachines, 1, machines);\r\n _addSigners(proposal.newInstitutions, 2, institutions);\r\n _addSigners(proposal.newHumans, 3, humans);\r\n\r\n requiredMachines = proposal.newRequiredMachines;\r\n requiredInstitutions = proposal.newRequiredInstitutions;\r\n requiredHumans = proposal.newRequiredHumans;\r\n\r\n emit RecoveryExecuted(recoveryHash);\r\n }\r\n\r\n function setGuardian(address _newGuardian) external virtual onlyQorum {\r\n require(_newGuardian != address(0), \"LQ: invalid guardian\");\r\n guardian = _newGuardian;\r\n emit GuardianUpdated(_newGuardian);\r\n }\r\n\r\n\r\n function confirmServers(\r\n bytes32 txHash,\r\n string memory actionType\r\n ) internal returns (bool) {\r\n require(!isExecuted[txHash], \"LQ: already executed\");\r\n uint8 sType = signerType[msg.sender];\r\n require(sType == 1 || sType == 2, \"LQ: not a server layer\");\r\n require(!isConfirmed[txHash][msg.sender], \"LQ: already confirmed\");\r\n\r\n isConfirmed[txHash][msg.sender] = true;\r\n\r\n if (sType == 1) {\r\n machineConfirmations[txHash]++;\r\n } else {\r\n institutionConfirmations[txHash]++;\r\n }\r\n\r\n if (confirmationCount[txHash] == 0) {\r\n emit ActionProposed(txHash, msg.sender, actionType);\r\n }\r\n\r\n confirmationCount[txHash]++;\r\n emit ActionConfirmed(txHash, msg.sender);\r\n\r\n if (\r\n machineConfirmations[txHash] >= requiredMachines &&\r\n institutionConfirmations[txHash] >= requiredInstitutions\r\n ) {\r\n isExecuted[txHash] = true;\r\n actionNonce[actionType]++;\r\n emit ActionExecuted(txHash);\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n function confirm(\r\n bytes32 txHash,\r\n string memory actionType\r\n ) internal returns (bool) {\r\n require(!isExecuted[txHash], \"LQ: already executed\");\r\n require(signerType[msg.sender] != 0, \"LQ: invalid signer\");\r\n require(!isConfirmed[txHash][msg.sender], \"LQ: already confirmed\");\r\n\r\n isConfirmed[txHash][msg.sender] = true;\r\n uint8 sType = signerType[msg.sender];\r\n\r\n if (sType == 1) {\r\n machineConfirmations[txHash]++;\r\n } else if (sType == 2) {\r\n institutionConfirmations[txHash]++;\r\n } else if (sType == 3) {\r\n humanConfirmations[txHash]++;\r\n }\r\n\r\n if (confirmationCount[txHash] == 0) {\r\n emit ActionProposed(txHash, msg.sender, actionType);\r\n }\r\n\r\n confirmationCount[txHash]++;\r\n emit ActionConfirmed(txHash, msg.sender);\r\n\r\n if (\r\n machineConfirmations[txHash] >= requiredMachines &&\r\n institutionConfirmations[txHash] >= requiredInstitutions &&\r\n humanConfirmations[txHash] >= requiredHumans\r\n ) {\r\n isExecuted[txHash] = true;\r\n actionNonce[actionType]++;\r\n emit ActionExecuted(txHash);\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n function _computeActionHash(\r\n string memory actionType,\r\n bytes memory params\r\n ) internal view returns (bytes32) {\r\n return keccak256(abi.encode(\r\n keccak256(bytes(actionType)),\r\n address(this),\r\n block.chainid,\r\n keccak256(params),\r\n actionNonce[actionType]\r\n ));\r\n }\r\n\r\n function _isSigner(address account) public view returns (bool) {\r\n return signerType[account] != 0;\r\n }\r\n\r\n function _isMachine(address account) internal view returns (bool) {\r\n return signerType[account] == 1;\r\n }\r\n\r\n function _isInstitution(address account) internal view returns (bool) {\r\n return signerType[account] == 2;\r\n }\r\n\r\n function _isHuman(address account) internal view returns (bool) {\r\n return signerType[account] == 3;\r\n }\r\n\r\n function _addSigners(address[] memory accounts, uint8 typeId, address[] storage storageArray) private {\r\n for (uint256 i = 0; i < accounts.length; i++) {\r\n address acc = accounts[i];\r\n require(acc != address(0), \"LQ: zero address\");\r\n require(signerType[acc] == 0, \"LQ: duplicate signer\");\r\n signerType[acc] = typeId;\r\n storageArray.push(acc);\r\n }\r\n }\r\n\r\n function _clearSigners(address[] storage storageArray) private {\r\n for (uint256 i = 0; i < storageArray.length; i++) {\r\n signerType[storageArray[i]] = 0;\r\n }\r\n uint256 len = storageArray.length;\r\n for (uint256 i = 0; i < len; i++) {\r\n storageArray.pop();\r\n }\r\n }\r\n\r\n function _validateAddresses(address[] memory accounts) private pure {\r\n for (uint256 i = 0; i < accounts.length; i++) {\r\n require(accounts[i] != address(0), \"LQ: zero address proposed\");\r\n }\r\n }\r\n}"
|
|
326
|
+
},
|
|
327
|
+
"project/contracts/institution/LinealCitizens.sol": {
|
|
328
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\r\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\r\n\r\ncontract LinealCitizens is ERC721, Ownable {\r\n using Strings for uint256;\r\n\r\n // ───────────── Constantes ─────────────\r\n\r\n uint256 public constant MAX_SCORE = 10000;\r\n uint256 public constant MIN_DELTA = 1;\r\n uint256 public constant MAX_DELTA = 10000;\r\n\r\n // ───────────── Identidad y reputación ─────────────\r\n\r\n uint256 public tokenCounter;\r\n\r\n // Permite encontrar el NFT de una wallet.\r\n mapping(address => uint256) public walletToToken;\r\n\r\n // Los nombres de usuario son únicos dentro de esta institución.\r\n mapping(string => bool) public usernameTaken;\r\n\r\n struct Profile {\r\n uint256 tokenId;\r\n string username;\r\n string imageURI;\r\n bytes32 subAccountId;\r\n uint256 reputation;\r\n bool exists;\r\n }\r\n\r\n // La identidad y su reputación pertenecen al mismo NFT.\r\n mapping(uint256 => Profile) private profiles;\r\n\r\n // Estadísticas agregadas de todos los perfiles.\r\n uint256 public totalGlobalScore;\r\n uint256 public totalWallets;\r\n\r\n // ───────────── Eventos ─────────────\r\n\r\n event ProfileIssued(\r\n address indexed wallet,\r\n uint256 indexed tokenId,\r\n string username,\r\n bytes32 subAccountId\r\n );\r\n\r\n event ProfileImageUpdated(\r\n address indexed wallet,\r\n string newImageURI\r\n );\r\n\r\n event ScoreUpdated(\r\n address indexed wallet,\r\n uint256 indexed tokenId,\r\n uint256 oldScore,\r\n uint256 newScore\r\n );\r\n\r\n // ───────────── Constructor ─────────────\r\n\r\n constructor(\r\n string memory identityName,\r\n string memory identitySymbol,\r\n address institutionOwner\r\n )\r\n ERC721(identityName, identitySymbol)\r\n Ownable(institutionOwner)\r\n {\r\n require(\r\n institutionOwner != address(0),\r\n \"Invalid institution owner\"\r\n );\r\n }\r\n\r\n // ───────────── Crear perfil NFT ─────────────\r\n\r\n function mintProfile(\r\n address wallet,\r\n string calldata username,\r\n string calldata imageURI,\r\n bytes32 subAccountId\r\n ) external onlyOwner returns (uint256) {\r\n require(wallet != address(0), \"Invalid wallet\");\r\n require(walletToToken[wallet] == 0, \"Profile exists\");\r\n require(bytes(username).length > 0, \"Empty username\");\r\n require(bytes(username).length <= 32, \"Username too long\");\r\n require(!usernameTaken[username], \"Username taken\");\r\n require(_validUsername(username), \"Invalid username\");\r\n require(_validImageURI(imageURI), \"Invalid image URI\");\r\n require(subAccountId != bytes32(0), \"Invalid subaccount\");\r\n\r\n tokenCounter++;\r\n uint256 tokenId = tokenCounter;\r\n\r\n usernameTaken[username] = true;\r\n walletToToken[wallet] = tokenId;\r\n\r\n profiles[tokenId] = Profile({\r\n tokenId: tokenId,\r\n username: username,\r\n imageURI: imageURI,\r\n subAccountId: subAccountId,\r\n reputation: 0,\r\n exists: true\r\n });\r\n\r\n // Cada NFT nuevo inicia con reputación cero.\r\n totalWallets++;\r\n\r\n _mint(wallet, tokenId);\r\n\r\n emit ProfileIssued(\r\n wallet,\r\n tokenId,\r\n username,\r\n subAccountId\r\n );\r\n\r\n return tokenId;\r\n }\r\n\r\n // ───────────── Actualizar imagen ─────────────\r\n\r\n function setImageURI(\r\n address wallet,\r\n string calldata newImageURI\r\n ) external onlyOwner {\r\n uint256 tokenId = walletToToken[wallet];\r\n\r\n require(tokenId != 0, \"Profile not found\");\r\n require(_validImageURI(newImageURI), \"Invalid image URI\");\r\n\r\n profiles[tokenId].imageURI = newImageURI;\r\n\r\n emit ProfileImageUpdated(wallet, newImageURI);\r\n }\r\n\r\n // ───────────── Consultar perfil ─────────────\r\n\r\n function getProfile(\r\n address wallet\r\n )\r\n external\r\n view\r\n returns (\r\n uint256 tokenId,\r\n string memory username,\r\n string memory imageURI,\r\n bytes32 subAccountId,\r\n uint256 reputation,\r\n string memory level\r\n )\r\n {\r\n tokenId = walletToToken[wallet];\r\n\r\n require(tokenId != 0, \"Profile not found\");\r\n\r\n Profile storage p = profiles[tokenId];\r\n\r\n return (\r\n p.tokenId,\r\n p.username,\r\n p.imageURI,\r\n p.subAccountId,\r\n p.reputation,\r\n _levelOf(p.reputation)\r\n );\r\n }\r\n\r\n function getProfileByToken(\r\n uint256 tokenId\r\n )\r\n external\r\n view\r\n returns (Profile memory profile, string memory level)\r\n {\r\n require(profiles[tokenId].exists, \"Profile not found\");\r\n\r\n profile = profiles[tokenId];\r\n level = _levelOf(profile.reputation);\r\n }\r\n\r\n function getTokenCounter() external view returns (uint256) {\r\n return tokenCounter;\r\n }\r\n\r\n // ───────────── Reputación del NFT ─────────────\r\n\r\n function updateScore(\r\n uint256 tokenId,\r\n uint256 delta,\r\n bool positive\r\n ) external onlyOwner {\r\n require(profiles[tokenId].exists, \"Profile not found\");\r\n require(\r\n delta >= MIN_DELTA && delta <= MAX_DELTA,\r\n \"Invalid delta\"\r\n );\r\n\r\n Profile storage p = profiles[tokenId];\r\n\r\n uint256 oldScore = p.reputation;\r\n uint256 newScore;\r\n\r\n if (positive) {\r\n // Evita desbordamiento y limita la reputación a 10000.\r\n if (delta >= MAX_SCORE - oldScore) {\r\n newScore = MAX_SCORE;\r\n } else {\r\n newScore = oldScore + delta;\r\n }\r\n } else {\r\n newScore = delta >= oldScore ? 0 : oldScore - delta;\r\n }\r\n\r\n p.reputation = newScore;\r\n\r\n totalGlobalScore =\r\n totalGlobalScore -\r\n oldScore +\r\n newScore;\r\n\r\n emit ScoreUpdated(\r\n ownerOf(tokenId),\r\n tokenId,\r\n oldScore,\r\n newScore\r\n );\r\n }\r\n\r\n function getReputation(\r\n uint256 tokenId\r\n )\r\n external\r\n view\r\n returns (\r\n uint256 overall,\r\n string memory level\r\n )\r\n {\r\n require(profiles[tokenId].exists, \"Profile not found\");\r\n\r\n overall = profiles[tokenId].reputation;\r\n level = _levelOf(overall);\r\n }\r\n\r\n function _levelOf(\r\n uint256 score\r\n ) internal view returns (string memory) {\r\n uint256 average = totalWallets == 0\r\n ? 0\r\n : totalGlobalScore / totalWallets;\r\n\r\n if (\r\n score >= 9500 ||\r\n (average > 0 && score >= average * 5)\r\n ) {\r\n return \"Anomalia\";\r\n }\r\n\r\n if (score >= 8000) return \"Principal\";\r\n if (score >= 6000) return \"Agente\";\r\n if (score >= 4000) return \"Operador\";\r\n if (score >= 2000) return \"Jugador\";\r\n\r\n return \"Ciudadano\";\r\n }\r\n\r\n // ───────────── NFT soulbound ─────────────\r\n\r\n function _update(\r\n address to,\r\n uint256 tokenId,\r\n address auth\r\n ) internal override returns (address) {\r\n address from = _ownerOf(tokenId);\r\n\r\n // Permite mintear, pero impide transferencias y quemados.\r\n if (from != address(0)) {\r\n revert(\"Identity is non-transferable\");\r\n }\r\n\r\n return super._update(to, tokenId, auth);\r\n }\r\n\r\n // ───────────── Metadatos NFT ─────────────\r\n\r\n function tokenURI(\r\n uint256 tokenId\r\n ) public view override returns (string memory) {\r\n require(profiles[tokenId].exists, \"Token not found\");\r\n\r\n Profile storage p = profiles[tokenId];\r\n\r\n string memory json = string.concat(\r\n '{\"name\":\"',\r\n _escapeJSON(p.username),\r\n '\",\"description\":\"Lineal Identity\",',\r\n '\"image\":\"',\r\n _escapeJSON(p.imageURI),\r\n '\",\"attributes\":[',\r\n '{\"trait_type\":\"Institution\",\"value\":\"',\r\n Strings.toHexString(uint160(owner()), 20),\r\n '\"},',\r\n '{\"trait_type\":\"Account\",\"value\":\"',\r\n Strings.toHexString(uint256(p.subAccountId), 32),\r\n '\"},',\r\n '{\"trait_type\":\"Reputation\",\"value\":',\r\n Strings.toString(p.reputation),\r\n '},',\r\n '{\"trait_type\":\"Level\",\"value\":\"',\r\n _levelOf(p.reputation),\r\n '\"}]}'\r\n );\r\n\r\n return string.concat(\r\n \"data:application/json;base64,\",\r\n Base64.encode(bytes(json))\r\n );\r\n }\r\n\r\n\r\n function subAccountOf(address wallet) external view returns (bytes32) {\r\n uint256 tokenId = walletToToken[wallet];\r\n if (tokenId == 0) return bytes32(0);\r\n return profiles[tokenId].subAccountId;\r\n }\r\n // ───────────── Validaciones ─────────────\r\n\r\n function _validUsername(\r\n string calldata username\r\n ) internal pure returns (bool) {\r\n bytes calldata b = bytes(username);\r\n\r\n for (uint256 i; i < b.length; i++) {\r\n bytes1 c = b[i];\r\n\r\n bool valid =\r\n (c >= 0x41 && c <= 0x5A) ||\r\n (c >= 0x61 && c <= 0x7A) ||\r\n (c >= 0x30 && c <= 0x39) ||\r\n c == 0x5F ||\r\n c == 0x2D ||\r\n c == 0x2E;\r\n\r\n if (!valid) return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n function _validImageURI(\r\n string calldata uri\r\n ) internal pure returns (bool) {\r\n bytes calldata b = bytes(uri);\r\n\r\n if (b.length == 0) return false;\r\n\r\n for (uint256 i; i < b.length; i++) {\r\n uint8 c = uint8(b[i]);\r\n\r\n // Evita caracteres de control. El JSON se escapa aparte.\r\n if (c < 0x20 || c == 0x7F) return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n function _escapeJSON(\r\n string memory value\r\n ) internal pure returns (string memory) {\r\n bytes memory input = bytes(value);\r\n bytes memory output = new bytes(input.length * 2);\r\n uint256 j;\r\n\r\n for (uint256 i; i < input.length; i++) {\r\n bytes1 c = input[i];\r\n\r\n if (c == 0x22 || c == 0x5C) {\r\n output[j++] = 0x5C;\r\n output[j++] = c;\r\n } else if (uint8(c) < 0x20) {\r\n // Los caracteres de control no son necesarios\r\n // en username ni imageURI.\r\n output[j++] = 0x20;\r\n } else {\r\n output[j++] = c;\r\n }\r\n }\r\n\r\n bytes memory result = new bytes(j);\r\n\r\n for (uint256 i; i < j; i++) {\r\n result[i] = output[i];\r\n }\r\n\r\n return string(result);\r\n }\r\n}"
|
|
329
|
+
},
|
|
330
|
+
"project/contracts/institution/LinealInstitution.sol": {
|
|
331
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"../governance/LinealQorum.sol\";\r\nimport \"../economy/banks/LinealBank.sol\";\r\nimport \"../economy/token/LinealToken.sol\";\r\nimport \"../institution/LinealTender.sol\";\r\nimport \"../institution/LinealCitizens.sol\"; // ajusta la ruta a donde esté tu archivo\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n\r\n/**\r\n * @title LinealInstitution - NeoQuor\r\n * @notice Contrato estándar que representa a una Institución/Corporación en el ecosistema.\r\n * Su banco custodia varios tokens ERC20; los tokens habilitados se gestionan por quórum.\r\n */\r\ncontract LinealInstitution is LinealQorum {\r\n\r\n string public institutionName;\r\n string public description;\r\n address public linealIdentity;\r\n address public linealCoin; // token principal (el primero de la lista inicial), por compatibilidad\r\n address public institutionBank;\r\n address public institutionTender;\r\n address public stableCoin;\r\n bytes32 public rewardsAccountId;\r\n bytes32 public institutionAccountId;\r\n uint256 public constant CREATION_FEE = 1_000_000;\r\n mapping(bytes32 => bool) public activeSubAccounts;\r\n mapping(address => bool) public isDirectiva;\r\n bytes32[] public subAccountIds;\r\n address[] private _directiva;\r\n\r\n event RewardsAccountCreated(bytes32 indexed accountId);\r\n event DescriptionUpdated(string newDescription);\r\n event SubAccountCreated(bytes32 indexed accountId, string accountName);\r\n event FundsMovedToSubAccount(\r\n bytes32 indexed fromAccount,\r\n bytes32 indexed toAccount,\r\n address indexed token,\r\n uint256 amount\r\n );\r\n event FundsMovedToBank(\r\n bytes32 indexed fromAccount,\r\n address indexed destBank,\r\n bytes32 indexed toAccount,\r\n address token,\r\n uint256 amount\r\n );\r\n event FundsReleased(\r\n bytes32 indexed accountId,\r\n address indexed to,\r\n address indexed token,\r\n uint256 amount,\r\n bytes32 reason\r\n );\r\n event TokenSupportSet(address indexed token, bool supported);\r\n event BankLinked(address indexed bankAddress);\r\n event TendersLinked(address indexed tendersAddress);\r\n event IdentityLinked(address indexed identityAddress);\r\n event ProfileIssued(address indexed wallet, string username, string imageURI);\r\n event CitizenAccountCreated(address indexed wallet, bytes32 indexed accountId);\r\n event ProfileImageUpdated(address indexed wallet, string newImageURI);\r\n event TenderIssued(uint256 indexed tokenId, string title, string documentURL);\r\n event PaymentProcessed(address indexed wallet, uint256 amount);\r\n event TenderAccountCreated(uint256 indexed tokenId, bytes32 indexed accountId);\r\n event InstitutionAccountCreated(bytes32 indexed accountId, string accountName);\r\n\r\n error MintFailed();\r\n error PaymentFailed();\r\n error BankNotLinked();\r\n error TendersNotLinked();\r\n error InvalidSubAccount();\r\n error InvalidDestBank();\r\n error InvalidToken();\r\n\r\n constructor(\r\n address _stableCoin,\r\n uint256 _bps,\r\n string memory _institutionName,\r\n string memory _description,\r\n address[] memory _machines,\r\n address[] memory _institutions,\r\n address[] memory _humans,\r\n uint256 _requiredMachines,\r\n uint256 _requiredInstitutions,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryQuorum\r\n ) {\r\n institutionName = _institutionName;\r\n description = _description;\r\n stableCoin = _stableCoin;\r\n // La directiva son los humans definidos\r\n for (uint256 i; i < _humans.length; i++) {\r\n address h = _humans[i];\r\n if (h != address(0) && !isDirectiva[h]) {\r\n isDirectiva[h] = true;\r\n _directiva.push(h);\r\n }\r\n }\r\n\r\n // Banco: esta Institución es su owner. _bps = fee de rewards por transferencia interna.\r\n LinealBank bank = new LinealBank(address(this), _bps);\r\n institutionBank = address(bank);\r\n\r\n // La subcuenta \"Rewards\" la crea el banco en su constructor: se registra aquí también.\r\n bytes32 rewardsId = bank.rewardsAccountId();\r\n rewardsAccountId = rewardsId;\r\n activeSubAccounts[rewardsId] = true;\r\n subAccountIds.push(rewardsId);\r\n // Cuenta propia de la institución\r\n bytes32 instId = bank.createSubAccount(_institutionName);\r\n institutionAccountId = instId;\r\n activeSubAccounts[instId] = true;\r\n subAccountIds.push(instId);\r\n emit InstitutionAccountCreated(instId, _institutionName);\r\n emit BankLinked(institutionBank);\r\n\r\n // Licitaciones (NFT): esta Institución es su owner\r\n institutionTender = address(\r\n new LinealTender(\r\n string.concat(_institutionName, \" Tenders\"),\r\n \"TENDER\",\r\n address(this)\r\n )\r\n );\r\n LinealBank(institutionBank).setTokenSupport(_stableCoin, true);\r\n emit TendersLinked(institutionTender);\r\n }\r\n\r\n // ───────────── Tokens soportados por el banco ─────────────\r\n\r\n /**\r\n * @notice Habilita o deshabilita depósitos de un token en el banco. Requiere quórum.\r\n * @dev Deshabilitar no bloquea retiros ni transferencias de saldos existentes.\r\n */\r\n function setTokenSupport(address token, bool supported) external onlyServers {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n if (token == address(0)) revert InvalidToken();\r\n\r\n bytes32 txHash = _computeActionHash(\"setTokenSupport\", abi.encode(token, supported));\r\n if (!confirmServers(txHash, \"setTokenSupport\")) return;\r\n\r\n LinealBank(institutionBank).setTokenSupport(token, supported);\r\n emit TokenSupportSet(token, supported);\r\n }\r\n\r\n function setPairToken(address token) external onlyServers {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n if (token == address(0)) revert InvalidToken();\r\n\r\n {\r\n bytes32 txHash = _computeActionHash(\"setPairToken\", abi.encode(token));\r\n if (!confirmServers(txHash, \"setPairToken\")) return;\r\n }\r\n LinealBank(institutionBank).setTokenSupport(token, true);\r\n linealCoin = token;\r\n emit TokenSupportSet(token, true);\r\n }\r\n\r\n function setCitizensAddress(address contractAddress) external onlyServers {\r\n if (contractAddress == address(0)) revert InvalidToken();\r\n bytes32 txHash = _computeActionHash(\"setCitizensAddress\", abi.encode(contractAddress));\r\n if (!confirmServers(txHash, \"setCitizensAddress\")) return;\r\n linealIdentity = contractAddress;\r\n emit IdentityLinked(contractAddress);\r\n }\r\n\r\n /**\r\n * @notice Crea una nueva subcuenta asociada a esta Institución. Requiere quorum de signers.\r\n * @param accountName Nombre de la subcuenta.\r\n */\r\n function createSubAccount(string calldata accountName) external onlyQorum {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n\r\n bytes32 txHash = _computeActionHash(\"createSubAccount\", abi.encode(accountName));\r\n if (!confirm(txHash, \"createSubAccount\")) return;\r\n\r\n bytes32 id = LinealBank(institutionBank).createSubAccount(accountName);\r\n activeSubAccounts[id] = true;\r\n subAccountIds.push(id);\r\n emit SubAccountCreated(id, accountName);\r\n }\r\n\r\n /**\r\n * @notice Mueve un token entre dos subcuentas del banco de esta Institución. Requiere quórum.\r\n */\r\n function moveFundsToSubAccount(\r\n bytes32 fromAccount,\r\n bytes32 toAccount,\r\n address token,\r\n uint256 amount\r\n ) external onlyQorum {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n if (!activeSubAccounts[fromAccount]) revert InvalidSubAccount();\r\n if (!activeSubAccounts[toAccount]) revert InvalidSubAccount();\r\n\r\n bytes32 txHash = _computeActionHash(\r\n \"moveFundsToSubAccount\",\r\n abi.encode(fromAccount, toAccount, token, amount)\r\n );\r\n if (!confirm(txHash, \"moveFundsToSubAccount\")) return;\r\n\r\n LinealBank(institutionBank).internalTransfer(fromAccount, toAccount, token, amount);\r\n emit FundsMovedToSubAccount(fromAccount, toAccount, token, amount);\r\n }\r\n\r\n /**\r\n * @notice Envía un token de una subcuenta del banco de esta Institución a una subcuenta\r\n * del banco de OTRA institución. Requiere quórum de signers.\r\n * @dev El banco destino debe tener habilitado ese token (lo valida el banco).\r\n * `toAccount` pertenece al banco destino, por eso no se valida contra `activeSubAccounts`.\r\n * @param fromAccount Subcuenta de origen en el banco de esta Institución.\r\n * @param destBank Dirección del LinealBank destino.\r\n * @param toAccount Subcuenta de destino en `destBank`.\r\n * @param token Token a enviar.\r\n * @param amount Monto bruto a debitar (el banco descuenta el fee de rewards).\r\n */\r\n function moveFundsToBank(\r\n bytes32 fromAccount,\r\n address destBank,\r\n bytes32 toAccount,\r\n address token,\r\n uint256 amount\r\n ) external onlyQorum {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n if (!activeSubAccounts[fromAccount]) revert InvalidSubAccount();\r\n if (destBank == address(0) || destBank == institutionBank) revert InvalidDestBank();\r\n\r\n bytes32 txHash = _computeActionHash(\r\n \"moveFundsToBank\",\r\n abi.encode(fromAccount, destBank, toAccount, token, amount)\r\n );\r\n if (!confirm(txHash, \"moveFundsToBank\")) return;\r\n\r\n LinealBank(institutionBank).transferToBank(fromAccount, destBank, toAccount, token, amount);\r\n emit FundsMovedToBank(fromAccount, destBank, toAccount, token, amount);\r\n }\r\n\r\n /**\r\n * @notice Libera un token de una subcuenta del banco hacia una dirección externa. Requiere quórum.\r\n */\r\n function releaseFromBank(\r\n bytes32 accountId,\r\n address token,\r\n address payable to,\r\n uint256 amount,\r\n bytes32 reason\r\n ) external onlyQorum {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n if (!activeSubAccounts[accountId]) revert InvalidSubAccount();\r\n\r\n bytes32 txHash = _computeActionHash(\r\n \"releaseFromBank\",\r\n abi.encode(accountId, token, to, amount, reason)\r\n );\r\n if (!confirm(txHash, \"releaseFromBank\")) return;\r\n\r\n LinealBank(institutionBank).release(accountId, token, to, amount, reason);\r\n emit FundsReleased(accountId, to, token, amount, reason);\r\n }\r\n\r\n\r\n /**\r\n * @notice Libera un token de una subcuenta del banco hacia una dirección externa. Requiere quórum.\r\n */\r\n function releasePreSale(\r\n address token,\r\n address payable to,\r\n uint256 amount,\r\n bytes32 reason\r\n ) external onlyServers {\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n\r\n bytes32 txHash = _computeActionHash(\r\n \"releaseFromBank\",\r\n abi.encode(token, to, amount, reason)\r\n );\r\n if (!confirm(txHash, \"releaseFromBank\")) return;\r\n\r\n LinealBank(institutionBank).release(institutionAccountId, token, to, amount, reason);\r\n emit FundsReleased(institutionAccountId, to, token, amount, reason);\r\n }\r\n\r\n // ───────────── Licitaciones (LinealTenders) ─────────────\r\n\r\n function mintTender(\r\n string calldata title,\r\n string calldata tenderDescription,\r\n string calldata imageURI,\r\n string calldata documentURL,\r\n uint256 amount\r\n ) external onlyQorum {\r\n if (institutionTender == address(0)) revert TendersNotLinked();\r\n if (institutionBank == address(0)) revert BankNotLinked();\r\n\r\n {\r\n bytes32 txHash = _computeActionHash(\r\n \"mintTender\",\r\n abi.encode(title, tenderDescription, imageURI, documentURL, amount)\r\n );\r\n if (!confirm(txHash, \"mintTender\")) return;\r\n }\r\n\r\n // 1. Crear la subcuenta de la licitación en el banco\r\n bytes32 id = LinealBank(institutionBank).createSubAccount(title);\r\n activeSubAccounts[id] = true;\r\n subAccountIds.push(id);\r\n\r\n // 2. Mintear la licitación pasando la subcuenta como argumento\r\n uint256 tokenId = LinealTender(institutionTender).mintTender(\r\n title,\r\n tenderDescription,\r\n imageURI,\r\n documentURL,\r\n amount,\r\n id\r\n );\r\n\r\n emit TenderIssued(tokenId, title, documentURL);\r\n emit TenderAccountCreated(tokenId, id);\r\n }\r\n\r\n // ───────────── Identidad (LinealCitizens) ─────────────\r\n\r\n /**\r\n * @notice Emite un perfil soulbound en LinealCitizens. Requiere quórum de servers.\r\n * Primero crea la subcuenta del ciudadano en el banco y luego mintea el perfil\r\n * pasando el id de la subcuenta. La recompensa de 5 QRM sale del saldo de LinealCitizens.\r\n */\r\n function mintProfile(\r\n address wallet,\r\n string calldata username,\r\n string calldata imageURI\r\n ) external onlyServers {\r\n {\r\n bytes32 txHash = _computeActionHash(\r\n \"mintProfile\",\r\n abi.encode(wallet, username, imageURI)\r\n );\r\n if (!confirmServers(txHash, \"mintProfile\")) return;\r\n }\r\n uint256 tokenCounter = LinealCitizens(linealIdentity).tokenCounter();\r\n\r\n bytes32 id = LinealBank(institutionBank).createCitizenAccount(username);\r\n activeSubAccounts[id] = true;\r\n subAccountIds.push(id);\r\n\r\n if ((tokenCounter + 1) <= 25000) {\r\n LinealBank(institutionBank).zeroFeeInternalTransfer(institutionAccountId, id, linealCoin, 50 * 1e18);\r\n }\r\n\r\n // 2. Mintear el perfil pasando la subcuenta como argumento\r\n LinealCitizens(linealIdentity).mintProfile(wallet, username, imageURI, id);\r\n emit ProfileIssued(wallet, username, imageURI);\r\n emit CitizenAccountCreated(wallet, id);\r\n }\r\n\r\n function updateIdentityScore(\r\n uint256 tokenId,\r\n uint256 delta,\r\n bool positive\r\n ) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\r\n \"updateIdentityScore\",\r\n abi.encode(tokenId, delta, positive)\r\n );\r\n\r\n if (!confirmServers(txHash, \"updateIdentityScore\")) return;\r\n\r\n LinealCitizens(linealIdentity).updateScore(\r\n tokenId,\r\n delta,\r\n positive\r\n );\r\n }\r\n\r\n /**\r\n * @notice Actualiza la imagen de un perfil existente. Requiere quórum de servers.\r\n */\r\n function setProfileImageURI(address wallet, string calldata newImageURI) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\r\n \"setProfileImageURI\",\r\n abi.encode(wallet, newImageURI)\r\n );\r\n if (!confirmServers(txHash, \"setProfileImageURI\")) return;\r\n\r\n LinealCitizens(linealIdentity).setImageURI(wallet, newImageURI);\r\n emit ProfileImageUpdated(wallet, newImageURI);\r\n }\r\n\r\n function getDirectiva() external view returns (address[] memory) {\r\n return _directiva;\r\n }\r\n\r\n function setDescription(string calldata newDescription) external onlyQorum {\r\n bytes32 txHash = _computeActionHash(\"setDescription\", abi.encode(newDescription));\r\n if (!confirm(txHash, \"setDescription\")) return;\r\n\r\n description = newDescription;\r\n emit DescriptionUpdated(newDescription);\r\n }\r\n\r\n // ───────────── Vistas ─────────────\r\n\r\n /**\r\n * @notice Devuelve todas las subcuentas creadas por esta Institución.\r\n */\r\n function getSubAccounts() external view returns (bytes32[] memory) {\r\n return subAccountIds;\r\n }\r\n\r\n /**\r\n * @notice Devuelve la dirección del banco vinculado a esta institución.\r\n */\r\n function getInstitutionBank() external view returns (address) {\r\n return address(institutionBank);\r\n }\r\n\r\n /**\r\n * @notice Devuelve la dirección del contrato de licitaciones (LinealTenders).\r\n */\r\n function getInstitutionTender() external view returns (address) {\r\n return institutionTender;\r\n }\r\n\r\n /**\r\n * @notice Devuelve la dirección del contrato de identidad (LinealCitizens).\r\n */\r\n function getIdentity() external view returns (address) {\r\n return linealIdentity;\r\n }\r\n\r\n function getRewardsAccountId() external view returns (bytes32) {\r\n return LinealBank(institutionBank).rewardsAccountId();\r\n }\r\n\r\n /**\r\n * @notice Tokens registrados en el banco (habilitados o no; ver `supportedToken` en el banco).\r\n */\r\n function getBankTokens() external view returns (address[] memory) {\r\n return LinealBank(institutionBank).tokenList();\r\n }\r\n\r\n /**\r\n * @notice Saldos de una subcuenta en todos los tokens registrados del banco.\r\n */\r\n function getAccountBalances(bytes32 accountId)\r\n external\r\n view\r\n returns (address[] memory tokens, uint256[] memory balances)\r\n {\r\n return LinealBank(institutionBank).accountBalancesAll(accountId);\r\n }\r\n}\r\n"
|
|
332
|
+
},
|
|
333
|
+
"project/contracts/institution/LinealTender.sol": {
|
|
334
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\r\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\r\n\r\n/**\r\n * @title LinealTenders - NeoQuor\r\n * @notice Licitaciones como NFT. Cada licitación es un token (soulbound, en custodia de la\r\n * Institución) con título, descripción, imagen, URL del documento y su subcuenta en el banco.\r\n * Solo el owner (la Institución) puede emitirlas y modificarlas.\r\n */\r\ncontract LinealTender is ERC721, Ownable {\r\n\r\n uint256 public constant MAX_TITLE_LENGTH = 100; // bytes\r\n\r\n // Institución dueña de este contrato\r\n address public immutable institutionAddress;\r\n\r\n uint256 public tenderCounter;\r\n\r\n struct Tender {\r\n uint256 tokenId;\r\n string title;\r\n string description;\r\n string imageURI;\r\n string documentURL;\r\n uint256 amount; // Monto de la licitación\r\n uint256 createdAt;\r\n bool active;\r\n bytes32 subAccountId; // Subcuenta del banco asociada a la licitación\r\n }\r\n\r\n mapping(uint256 => Tender) private tenders;\r\n\r\n event TenderMinted(\r\n uint256 indexed tokenId,\r\n string title,\r\n string description,\r\n string imageURI,\r\n string documentURL,\r\n uint256 amount,\r\n bytes32 subAccountId\r\n );\r\n event TenderUpdated(\r\n uint256 indexed tokenId,\r\n string title,\r\n string description,\r\n string imageURI,\r\n string documentURL,\r\n uint256 amount\r\n );\r\n event TenderStatusChanged(uint256 indexed tokenId, bool active);\r\n\r\n error InvalidAddress();\r\n error EmptyTitle();\r\n error TitleTooLong();\r\n error EmptyDescription();\r\n error EmptyImageURI();\r\n error EmptyDocumentURL();\r\n error TenderDoesNotExist();\r\n error NonTransferable();\r\n error InvalidAmount();\r\n error InvalidSubAccount();\r\n\r\n /// @param _name Nombre de la colección.\r\n /// @param _symbol Símbolo de la colección.\r\n /// @param _institutionAddress Dueño del contrato (la Institución). Recibe los NFT.\r\n constructor(\r\n string memory _name,\r\n string memory _symbol,\r\n address _institutionAddress\r\n )\r\n ERC721(_name, _symbol)\r\n Ownable(_institutionAddress)\r\n {\r\n if (_institutionAddress == address(0)) revert InvalidAddress();\r\n institutionAddress = _institutionAddress;\r\n }\r\n\r\n /**\r\n * @notice Emite una licitación como NFT a la Institución (solo owner).\r\n * @param _title Título (máx. 100 bytes).\r\n * @param _description Descripción.\r\n * @param _imageURI URL de la foto/imagen.\r\n * @param _documentURL URL del documento de la licitación.\r\n * @param _amount Monto de la licitación.\r\n * @param _subAccountId Subcuenta del banco creada previamente por la Institución.\r\n */\r\n function mintTender(\r\n string calldata _title,\r\n string calldata _description,\r\n string calldata _imageURI,\r\n string calldata _documentURL,\r\n uint256 _amount,\r\n bytes32 _subAccountId\r\n ) external onlyOwner returns (uint256 tokenId) {\r\n _validate(_title, _description, _imageURI, _documentURL);\r\n\r\n if (_amount == 0) revert InvalidAmount();\r\n if (_subAccountId == bytes32(0)) revert InvalidSubAccount();\r\n\r\n tokenId = ++tenderCounter;\r\n\r\n tenders[tokenId] = Tender({\r\n tokenId: tokenId,\r\n title: _title,\r\n description: _description,\r\n imageURI: _imageURI,\r\n documentURL: _documentURL,\r\n amount: _amount,\r\n createdAt: block.timestamp,\r\n active: true,\r\n subAccountId: _subAccountId\r\n });\r\n\r\n _mint(institutionAddress, tokenId);\r\n\r\n emit TenderMinted(\r\n tokenId,\r\n _title,\r\n _description,\r\n _imageURI,\r\n _documentURL,\r\n _amount,\r\n _subAccountId\r\n );\r\n }\r\n\r\n /// @notice Actualiza los datos de una licitación existente (solo owner). La subcuenta no cambia.\r\n function updateTender(\r\n uint256 tokenId,\r\n string calldata _title,\r\n string calldata _description,\r\n string calldata _imageURI,\r\n string calldata _documentURL,\r\n uint256 amount\r\n ) external onlyOwner {\r\n if (_ownerOf(tokenId) == address(0)) revert TenderDoesNotExist();\r\n _validate(_title, _description, _imageURI, _documentURL);\r\n if (amount == 0) revert InvalidAmount();\r\n\r\n Tender storage t = tenders[tokenId];\r\n t.title = _title;\r\n t.description = _description;\r\n t.imageURI = _imageURI;\r\n t.documentURL = _documentURL;\r\n t.amount = amount;\r\n\r\n emit TenderUpdated(tokenId, _title, _description, _imageURI, _documentURL, amount);\r\n }\r\n\r\n /// @notice Abre o cierra una licitación (solo owner).\r\n function setTenderActive(uint256 tokenId, bool active) external onlyOwner {\r\n if (_ownerOf(tokenId) == address(0)) revert TenderDoesNotExist();\r\n tenders[tokenId].active = active;\r\n emit TenderStatusChanged(tokenId, active);\r\n }\r\n\r\n // --- LECTURA ---\r\n\r\n function getTender(uint256 tokenId) external view returns (Tender memory) {\r\n if (_ownerOf(tokenId) == address(0)) revert TenderDoesNotExist();\r\n return tenders[tokenId];\r\n }\r\n\r\n function getTenderCounter() external view returns (uint256) {\r\n return tenderCounter;\r\n }\r\n\r\n /// @notice Subcuenta del banco asociada a una licitación.\r\n function subAccountOf(uint256 tokenId) external view returns (bytes32) {\r\n if (_ownerOf(tokenId) == address(0)) revert TenderDoesNotExist();\r\n return tenders[tokenId].subAccountId;\r\n }\r\n\r\n /// @notice Lista todos los ids de licitaciones emitidas (1..tenderCounter).\r\n function getTenderIds() external view returns (uint256[] memory ids) {\r\n uint256 total = tenderCounter;\r\n ids = new uint256[](total);\r\n for (uint256 i = 0; i < total; i++) {\r\n ids[i] = i + 1;\r\n }\r\n }\r\n\r\n /// @notice Lista paginada de licitaciones completas (para evitar quedarse sin gas en lecturas grandes).\r\n /// @param offset Posición inicial (0 = primera licitación).\r\n /// @param limit Máximo de resultados a devolver.\r\n function getTenders(uint256 offset, uint256 limit) external view returns (Tender[] memory page) {\r\n uint256 total = tenderCounter;\r\n if (offset >= total) return new Tender[](0);\r\n\r\n uint256 end = offset + limit;\r\n if (end > total) end = total;\r\n\r\n page = new Tender[](end - offset);\r\n for (uint256 i = offset; i < end; i++) {\r\n page[i - offset] = tenders[i + 1];\r\n }\r\n }\r\n\r\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\r\n if (_ownerOf(tokenId) == address(0)) revert TenderDoesNotExist();\r\n\r\n Tender storage t = tenders[tokenId];\r\n\r\n string memory json = Base64.encode(\r\n bytes(\r\n string.concat(\r\n '{\"name\":\"', _escape(t.title), '\",',\r\n '\"description\":\"', _escape(t.description), '\",',\r\n '\"image\":\"', _escape(t.imageURI), '\",',\r\n '\"external_url\":\"', _escape(t.documentURL), '\",',\r\n _attributes(t),\r\n '}'\r\n )\r\n )\r\n );\r\n\r\n return string.concat(\"data:application/json;base64,\", json);\r\n }\r\n\r\n // --- INTERNAS ---\r\n\r\n function _attributes(Tender storage t) internal view returns (string memory) {\r\n return string.concat(\r\n '\"attributes\":[',\r\n '{\"trait_type\":\"Institution\",\"value\":\"', Strings.toHexString(institutionAddress), '\"},',\r\n '{\"trait_type\":\"Status\",\"value\":\"', t.active ? \"Active\" : \"Closed\", '\"},',\r\n '{\"trait_type\":\"Account\",\"value\":\"', Strings.toHexString(uint256(t.subAccountId), 32), '\"},',\r\n '{\"display_type\":\"date\",\"trait_type\":\"Created\",\"value\":', Strings.toString(t.createdAt), '}',\r\n ']'\r\n );\r\n }\r\n\r\n /// @dev Soulbound: se puede mintear, pero no transferir entre wallets.\r\n function _update(\r\n address to,\r\n uint256 tokenId,\r\n address auth\r\n ) internal override returns (address) {\r\n address from = _ownerOf(tokenId);\r\n if (from != address(0) && to != address(0)) revert NonTransferable();\r\n return super._update(to, tokenId, auth);\r\n }\r\n\r\n function _validate(\r\n string calldata _title,\r\n string calldata _description,\r\n string calldata _imageURI,\r\n string calldata _documentURL\r\n ) internal pure {\r\n uint256 len = bytes(_title).length;\r\n if (len == 0) revert EmptyTitle();\r\n if (len > MAX_TITLE_LENGTH) revert TitleTooLong();\r\n if (bytes(_description).length == 0) revert EmptyDescription();\r\n if (bytes(_imageURI).length == 0) revert EmptyImageURI();\r\n if (bytes(_documentURL).length == 0) revert EmptyDocumentURL();\r\n }\r\n\r\n /// @dev Escapa comillas, backslash y saltos de línea para no romper el JSON del tokenURI.\r\n function _escape(string memory s) internal pure returns (string memory) {\r\n bytes memory b = bytes(s);\r\n bytes memory out = new bytes(b.length * 2);\r\n uint256 j;\r\n for (uint256 i = 0; i < b.length; i++) {\r\n bytes1 c = b[i];\r\n if (c == 0x22 || c == 0x5c) { // \" o \\\r\n out[j++] = 0x5c;\r\n out[j++] = c;\r\n } else if (c == 0x0a) { // \\n\r\n out[j++] = 0x5c;\r\n out[j++] = 0x6e;\r\n } else if (c == 0x0d || c == 0x09) { // \\r, \\t -> espacio\r\n out[j++] = 0x20;\r\n } else {\r\n out[j++] = c;\r\n }\r\n }\r\n bytes memory trimmed = new bytes(j);\r\n for (uint256 k = 0; k < j; k++) {\r\n trimmed[k] = out[k];\r\n }\r\n return string(trimmed);\r\n }\r\n}"
|
|
335
|
+
},
|
|
336
|
+
"project/contracts/interfaces/IAccount.sol": {
|
|
337
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\nimport \"./PackedUserOperation.sol\";\n\ninterface IAccount {\n /**\n * Validate user's signature and nonce\n * the entryPoint will make the call to the recipient only if this validation call returns successfully.\n * signature failure should be reported by returning SIG_VALIDATION_FAILED (1).\n * This allows making a \"simulation call\" without a valid signature\n * Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.\n *\n * @dev Must validate caller is the entryPoint.\n * Must validate the signature and nonce\n * @param userOp - The operation that is about to be executed.\n * @param userOpHash - Hash of the user's request data. can be used as the basis for signature.\n * @param missingAccountFunds - Missing funds on the account's deposit in the entrypoint.\n * This is the minimum amount to transfer to the sender(entryPoint) to be\n * able to make the call. The excess is left as a deposit in the entrypoint\n * for future calls. Can be withdrawn anytime using \"entryPoint.withdrawTo()\".\n * In case there is a paymaster in the request (or the current deposit is high\n * enough), this value will be zero.\n * @return validationData - Packaged ValidationData structure. use `_packValidationData` and\n * `_unpackValidationData` to encode and decode.\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - Last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - First timestamp this operation is valid\n * If an account doesn't use time-range, it is enough to\n * return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validateUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external returns (uint256 validationData);\n}\n"
|
|
338
|
+
},
|
|
339
|
+
"project/contracts/interfaces/IAccountExecute.sol": {
|
|
340
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\nimport \"./PackedUserOperation.sol\";\n\ninterface IAccountExecute {\n /**\n * Account may implement this execute method.\n * passing this methodSig at the beginning of callData will cause the entryPoint to pass the full UserOp (and hash)\n * to the account.\n * The account should skip the methodSig, and use the callData (and optionally, other UserOp fields)\n *\n * @param userOp - The operation that was just validated.\n * @param userOpHash - Hash of the user's request data.\n */\n function executeUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash\n ) external;\n}\n"
|
|
341
|
+
},
|
|
342
|
+
"project/contracts/interfaces/IAggregator.sol": {
|
|
343
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\nimport \"./PackedUserOperation.sol\";\n\n/**\n * Aggregated Signatures validator.\n */\ninterface IAggregator {\n /**\n * Validate aggregated signature.\n * Revert if the aggregated signature does not match the given list of operations.\n * @param userOps - Array of UserOperations to validate the signature for.\n * @param signature - The aggregated signature.\n */\n function validateSignatures(\n PackedUserOperation[] calldata userOps,\n bytes calldata signature\n ) external view;\n\n /**\n * Validate signature of a single userOp.\n * This method should be called by bundler after EntryPointSimulation.simulateValidation() returns\n * the aggregator this account uses.\n * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.\n * @param userOp - The userOperation received from the user.\n * @return sigForUserOp - The value to put into the signature field of the userOp when calling handleOps.\n * (usually empty, unless account and aggregator support some kind of \"multisig\".\n */\n function validateUserOpSignature(\n PackedUserOperation calldata userOp\n ) external view returns (bytes memory sigForUserOp);\n\n /**\n * Aggregate multiple signatures into a single value.\n * This method is called off-chain to calculate the signature to pass with handleOps()\n * bundler MAY use optimized custom code perform this aggregation.\n * @param userOps - Array of UserOperations to collect the signatures from.\n * @return aggregatedSignature - The aggregated signature.\n */\n function aggregateSignatures(\n PackedUserOperation[] calldata userOps\n ) external view returns (bytes memory aggregatedSignature);\n}\n"
|
|
344
|
+
},
|
|
345
|
+
"project/contracts/interfaces/IEntryPoint.sol": {
|
|
346
|
+
"content": "/**\n ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n ** Only one instance required on each chain.\n **/\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"./PackedUserOperation.sol\";\nimport \"./IStakeManager.sol\";\nimport \"./IAggregator.sol\";\nimport \"./INonceManager.sol\";\n\ninterface IEntryPoint is IStakeManager, INonceManager {\n /***\n * An event emitted after each successful request.\n * @param userOpHash - Unique identifier for the request (hash its entire content, except signature).\n * @param sender - The account that generates this request.\n * @param paymaster - If non-null, the paymaster that pays for this request.\n * @param nonce - The nonce value from the request.\n * @param success - True if the sender transaction succeeded, false if reverted.\n * @param actualGasCost - Actual amount paid (by account or paymaster) for this UserOperation.\n * @param actualGasUsed - Total gas used by this UserOperation (including preVerification, creation,\n * validation and execution).\n */\n event UserOperationEvent(\n bytes32 indexed userOpHash,\n address indexed sender,\n address indexed paymaster,\n uint256 nonce,\n bool success,\n uint256 actualGasCost,\n uint256 actualGasUsed\n );\n\n /**\n * Account \"sender\" was deployed.\n * @param userOpHash - The userOp that deployed this account. UserOperationEvent will follow.\n * @param sender - The account that is deployed\n * @param factory - The factory used to deploy this account (in the initCode)\n * @param paymaster - The paymaster used by this UserOp\n */\n event AccountDeployed(\n bytes32 indexed userOpHash,\n address indexed sender,\n address factory,\n address paymaster\n );\n\n /**\n * An event emitted if the UserOperation \"callData\" reverted with non-zero length.\n * @param userOpHash - The request unique identifier.\n * @param sender - The sender of this request.\n * @param nonce - The nonce used in the request.\n * @param revertReason - The return bytes from the (reverted) call to \"callData\".\n */\n event UserOperationRevertReason(\n bytes32 indexed userOpHash,\n address indexed sender,\n uint256 nonce,\n bytes revertReason\n );\n\n /**\n * An event emitted if the UserOperation Paymaster's \"postOp\" call reverted with non-zero length.\n * @param userOpHash - The request unique identifier.\n * @param sender - The sender of this request.\n * @param nonce - The nonce used in the request.\n * @param revertReason - The return bytes from the (reverted) call to \"callData\".\n */\n event PostOpRevertReason(\n bytes32 indexed userOpHash,\n address indexed sender,\n uint256 nonce,\n bytes revertReason\n );\n\n /**\n * UserOp consumed more than prefund. The UserOperation is reverted, and no refund is made.\n * @param userOpHash - The request unique identifier.\n * @param sender - The sender of this request.\n * @param nonce - The nonce used in the request.\n */\n event UserOperationPrefundTooLow(\n bytes32 indexed userOpHash,\n address indexed sender,\n uint256 nonce\n );\n\n /**\n * An event emitted by handleOps(), before starting the execution loop.\n * Any event emitted before this event, is part of the validation.\n */\n event BeforeExecution();\n\n /**\n * Signature aggregator used by the following UserOperationEvents within this bundle.\n * @param aggregator - The aggregator used for the following UserOperationEvents.\n */\n event SignatureAggregatorChanged(address indexed aggregator);\n\n /**\n * A custom revert error of handleOps, to identify the offending op.\n * Should be caught in off-chain handleOps simulation and not happen on-chain.\n * Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.\n * NOTE: If simulateValidation passes successfully, there should be no reason for handleOps to fail on it.\n * @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).\n * @param reason - Revert reason. The string starts with a unique code \"AAmn\",\n * where \"m\" is \"1\" for factory, \"2\" for account and \"3\" for paymaster issues,\n * so a failure can be attributed to the correct entity.\n */\n error FailedOp(uint256 opIndex, string reason);\n\n /**\n * A custom revert error of handleOps, to report a revert by account or paymaster.\n * @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).\n * @param reason - Revert reason. see FailedOp(uint256,string), above\n * @param inner - data from inner cought revert reason\n * @dev note that inner is truncated to 2048 bytes\n */\n error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);\n\n error PostOpReverted(bytes returnData);\n\n /**\n * Error case when a signature aggregator fails to verify the aggregated signature it had created.\n * @param aggregator The aggregator that failed to verify the signature\n */\n error SignatureValidationFailed(address aggregator);\n\n // Return value of getSenderAddress.\n error SenderAddressResult(address sender);\n\n // UserOps handled, per aggregator.\n struct UserOpsPerAggregator {\n PackedUserOperation[] userOps;\n // Aggregator address\n IAggregator aggregator;\n // Aggregated signature\n bytes signature;\n }\n\n /**\n * Execute a batch of UserOperations.\n * No signature aggregator is used.\n * If any account requires an aggregator (that is, it returned an aggregator when\n * performing simulateValidation), then handleAggregatedOps() must be used instead.\n * @param ops - The operations to execute.\n * @param beneficiary - The address to receive the fees.\n */\n function handleOps(\n PackedUserOperation[] calldata ops,\n address payable beneficiary\n ) external;\n\n /**\n * Execute a batch of UserOperation with Aggregators\n * @param opsPerAggregator - The operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts).\n * @param beneficiary - The address to receive the fees.\n */\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) external;\n\n /**\n * Generate a request Id - unique identifier for this request.\n * The request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.\n * @param userOp - The user operation to generate the request ID for.\n * @return hash the hash of this UserOperation\n */\n function getUserOpHash(\n PackedUserOperation calldata userOp\n ) external view returns (bytes32);\n\n /**\n * Gas and return values during simulation.\n * @param preOpGas - The gas used for validation (including preValidationGas)\n * @param prefund - The required prefund for this operation\n * @param accountValidationData - returned validationData from account.\n * @param paymasterValidationData - return validationData from paymaster.\n * @param paymasterContext - Returned by validatePaymasterUserOp (to be passed into postOp)\n */\n struct ReturnInfo {\n uint256 preOpGas;\n uint256 prefund;\n uint256 accountValidationData;\n uint256 paymasterValidationData;\n bytes paymasterContext;\n }\n\n /**\n * Returned aggregated signature info:\n * The aggregator returned by the account, and its current stake.\n */\n struct AggregatorStakeInfo {\n address aggregator;\n StakeInfo stakeInfo;\n }\n\n /**\n * Get counterfactual sender address.\n * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.\n * This method always revert, and returns the address in SenderAddressResult error\n * @param initCode - The constructor code to be passed into the UserOperation.\n */\n function getSenderAddress(bytes memory initCode) external;\n\n error DelegateAndRevert(bool success, bytes ret);\n\n /**\n * Helper method for dry-run testing.\n * @dev calling this method, the EntryPoint will make a delegatecall to the given data, and report (via revert) the result.\n * The method always revert, so is only useful off-chain for dry run calls, in cases where state-override to replace\n * actual EntryPoint code is less convenient.\n * @param target a target contract to make a delegatecall from entrypoint\n * @param data data to pass to target in a delegatecall\n */\n function delegateAndRevert(address target, bytes calldata data) external;\n}\n"
|
|
347
|
+
},
|
|
348
|
+
"project/contracts/interfaces/IEntryPointSimulations.sol": {
|
|
349
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\nimport \"./PackedUserOperation.sol\";\nimport \"./IEntryPoint.sol\";\n\ninterface IEntryPointSimulations is IEntryPoint {\n // Return value of simulateHandleOp.\n struct ExecutionResult {\n uint256 preOpGas;\n uint256 paid;\n uint256 accountValidationData;\n uint256 paymasterValidationData;\n bool targetSuccess;\n bytes targetResult;\n }\n\n /**\n * Successful result from simulateValidation.\n * If the account returns a signature aggregator the \"aggregatorInfo\" struct is filled in as well.\n * @param returnInfo Gas and time-range returned values\n * @param senderInfo Stake information about the sender\n * @param factoryInfo Stake information about the factory (if any)\n * @param paymasterInfo Stake information about the paymaster (if any)\n * @param aggregatorInfo Signature aggregation info (if the account requires signature aggregator)\n * Bundler MUST use it to verify the signature, or reject the UserOperation.\n */\n struct ValidationResult {\n ReturnInfo returnInfo;\n StakeInfo senderInfo;\n StakeInfo factoryInfo;\n StakeInfo paymasterInfo;\n AggregatorStakeInfo aggregatorInfo;\n }\n\n /**\n * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.\n * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage\n * outside the account's data.\n * @param userOp - The user operation to validate.\n * @return the validation result structure\n */\n function simulateValidation(\n PackedUserOperation calldata userOp\n )\n external\n returns (\n ValidationResult memory\n );\n\n /**\n * Simulate full execution of a UserOperation (including both validation and target execution)\n * It performs full validation of the UserOperation, but ignores signature error.\n * An optional target address is called after the userop succeeds,\n * and its value is returned (before the entire call is reverted).\n * Note that in order to collect the the success/failure of the target call, it must be executed\n * with trace enabled to track the emitted events.\n * @param op The UserOperation to simulate.\n * @param target - If nonzero, a target address to call after userop simulation. If called,\n * the targetSuccess and targetResult are set to the return from that call.\n * @param targetCallData - CallData to pass to target address.\n * @return the execution result structure\n */\n function simulateHandleOp(\n PackedUserOperation calldata op,\n address target,\n bytes calldata targetCallData\n )\n external\n returns (\n ExecutionResult memory\n );\n}\n"
|
|
350
|
+
},
|
|
351
|
+
"project/contracts/interfaces/IMetricsAdapter.sol": {
|
|
352
|
+
"content": "\r\n// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\ninterface IMetricsAdapter {\r\n function getMetrics() external view returns (uint256 alpha, uint256 idp);\r\n}"
|
|
353
|
+
},
|
|
354
|
+
"project/contracts/interfaces/INonceManager.sol": {
|
|
355
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\ninterface INonceManager {\n\n /**\n * Return the next nonce for this sender.\n * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)\n * But UserOp with different keys can come with arbitrary order.\n *\n * @param sender the account address\n * @param key the high 192 bit of the nonce\n * @return nonce a full nonce to pass for next UserOp with this sender.\n */\n function getNonce(address sender, uint192 key)\n external view returns (uint256 nonce);\n\n /**\n * Manually increment the nonce of the sender.\n * This method is exposed just for completeness..\n * Account does NOT need to call it, neither during validation, nor elsewhere,\n * as the EntryPoint will update the nonce regardless.\n * Possible use-case is call it with various keys to \"initialize\" their nonces to one, so that future\n * UserOperations will not pay extra for the first transaction with a given key.\n */\n function incrementNonce(uint192 key) external;\n}\n"
|
|
356
|
+
},
|
|
357
|
+
"project/contracts/interfaces/IPaymaster.sol": {
|
|
358
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\nimport \"./PackedUserOperation.sol\";\n\n/**\n * The interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.\n * A paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.\n */\ninterface IPaymaster {\n enum PostOpMode {\n // User op succeeded.\n opSucceeded,\n // User op reverted. Still has to pay for gas.\n opReverted,\n // Only used internally in the EntryPoint (cleanup after postOp reverts). Never calling paymaster with this value\n postOpReverted\n }\n\n /**\n * Payment validation: check if paymaster agrees to pay.\n * Must verify sender is the entryPoint.\n * Revert to reject this request.\n * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted).\n * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.\n * @param userOp - The user operation.\n * @param userOpHash - Hash of the user's request data.\n * @param maxCost - The maximum cost of this transaction (based on maximum gas and gas price from userOp).\n * @return context - Value to send to a postOp. Zero length to signify postOp is not required.\n * @return validationData - Signature and time-range of this operation, encoded the same as the return\n * value of validateUserOperation.\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * other values are invalid for paymaster.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validatePaymasterUserOp(\n PackedUserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) external returns (bytes memory context, uint256 validationData);\n\n /**\n * Post-operation handler.\n * Must verify sender is the entryPoint.\n * @param mode - Enum with the following options:\n * opSucceeded - User operation succeeded.\n * opReverted - User op reverted. The paymaster still has to pay for gas.\n * postOpReverted - never passed in a call to postOp().\n * @param context - The context value returned by validatePaymasterUserOp\n * @param actualGasCost - Actual gas used so far (without this postOp call).\n * @param actualUserOpFeePerGas - the gas price this UserOp pays. This value is based on the UserOp's maxFeePerGas\n * and maxPriorityFee (and basefee)\n * It is not the same as tx.gasprice, which is what the bundler pays.\n */\n function postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost,\n uint256 actualUserOpFeePerGas\n ) external;\n}\n"
|
|
359
|
+
},
|
|
360
|
+
"project/contracts/interfaces/IQorumsToken.sol": {
|
|
361
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n\r\n/**\r\n * @title IPopcornsToken\r\n * @notice Interfaz para el token POPCORNS con supply fijo de 1B.\r\n * \r\n * MODELO DE CIRCULACIÓN:\r\n * - Supply Total: 1,000,000,000 POPCORNS (FIJO, NUNCA CAMBIA)\r\n * - \"Liberar\" = Transferir desde RESERVA → Circulación\r\n * - \"Retornar\" = Transferir desde Circulación → RESERVA\r\n * \r\n * NO HAY MINT NI BURN REAL - Solo transferencias desde/hacia la reserva.\r\n */\r\ninterface IQorumsToken is IERC20 {\r\n /**\r\n * @notice Libera tokens desde la reserva hacia un destinatario.\r\n * @param to Destinatario de los tokens.\r\n * @param amount Cantidad de tokens a liberar.\r\n */\r\n function releaseFromReserve(address to, uint256 amount) external;\r\n \r\n /**\r\n * @notice Retorna tokens a la reserva (simula \"burn\" retirando de circulación).\r\n * @param amount Cantidad de tokens a retornar a la reserva.\r\n */\r\n function returnToReserve(uint256 amount) external;\r\n \r\n /**\r\n * @notice Devuelve la dirección de la wallet de reserva.\r\n * @return Dirección de la reserva.\r\n */\r\n function reserve() external view returns (address);\r\n \r\n /**\r\n * @notice Devuelve la cantidad de tokens en la reserva (fuera de circulación).\r\n * @return Balance de la wallet de reserva.\r\n */\r\n function getReserveBalance() external view returns (uint256);\r\n \r\n /**\r\n * @notice Devuelve la cantidad de tokens en circulación.\r\n * @return Total supply menos balance de reserva.\r\n */\r\n function getCirculatingSupply() external view returns (uint256);\r\n}"
|
|
362
|
+
},
|
|
363
|
+
"project/contracts/interfaces/IStakeManager.sol": {
|
|
364
|
+
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.5;\n\n/**\n * Manage deposits and stakes.\n * Deposit is just a balance used to pay for UserOperations (either by a paymaster or an account).\n * Stake is value locked for at least \"unstakeDelay\" by the staked entity.\n */\ninterface IStakeManager {\n event Deposited(address indexed account, uint256 totalDeposit);\n\n event Withdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n // Emitted when stake or unstake delay are modified.\n event StakeLocked(\n address indexed account,\n uint256 totalStaked,\n uint256 unstakeDelaySec\n );\n\n // Emitted once a stake is scheduled for withdrawal.\n event StakeUnlocked(address indexed account, uint256 withdrawTime);\n\n event StakeWithdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /**\n * @param deposit - The entity's deposit.\n * @param staked - True if this entity is staked.\n * @param stake - Actual amount of ether staked for this entity.\n * @param unstakeDelaySec - Minimum delay to withdraw the stake.\n * @param withdrawTime - First block timestamp where 'withdrawStake' will be callable, or zero if already locked.\n * @dev Sizes were chosen so that deposit fits into one cell (used during handleOp)\n * and the rest fit into a 2nd cell (used during stake/unstake)\n * - 112 bit allows for 10^15 eth\n * - 48 bit for full timestamp\n * - 32 bit allows 150 years for unstake delay\n */\n struct DepositInfo {\n uint256 deposit;\n bool staked;\n uint112 stake;\n uint32 unstakeDelaySec;\n uint48 withdrawTime;\n }\n\n // API struct used by getStakeInfo and simulateValidation.\n struct StakeInfo {\n uint256 stake;\n uint256 unstakeDelaySec;\n }\n\n /**\n * Get deposit info.\n * @param account - The account to query.\n * @return info - Full deposit information of given account.\n */\n function getDepositInfo(\n address account\n ) external view returns (DepositInfo memory info);\n\n /**\n * Get account balance.\n * @param account - The account to query.\n * @return - The deposit (for gas payment) of the account.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * Add to the deposit of the given account.\n * @param account - The account to add to.\n */\n function depositTo(address account) external payable;\n\n /**\n * Add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param _unstakeDelaySec - The new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 _unstakeDelaySec) external payable;\n\n /**\n * Attempt to unlock the stake.\n * The value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external;\n\n /**\n * Withdraw from the (unlocked) stake.\n * Must first call unlockStake and wait for the unstakeDelay to pass.\n * @param withdrawAddress - The address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external;\n\n /**\n * Withdraw from the deposit.\n * @param withdrawAddress - The address to send withdrawn value.\n * @param withdrawAmount - The amount to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 withdrawAmount\n ) external;\n}\n"
|
|
365
|
+
},
|
|
366
|
+
"project/contracts/interfaces/PackedUserOperation.sol": {
|
|
367
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.5;\n\n/**\n * User Operation struct\n * @param sender - The sender account of this request.\n * @param nonce - Unique value the sender uses to verify it is not a replay.\n * @param initCode - If set, the account contract will be created by this constructor/\n * @param callData - The method call to execute on this account.\n * @param accountGasLimits - Packed gas limits for validateUserOp and gas limit passed to the callData method call.\n * @param preVerificationGas - Gas not calculated by the handleOps method, but added to the gas paid.\n * Covers batch overhead.\n * @param gasFees - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.\n * @param paymasterAndData - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data\n * The paymaster will pay for the transaction instead of the sender.\n * @param signature - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.\n */\nstruct PackedUserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n bytes32 accountGasLimits;\n uint256 preVerificationGas;\n bytes32 gasFees;\n bytes paymasterAndData;\n bytes signature;\n}\n"
|
|
368
|
+
},
|
|
369
|
+
"project/contracts/kernel/LinealEconomy.sol": {
|
|
370
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\r\npragma solidity ^0.8.30;\r\n\r\nimport \"../governance/LinealQorum.sol\";\r\n\r\n/**\r\n * Neoquor - Tech Artisan\r\n * @title LinealEconomicKernel - Lineal Qorum Finternet\r\n * @notice Low Life, High Tech - Todos los derechos reservados.\r\n */\r\ncontract LinealEconomicKernel is LinealQorum {\r\n mapping(address => bool) public authorizedIssuers;\r\n mapping(address => bool) public officialBanks;\r\n\r\n event IssuerAuthorized(address indexed issuer);\r\n event IssuerDeauthorized(address indexed issuer);\r\n event BankRegistered(address indexed bank);\r\n\r\n constructor(\r\n address[] memory _machines,\r\n uint256 _requiredMachines,\r\n address[] memory _institutions,\r\n uint256 _requiredInstitutions,\r\n address[] memory _humans,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryQuorum\r\n ) {}\r\n\r\n\r\n /**\r\n * @notice Autoriza a un contrato (ej. un Liquidity Locker) a liberar tokens.\r\n */\r\n function authorizeIssuer(address _issuer) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\"authorizeIssuer\", abi.encode(_issuer));\r\n if (!confirmServers(txHash, \"authorizeIssuer\")) return;\r\n authorizedIssuers[_issuer] = true;\r\n emit IssuerAuthorized(_issuer);\r\n }\r\n\r\n /**\r\n * @notice Revoca la autorización de emisión.\r\n */\r\n function deauthorizeIssuer(address _issuer) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\"deauthorizeIssuer\", abi.encode(_issuer));\r\n if (!confirmServers(txHash, \"deauthorizeIssuer\")) return;\r\n authorizedIssuers[_issuer] = false;\r\n emit IssuerDeauthorized(_issuer);\r\n }\r\n\r\n /**\r\n * @notice Registra un banco como oficial del sistema.\r\n */\r\n function registerBank(address _bank) external onlyServers {\r\n bytes32 txHash = _computeActionHash(\"addDimension\", abi.encode(_bank));\r\n if (!confirmServers(txHash, \"addDimension\")) return;\r\n officialBanks[_bank] = true;\r\n emit BankRegistered(_bank);\r\n }\r\n\r\n /**\r\n * @notice Verifica si un caller está autorizado para operar sobre la economía.\r\n */\r\n function isAuthorized(address _account) external view returns (bool) {\r\n return authorizedIssuers[_account] || officialBanks[_account];\r\n }\r\n}"
|
|
371
|
+
},
|
|
372
|
+
"project/contracts/social/LinealStorage.sol": {
|
|
373
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\r\npragma solidity >=0.8.2 <0.9.0;\r\n\r\nimport \"../governance/LinealQorum.sol\";\r\n\r\n/**\r\n * @title PostBoard\r\n * @dev Tablero de publicaciones (\"posts\") respaldado por un mapa (mapping) on-chain,\r\n * protegido por el sistema de quorum multi-nivel de LinealQorum\r\n * (máquinas, instituciones, humanos) para las acciones sensibles\r\n * (crear, editar, eliminar, moderar).\r\n *\r\n * @custom:dev-run-script ./scripts/deploy_with_ethers.ts\r\n */\r\ncontract PostBoard is LinealQorum {\r\n\r\n // ---------------------------------------------------------------------\r\n // Tipos de datos\r\n // ---------------------------------------------------------------------\r\n\r\n address private owner;\r\n\r\n // event for EVM logging\r\n event OwnerSet(address indexed oldOwner, address indexed newOwner);\r\n\r\n /**\r\n * @dev Return owner address\r\n * @return address of owner\r\n */\r\n\r\n /// @dev Estructura que representa un post individual\r\n struct Post {\r\n uint256 id;\r\n address author;\r\n string title;\r\n string content;\r\n string[] tags;\r\n uint256 createdAt;\r\n uint256 updatedAt;\r\n bool exists;\r\n bool isHidden;\r\n uint256 likeCount;\r\n }\r\n\r\n /// @dev Estructura para un comentario asociado a un post\r\n struct Comment {\r\n uint256 id;\r\n uint256 postId;\r\n address author;\r\n string content;\r\n uint256 createdAt;\r\n bool exists;\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Almacenamiento (el \"mapa\")\r\n // ---------------------------------------------------------------------\r\n\r\n /// @dev Mapa principal: id de post => Post\r\n mapping(uint256 => Post) private posts;\r\n\r\n /// @dev Mapa de comentarios: id de comentario => Comment\r\n mapping(uint256 => Comment) private comments;\r\n\r\n /// @dev Mapa de comentarios por post: postId => arreglo de commentIds\r\n mapping(uint256 => uint256[]) private postComments;\r\n\r\n /// @dev Mapa de posts por autor: address => arreglo de postIds\r\n mapping(address => uint256[]) private postsByAuthor;\r\n\r\n /// @dev Mapa de \"me gusta\" para evitar likes duplicados: postId => (address => bool)\r\n mapping(uint256 => mapping(address => bool)) private hasLiked;\r\n\r\n /// @dev Lista de todos los ids de post existentes (para enumeración)\r\n uint256[] private allPostIds;\r\n\r\n /// @dev Contadores incrementales\r\n uint256 private nextPostId;\r\n uint256 private nextCommentId;\r\n\r\n // ---------------------------------------------------------------------\r\n // Eventos\r\n // ---------------------------------------------------------------------\r\n\r\n event PostCreated(uint256 indexed id, address indexed author, string title, uint256 timestamp);\r\n event PostUpdated(uint256 indexed id, address indexed editor, uint256 timestamp);\r\n event PostDeleted(uint256 indexed id, address indexed remover, uint256 timestamp);\r\n event PostHiddenStatusChanged(uint256 indexed id, bool isHidden, address indexed moderator);\r\n event PostLiked(uint256 indexed id, address indexed liker, uint256 newLikeCount);\r\n event CommentAdded(uint256 indexed commentId, uint256 indexed postId, address indexed author);\r\n event CommentRemoved(uint256 indexed commentId, uint256 indexed postId, address indexed remover);\r\n\r\n // ---------------------------------------------------------------------\r\n // Errores personalizados\r\n // ---------------------------------------------------------------------\r\n\r\n error PostDoesNotExist(uint256 id);\r\n error CommentDoesNotExist(uint256 id);\r\n error NotPostAuthor(address caller, address author);\r\n error AlreadyLiked(address liker, uint256 postId);\r\n error EmptyTitleOrContent();\r\n error QuorumNotReached(bytes32 txHash, string action);\r\n\r\n // ---------------------------------------------------------------------\r\n // Modificadores\r\n // ---------------------------------------------------------------------\r\n\r\n modifier postExists(uint256 _id) {\r\n if (!posts[_id].exists) revert PostDoesNotExist(_id);\r\n _;\r\n }\r\n\r\n modifier commentExists(uint256 _id) {\r\n if (!comments[_id].exists) revert CommentDoesNotExist(_id);\r\n _;\r\n }\r\n\r\n modifier onlyPostAuthor(uint256 _id) {\r\n if (posts[_id].author != msg.sender) revert NotPostAuthor(msg.sender, posts[_id].author);\r\n _;\r\n }\r\n\r\n // modifier to check if caller is owner\r\n modifier isOwner() {\r\n // If the first argument of 'require' evaluates to 'false', execution terminates and all\r\n // changes to the state and to Ether balances are reverted.\r\n // This used to consume all gas in old EVM versions, but not anymore.\r\n // It is often a good idea to use 'require' to check if functions are called correctly.\r\n // As a second argument, you can also provide an explanation about what went wrong.\r\n require(msg.sender == owner, \"Caller is not owner\");\r\n _;\r\n }\r\n\r\n constructor(\r\n address _owner,\r\n address[] memory _machines,\r\n uint256 _requiredMachines,\r\n address[] memory _institutions,\r\n uint256 _requiredInstitutions,\r\n address[] memory _humans,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryRequired\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryRequired\r\n ) {\r\n owner = _owner; // 'msg.sender' is sender of current call, contract deployer for a constructor\r\n emit OwnerSet(address(0), owner);\r\n nextPostId = 1;\r\n nextCommentId = 1;\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Creación y edición de posts (sin quorum: acción normal de usuario)\r\n // ---------------------------------------------------------------------\r\n\r\n /**\r\n * @notice Crea un nuevo post y lo guarda en el mapa.\r\n * @param _title Título del post.\r\n * @param _content Contenido del post.\r\n * @param _tags Etiquetas asociadas al post.\r\n * @return id El identificador del post recién creado.\r\n */\r\n function createPost(\r\n string calldata _title,\r\n string calldata _content,\r\n string[] calldata _tags\r\n ) external isOwner returns (uint256 id) {\r\n if (bytes(_title).length == 0 || bytes(_content).length == 0) {\r\n revert EmptyTitleOrContent();\r\n }\r\n\r\n id = nextPostId;\r\n nextPostId++;\r\n\r\n Post storage p = posts[id];\r\n p.id = id;\r\n p.author = msg.sender;\r\n p.title = _title;\r\n p.content = _content;\r\n p.createdAt = block.timestamp;\r\n p.updatedAt = block.timestamp;\r\n p.exists = true;\r\n p.isHidden = false;\r\n p.likeCount = 0;\r\n\r\n for (uint256 i = 0; i < _tags.length; i++) {\r\n p.tags.push(_tags[i]);\r\n }\r\n\r\n allPostIds.push(id);\r\n postsByAuthor[msg.sender].push(id);\r\n\r\n emit PostCreated(id, msg.sender, _title, block.timestamp);\r\n }\r\n\r\n /**\r\n * @notice Edita un post existente. Solo el autor puede editarlo directamente.\r\n */\r\n function editPost(\r\n uint256 _id,\r\n string calldata _newTitle,\r\n string calldata _newContent\r\n ) external isOwner postExists(_id) onlyPostAuthor(_id) {\r\n if (bytes(_newTitle).length == 0 || bytes(_newContent).length == 0) {\r\n revert EmptyTitleOrContent();\r\n }\r\n\r\n Post storage p = posts[_id];\r\n p.title = _newTitle;\r\n p.content = _newContent;\r\n p.updatedAt = block.timestamp;\r\n\r\n emit PostUpdated(_id, msg.sender, block.timestamp);\r\n }\r\n\r\n /**\r\n * @notice El propio autor elimina (lógicamente) su post.\r\n */\r\n function deleteOwnPost(uint256 _id) external isOwner postExists(_id) {\r\n _removePost(_id);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Acciones sensibles protegidas por quorum (servidores / moderación)\r\n // ---------------------------------------------------------------------\r\n\r\n /**\r\n * @notice Elimina un post mediante confirmación de quorum de servidores,\r\n * útil para moderación forzada cuando el autor no coopera.\r\n */\r\n function moderateDeletePost(uint256 _id) external onlyServers postExists(_id) {\r\n bytes32 txHash = _computeActionHash(\"moderateDeletePost\", abi.encode(_id));\r\n if (!confirmServers(txHash, \"moderateDeletePost\")) {\r\n revert QuorumNotReached(txHash, \"moderateDeletePost\");\r\n }\r\n _removePost(_id);\r\n }\r\n\r\n\r\n /**\r\n * @notice Elimina un comentario mediante confirmación de quorum.\r\n */\r\n function moderateRemoveComment(uint256 _commentId) external onlyServers commentExists(_commentId) {\r\n bytes32 txHash = _computeActionHash(\"moderateRemoveComment\", abi.encode(_commentId));\r\n if (!confirmServers(txHash, \"moderateRemoveComment\")) {\r\n revert QuorumNotReached(txHash, \"moderateRemoveComment\");\r\n }\r\n _removeComment(_commentId);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Interacciones sociales: likes y comentarios\r\n // ---------------------------------------------------------------------\r\n\r\n /**\r\n * @notice Da \"me gusta\" a un post. Cada dirección solo puede dar like una vez.\r\n */\r\n function likePost(uint256 _id) external postExists(_id) {\r\n if (hasLiked[_id][msg.sender]) revert AlreadyLiked(msg.sender, _id);\r\n\r\n hasLiked[_id][msg.sender] = true;\r\n posts[_id].likeCount += 1;\r\n\r\n emit PostLiked(_id, msg.sender, posts[_id].likeCount);\r\n }\r\n\r\n /**\r\n * @notice Agrega un comentario a un post existente.\r\n */\r\n function addComment(uint256 _postId, string calldata _content)\r\n external\r\n postExists(_postId)\r\n returns (uint256 commentId)\r\n {\r\n if (bytes(_content).length == 0) revert EmptyTitleOrContent();\r\n\r\n commentId = nextCommentId;\r\n nextCommentId++;\r\n\r\n comments[commentId] = Comment({\r\n id: commentId,\r\n postId: _postId,\r\n author: msg.sender,\r\n content: _content,\r\n createdAt: block.timestamp,\r\n exists: true\r\n });\r\n\r\n postComments[_postId].push(commentId);\r\n\r\n emit CommentAdded(commentId, _postId, msg.sender);\r\n }\r\n\r\n /**\r\n * @notice El autor de un comentario puede eliminarlo directamente.\r\n */\r\n function removeOwnComment(uint256 _commentId) external commentExists(_commentId) {\r\n if (comments[_commentId].author != msg.sender) {\r\n revert NotPostAuthor(msg.sender, comments[_commentId].author);\r\n }\r\n _removeComment(_commentId);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Funciones internas auxiliares\r\n // ---------------------------------------------------------------------\r\n\r\n function _removePost(uint256 _id) internal {\r\n posts[_id].exists = false;\r\n\r\n uint256[] storage ids = postComments[_id];\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n comments[ids[i]].exists = false;\r\n }\r\n\r\n emit PostDeleted(_id, msg.sender, block.timestamp);\r\n }\r\n\r\n function _removeComment(uint256 _commentId) internal {\r\n uint256 postId = comments[_commentId].postId;\r\n comments[_commentId].exists = false;\r\n emit CommentRemoved(_commentId, postId, msg.sender);\r\n }\r\n\r\n // ---------------------------------------------------------------------\r\n // Funciones de lectura (view)\r\n // ---------------------------------------------------------------------\r\n\r\n /// @notice Devuelve un post completo por id.\r\n function getPost(uint256 _id)\r\n external\r\n view\r\n postExists(_id)\r\n returns (\r\n uint256 id,\r\n address author,\r\n string memory title,\r\n string memory content,\r\n string[] memory tags,\r\n uint256 createdAt,\r\n uint256 updatedAt,\r\n bool isHidden,\r\n uint256 likeCount\r\n )\r\n {\r\n Post storage p = posts[_id];\r\n return (\r\n p.id,\r\n p.author,\r\n p.title,\r\n p.content,\r\n p.tags,\r\n p.createdAt,\r\n p.updatedAt,\r\n p.isHidden,\r\n p.likeCount\r\n );\r\n }\r\n\r\n /// @notice Devuelve los ids de todos los posts creados (incluidos los borrados lógicamente).\r\n function getAllPostIds() external view returns (uint256[] memory) {\r\n return allPostIds;\r\n }\r\n\r\n /// @notice Devuelve los ids de los posts creados por un autor específico.\r\n function getPostsByAuthor(address _author) external view returns (uint256[] memory) {\r\n return postsByAuthor[_author];\r\n }\r\n\r\n /// @notice Devuelve los ids de los comentarios de un post.\r\n function getCommentIdsForPost(uint256 _postId) external view postExists(_postId) returns (uint256[] memory) {\r\n return postComments[_postId];\r\n }\r\n\r\n /// @notice Devuelve el detalle de un comentario.\r\n function getComment(uint256 _commentId)\r\n external\r\n view\r\n commentExists(_commentId)\r\n returns (\r\n uint256 id,\r\n uint256 postId,\r\n address author,\r\n string memory content,\r\n uint256 createdAt\r\n )\r\n {\r\n Comment storage c = comments[_commentId];\r\n return (c.id, c.postId, c.author, c.content, c.createdAt);\r\n }\r\n\r\n /// @notice Devuelve una página de posts, útil para no traer todo el mapa de una vez.\r\n function getPostsPaginated(uint256 _offset, uint256 _limit)\r\n external\r\n view\r\n returns (Post[] memory page)\r\n {\r\n uint256 total = allPostIds.length;\r\n if (_offset >= total) {\r\n return new Post[](0);\r\n }\r\n\r\n uint256 end = _offset + _limit;\r\n if (end > total) {\r\n end = total;\r\n }\r\n\r\n page = new Post[](end - _offset);\r\n for (uint256 i = _offset; i < end; i++) {\r\n page[i - _offset] = posts[allPostIds[i]];\r\n }\r\n return page;\r\n }\r\n\r\n /// @notice Indica si una dirección ya dio like a un post.\r\n function didLike(uint256 _postId, address _user) external view returns (bool) {\r\n return hasLiked[_postId][_user];\r\n }\r\n\r\n /// @notice Devuelve el número total de posts creados (incluye eliminados lógicamente).\r\n function totalPostsCreated() external view returns (uint256) {\r\n return nextPostId - 1;\r\n }\r\n\r\n /// @notice Devuelve el número total de comentarios creados.\r\n function totalCommentsCreated() external view returns (uint256) {\r\n return nextCommentId - 1;\r\n }\r\n\r\n function getOwner() external view returns (address) {\r\n return owner;\r\n }\r\n}\r\n"
|
|
374
|
+
},
|
|
375
|
+
"project/contracts/test.sol": {
|
|
376
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\r\n\r\npragma solidity >=0.8.2 <0.9.0;\r\n\r\n\r\nimport \"./governance/LinealQorum.sol\";\r\n/**\r\n * @title LinealSecureStorage\r\n * @dev A simple contract that use LinealQorum to store and retrieve a number securely.\r\n */\r\n\r\ncontract LinealSecureStorage is LinealQorum {\r\n uint256 private number;\r\n constructor(\r\n address[] memory _machines,\r\n uint256 _requiredMachines,\r\n address[] memory _institutions,\r\n uint256 _requiredInstitutions,\r\n address[] memory _humans,\r\n uint256 _requiredHumans,\r\n uint256 _recoveryQuorum\r\n ) LinealQorum(\r\n _machines,\r\n _requiredMachines,\r\n _institutions,\r\n _requiredInstitutions,\r\n _humans,\r\n _requiredHumans,\r\n _recoveryQuorum\r\n ) {}\r\n\r\n /**\r\n * @dev Store value in variable\r\n * @param num value to store\r\n */\r\n function store(uint256 num) public onlyServers {\r\n bytes32 txHash = _computeActionHash(\"store\", abi.encode(num));\r\n if (!confirmServers(txHash, \"store\")) return;\r\n number = num;\r\n }\r\n\r\n /**\r\n * @dev Return value\r\n * @return value of 'number'\r\n */\r\n function retrieve() public onlyServers returns (uint256){\r\n bytes32 txHash = _computeActionHash(\"retrieve\", \"\");\r\n if (!confirmServers(txHash, \"retrieve\")) return 0;\r\n return number;\r\n }\r\n}"
|
|
377
|
+
},
|
|
378
|
+
"project/contracts/utils/Exec.sol": {
|
|
379
|
+
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity ^0.8.23;\n\n// solhint-disable no-inline-assembly\n\n/**\n * Utility functions helpful when making different kinds of contract calls in Solidity.\n */\nlibrary Exec {\n\n function call(\n address to,\n uint256 value,\n bytes memory data,\n uint256 txGas\n ) internal returns (bool success) {\n assembly (\"memory-safe\") {\n success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)\n }\n }\n\n function staticcall(\n address to,\n bytes memory data,\n uint256 txGas\n ) internal view returns (bool success) {\n assembly (\"memory-safe\") {\n success := staticcall(txGas, to, add(data, 0x20), mload(data), 0, 0)\n }\n }\n\n function delegateCall(\n address to,\n bytes memory data,\n uint256 txGas\n ) internal returns (bool success) {\n assembly (\"memory-safe\") {\n success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)\n }\n }\n\n // get returned data from last call or calldelegate\n function getReturnData(uint256 maxLen) internal pure returns (bytes memory returnData) {\n assembly (\"memory-safe\") {\n let len := returndatasize()\n if gt(len, maxLen) {\n len := maxLen\n }\n let ptr := mload(0x40)\n mstore(0x40, add(ptr, add(len, 0x20)))\n mstore(ptr, len)\n returndatacopy(add(ptr, 0x20), 0, len)\n returnData := ptr\n }\n }\n\n // revert with explicit byte array (probably reverted info from call)\n function revertWithData(bytes memory returnData) internal pure {\n assembly (\"memory-safe\") {\n revert(add(returnData, 32), mload(returnData))\n }\n }\n\n function callAndRevert(address to, bytes memory data, uint256 maxLen) internal {\n bool success = call(to,0,data,gasleft());\n if (!success) {\n revertWithData(getReturnData(maxLen));\n }\n }\n}\n"
|
|
380
|
+
},
|
|
381
|
+
"project/contracts/utils/IOracle.sol": {
|
|
382
|
+
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.23;\n\ninterface IOracle {\n function decimals() external view returns (uint8);\n function latestRoundData()\n external\n view\n returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);\n}\n"
|
|
383
|
+
},
|
|
384
|
+
"project/contracts/utils/OracleHelper.sol": {
|
|
385
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable not-rely-on-time */\n\nimport \"./IOracle.sol\";\n\n/// @title Helper functions for dealing with various forms of price feed oracles.\n/// @notice Maintains a price cache and updates the current price if needed.\n/// In the best case scenario we have a direct oracle from the token to the native asset.\n/// Also support tokens that have no direct price oracle to the native asset.\n/// Sometimes oracles provide the price in the opposite direction of what we need in the moment.\nabstract contract OracleHelper {\n\n event TokenPriceUpdated(uint256 currentPrice, uint256 previousPrice, uint256 cachedPriceTimestamp);\n\n uint256 private constant PRICE_DENOMINATOR = 1e26;\n\n struct OracleHelperConfig {\n\n /// @notice The price cache will be returned without even fetching the oracles for this number of seconds\n uint48 cacheTimeToLive;\n\n /// @notice The maximum acceptable age of the price oracle round\n uint48 maxOracleRoundAge;\n\n /// @notice The Oracle contract used to fetch the latest token prices\n IOracle tokenOracle;\n\n /// @notice The Oracle contract used to fetch the latest native asset prices. Only needed if tokenToNativeOracle flag is not set.\n IOracle nativeOracle;\n\n /// @notice If 'true' we will fetch price directly from tokenOracle\n /// @notice If 'false' we will use nativeOracle to establish a token price through a shared third currency\n bool tokenToNativeOracle;\n\n /// @notice 'false' if price is bridging-asset-per-token (or native-asset-per-token), 'true' if price is tokens-per-bridging-asset\n bool tokenOracleReverse;\n\n /// @notice 'false' if price is bridging-asset-per-native-asset, 'true' if price is native-asset-per-bridging-asset\n bool nativeOracleReverse;\n\n /// @notice The price update threshold percentage from PRICE_DENOMINATOR that triggers a price update (1e26 = 100%)\n uint256 priceUpdateThreshold;\n\n }\n\n /// @notice The cached token price from the Oracle, always in (native-asset-per-token) * PRICE_DENOMINATOR format\n uint256 public cachedPrice;\n\n /// @notice The timestamp of a block when the cached price was updated\n uint48 public cachedPriceTimestamp;\n\n OracleHelperConfig private oracleHelperConfig;\n\n /// @notice The \"10^(tokenOracle.decimals)\" value used for the price calculation\n uint128 private tokenOracleDecimalPower;\n\n /// @notice The \"10^(nativeOracle.decimals)\" value used for the price calculation\n uint128 private nativeOracleDecimalPower;\n\n constructor (\n OracleHelperConfig memory _oracleHelperConfig\n ) {\n cachedPrice = type(uint256).max; // initialize the storage slot to invalid value\n _setOracleConfiguration(\n _oracleHelperConfig\n );\n }\n\n function _setOracleConfiguration(\n OracleHelperConfig memory _oracleHelperConfig\n ) private {\n oracleHelperConfig = _oracleHelperConfig;\n require(_oracleHelperConfig.priceUpdateThreshold <= PRICE_DENOMINATOR, \"TPM: update threshold too high\");\n tokenOracleDecimalPower = uint128(10 ** oracleHelperConfig.tokenOracle.decimals());\n if (oracleHelperConfig.tokenToNativeOracle) {\n require(address(oracleHelperConfig.nativeOracle) == address(0), \"TPM: native oracle must be zero\");\n nativeOracleDecimalPower = 1;\n } else {\n nativeOracleDecimalPower = uint128(10 ** oracleHelperConfig.nativeOracle.decimals());\n }\n }\n\n /// @notice Updates the token price by fetching the latest price from the Oracle.\n /// @param force true to force cache update, even if called after short time or the change is lower than the update threshold.\n /// @return newPrice the new cached token price\n function updateCachedPrice(bool force) public returns (uint256) {\n uint256 cacheTimeToLive = oracleHelperConfig.cacheTimeToLive;\n uint256 cacheAge = block.timestamp - cachedPriceTimestamp;\n if (!force && cacheAge <= cacheTimeToLive) {\n return cachedPrice;\n }\n uint256 priceUpdateThreshold = oracleHelperConfig.priceUpdateThreshold;\n IOracle tokenOracle = oracleHelperConfig.tokenOracle;\n IOracle nativeOracle = oracleHelperConfig.nativeOracle;\n\n uint256 _cachedPrice = cachedPrice;\n uint256 tokenPrice = fetchPrice(tokenOracle);\n uint256 nativeAssetPrice = 1;\n // If the 'TokenOracle' returns the price in the native asset units there is no need to fetch native asset price\n if (!oracleHelperConfig.tokenToNativeOracle) {\n nativeAssetPrice = fetchPrice(nativeOracle);\n }\n uint256 newPrice = calculatePrice(\n tokenPrice,\n nativeAssetPrice,\n oracleHelperConfig.tokenOracleReverse,\n oracleHelperConfig.nativeOracleReverse\n );\n uint256 priceRatio = PRICE_DENOMINATOR * newPrice / _cachedPrice;\n bool updateRequired = force ||\n priceRatio > PRICE_DENOMINATOR + priceUpdateThreshold ||\n priceRatio < PRICE_DENOMINATOR - priceUpdateThreshold;\n if (!updateRequired) {\n return _cachedPrice;\n }\n cachedPrice = newPrice;\n cachedPriceTimestamp = uint48(block.timestamp);\n emit TokenPriceUpdated(newPrice, _cachedPrice, cachedPriceTimestamp);\n return newPrice;\n }\n\n /**\n * Calculate the effective price of the selected token denominated in native asset.\n *\n * @param tokenPrice - the price of the token relative to a native asset or a bridging asset like the U.S. dollar.\n * @param nativeAssetPrice - the price of the native asset relative to a bridging asset or 1 if no bridging needed.\n * @param tokenOracleReverse - flag indicating direction of the \"tokenPrice\".\n * @param nativeOracleReverse - flag indicating direction of the \"nativeAssetPrice\".\n * @return the native-asset-per-token price multiplied by the PRICE_DENOMINATOR constant.\n */\n function calculatePrice(\n uint256 tokenPrice,\n uint256 nativeAssetPrice,\n bool tokenOracleReverse,\n bool nativeOracleReverse\n ) private view returns (uint256){\n // tokenPrice is normalized as bridging-asset-per-token\n if (tokenOracleReverse) {\n // inverting tokenPrice that was tokens-per-bridging-asset (or tokens-per-native-asset)\n tokenPrice = PRICE_DENOMINATOR * tokenOracleDecimalPower / tokenPrice;\n } else {\n // tokenPrice already bridging-asset-per-token (or native-asset-per-token)\n tokenPrice = PRICE_DENOMINATOR * tokenPrice / tokenOracleDecimalPower;\n }\n\n if (nativeOracleReverse) {\n // multiplying by nativeAssetPrice that is native-asset-per-bridging-asset\n // => result = (bridging-asset / token) * (native-asset / bridging-asset) = native-asset / token\n return nativeAssetPrice * tokenPrice / nativeOracleDecimalPower;\n } else {\n // dividing by nativeAssetPrice that is bridging-asset-per-native-asset\n // => result = (bridging-asset / token) / (bridging-asset / native-asset) = native-asset / token\n return tokenPrice * nativeOracleDecimalPower / nativeAssetPrice;\n }\n }\n\n /// @notice Fetches the latest price from the given Oracle.\n /// @dev This function is used to get the latest price from the tokenOracle or nativeOracle.\n /// @param _oracle The Oracle contract to fetch the price from.\n /// @return price The latest price fetched from the Oracle.\n function fetchPrice(IOracle _oracle) internal view returns (uint256 price) {\n (uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) = _oracle.latestRoundData();\n require(answer > 0, \"TPM: Chainlink price <= 0\");\n require(updatedAt >= block.timestamp - oracleHelperConfig.maxOracleRoundAge, \"TPM: Incomplete round\");\n require(answeredInRound >= roundId, \"TPM: Stale price\");\n price = uint256(answer);\n }\n}\n"
|
|
386
|
+
},
|
|
387
|
+
"project/contracts/utils/UniswapHelper.sol": {
|
|
388
|
+
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.23;\n\n/* solhint-disable not-rely-on-time */\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol\";\nimport \"@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol\";\n\nabstract contract UniswapHelper {\n event UniswapReverted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMin);\n\n uint256 private constant PRICE_DENOMINATOR = 1e26;\n\n struct UniswapHelperConfig {\n /// @notice Minimum native asset amount to receive from a single swap\n uint256 minSwapAmount;\n\n uint24 uniswapPoolFee;\n\n uint8 slippage;\n }\n\n /// @notice The Uniswap V3 SwapRouter contract\n ISwapRouter public immutable uniswap;\n\n /// @notice The ERC20 token used for transaction fee payments\n IERC20 public immutable token;\n\n /// @notice The ERC-20 token that wraps the native asset for current chain\n IERC20 public immutable wrappedNative;\n\n UniswapHelperConfig private uniswapHelperConfig;\n\n constructor(\n IERC20 _token,\n IERC20 _wrappedNative,\n ISwapRouter _uniswap,\n UniswapHelperConfig memory _uniswapHelperConfig\n ){\n _token.approve(address(_uniswap), type(uint256).max);\n token = _token;\n wrappedNative = _wrappedNative;\n uniswap = _uniswap;\n _setUniswapHelperConfiguration(_uniswapHelperConfig);\n }\n\n function _setUniswapHelperConfiguration(UniswapHelperConfig memory _uniswapHelperConfig) internal {\n uniswapHelperConfig = _uniswapHelperConfig;\n }\n\n function _maybeSwapTokenToWeth(IERC20 tokenIn, uint256 quote) internal returns (uint256) {\n uint256 tokenBalance = tokenIn.balanceOf(address(this));\n uint256 amountOutMin = addSlippage(tokenToWei(tokenBalance, quote), uniswapHelperConfig.slippage);\n if (amountOutMin < uniswapHelperConfig.minSwapAmount) {\n return 0;\n }\n // note: calling 'swapToToken' but destination token is Wrapped Ether\n return swapToToken(\n address(tokenIn),\n address(wrappedNative),\n tokenBalance,\n amountOutMin,\n uniswapHelperConfig.uniswapPoolFee\n );\n }\n\n function addSlippage(uint256 amount, uint8 slippage) private pure returns (uint256) {\n return amount * (1000 - slippage) / 1000;\n }\n\n\n function tokenToWei(uint256 amount, uint256 price) public pure returns (uint256) {\n return amount * price / PRICE_DENOMINATOR;\n }\n\n function weiToToken(uint256 amount, uint256 price) public pure returns (uint256) {\n return amount * PRICE_DENOMINATOR / price;\n }\n\n function unwrapWeth(uint256 amount) internal {\n IPeripheryPayments(address(uniswap)).unwrapWETH9(amount, address(this));\n }\n\n // swap ERC-20 tokens at market price\n function swapToToken(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMin,\n uint24 fee\n ) internal returns (uint256 amountOut) {\n ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(\n tokenIn, //tokenIn\n tokenOut, //tokenOut\n fee,\n address(uniswap),\n block.timestamp, //deadline\n amountIn,\n amountOutMin,\n 0\n );\n try uniswap.exactInputSingle(params) returns (uint256 _amountOut) {\n amountOut = _amountOut;\n } catch {\n emit UniswapReverted(tokenIn, tokenOut, amountIn, amountOutMin);\n amountOut = 0;\n }\n }\n}\n"
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|