├── .gitattributes ├── LICENSE ├── README.md ├── audit ├── Cairo_and_SHARP_Verifiers_v3.0_Audit_Report.pdf ├── EVM_STARK_Verifier_v4.0_Audit_Report.pdf ├── StarkEx_v1.0_Audit_Report.pdf ├── StarkEx_v2.0_Audit_Report.pdf ├── StarkEx_v3.0_Audit_Report.pdf ├── StarkEx_v4.0_Audit_Report.pdf ├── StarkEx_v4.5_Audit_Report.pdf └── StarkPerpetual_v1.0_Audit_Report.pdf ├── common-contracts └── src │ ├── components │ ├── FactRegistry.sol │ ├── Governance.sol │ └── GovernanceStorage.sol │ ├── interfaces │ ├── BlockDirectCall.sol │ ├── ContractInitializer.sol │ ├── ExternalInitializer.sol │ ├── IFactRegistry.sol │ ├── IQueryableFactRegistry.sol │ ├── Identity.sol │ ├── MGovernance.sol │ └── ProxySupport.sol │ ├── libraries │ ├── Common.sol │ └── NamedStorage.sol │ └── upgrade │ ├── CallProxy.sol │ ├── Proxy.sol │ ├── ProxyGovernance.sol │ ├── ProxyStorage.sol │ └── StorageSlots.sol ├── evm-verifier ├── README.md └── solidity │ └── contracts │ ├── Fri.sol │ ├── FriLayer.sol │ ├── FriStatementContract.sol │ ├── FriStatementVerifier.sol │ ├── FriTransform.sol │ ├── HornerEvaluator.sol │ ├── IMerkleVerifier.sol │ ├── MemoryAccessUtils.sol │ ├── MerkleStatementContract.sol │ ├── MerkleStatementVerifier.sol │ ├── MerkleVerifier.sol │ ├── PrimeFieldElement0.sol │ ├── Prng.sol │ ├── StarkVerifier.sol │ ├── VerifierChannel.sol │ ├── components │ └── FactRegistry.sol │ ├── cpu │ ├── CairoBootloaderProgram.sol │ ├── CairoVerifierContract.sol │ ├── CpuFrilessVerifier.sol │ ├── CpuPublicInputOffsets.sol │ ├── CpuPublicInputOffsetsBase.sol │ ├── CpuVerifier.sol │ ├── MemoryPageFactRegistry.sol │ ├── PageInfo.sol │ ├── PublicMemoryOffsets.sol │ ├── layout0 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout1 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout2 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout3 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout4 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout5 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ ├── layout6 │ │ ├── CpuConstraintPoly.sol │ │ ├── CpuFrilessVerifier.sol │ │ ├── CpuOods.sol │ │ ├── CpuPublicInputOffsets.sol │ │ ├── CpuVerifier.sol │ │ ├── Fri.sol │ │ ├── FriStatementVerifier.sol │ │ ├── LayoutSpecific.sol │ │ ├── MemoryAccessUtils.sol │ │ ├── MemoryMap.sol │ │ ├── StarkParameters.sol │ │ └── StarkVerifier.sol │ └── periodic_columns │ │ ├── EcdsaPointsXColumn.sol │ │ ├── EcdsaPointsYColumn.sol │ │ ├── PedersenHashPointsXColumn.sol │ │ └── PedersenHashPointsYColumn.sol │ ├── gps │ ├── GpsOutputParser.sol │ └── GpsStatementVerifier.sol │ └── interfaces │ ├── IFactRegistry.sol │ ├── IPeriodicColumn.sol │ ├── IQueryableFactRegistry.sol │ ├── IStarkVerifier.sol │ └── Identity.sol └── scalable-dex ├── README.md ├── abi ├── StarkExchange.abi └── StarkPerpetual.abi └── contracts └── src ├── committee └── Committee.sol ├── components ├── ActionHash.sol ├── ApprovalChain.sol ├── AvailabilityVerifiers.sol ├── ECDSA.sol ├── ERC1155Receiver.sol ├── ERC721Receiver.sol ├── EcTableContract.sol ├── FactRegistry.sol ├── Freezable.sol ├── GenericGovernance.sol ├── Governance.sol ├── GovernanceStorage.sol ├── GpsFactRegistryAdapter.sol ├── KeyGetters.sol ├── MainGovernance.sol ├── MainStorage.sol ├── MessageRegistry.sol ├── OnchainDataFactTreeEncoder.sol ├── Operator.sol ├── PedersenMerkleVerifier.sol ├── StarkExOperator.sol ├── TokenRegister.sol ├── TokenTransfers.sol ├── Users.sol ├── UsersV2.sol ├── Verifiers.sol └── VerifyFactChain.sol ├── cpu └── MemoryPageFactRegistry.sol ├── interactions ├── AcceptModifications.sol ├── CompositeActionsV2.sol ├── Deposits.sol ├── StateRoot.sol ├── TokenAssetData.sol ├── TokenQuantization.sol └── Withdrawals.sol ├── interfaces ├── BlockDirectCall.sol ├── ContractInitializer.sol ├── ExternalInitializer.sol ├── IAvailabilityVerifier.sol ├── IDispatcherBase.sol ├── IFactRegistry.sol ├── IIdentity.sol ├── IQueryableFactRegistry.sol ├── IStarkVerifier.sol ├── Identity.sol ├── MAcceptModifications.sol ├── MApprovalChain.sol ├── MDeposits.sol ├── MFreezable.sol ├── MGovernance.sol ├── MKeyGetters.sol ├── MOperator.sol ├── MStateRoot.sol ├── MTokenAssetData.sol ├── MTokenQuantization.sol ├── MTokenTransfers.sol ├── MUsersV2.sol ├── MainDispatcher.sol ├── MainDispatcherBase.sol ├── ProxySupport.sol └── SubContractor.sol ├── libraries ├── Common.sol ├── LibConstants.sol └── NamedStorage.sol ├── perpetual ├── PerpetualConstants.sol ├── ProgramOutputOffsets.sol ├── StarkPerpetual.sol ├── StarkPerpetualV2.sol ├── components │ ├── Configuration.sol │ ├── PerpetualEscapeVerifier.sol │ ├── PerpetualEscapes.sol │ ├── PerpetualStorage.sol │ ├── PerpetualTokenRegister.sol │ └── UpdatePerpetualState.sol ├── interactions │ ├── ForcedTradeActionState.sol │ ├── ForcedTrades.sol │ ├── ForcedWithdrawalActionState.sol │ └── ForcedWithdrawals.sol ├── interfaces │ ├── MForcedTradeActionState.sol │ └── MForcedWithdrawalActionState.sol └── toplevel_subcontracts │ ├── PerpetualForcedActions.sol │ ├── PerpetualState.sol │ ├── PerpetualTokensAndRamping.sol │ └── PerpetualTokensAndRampingV2.sol ├── starkex ├── PublicInputOffsets.sol ├── StarkExConstants.sol ├── StarkExchange.sol ├── components │ ├── EscapeVerifier.sol │ ├── Escapes.sol │ ├── OrderRegistry.sol │ ├── StarkExStorage.sol │ ├── VaultDepositWithdrawal.sol │ └── VaultLocks.sol ├── interactions │ ├── FullWithdrawals.sol │ ├── StarkExForcedActionState.sol │ └── UpdateState.sol ├── interfaces │ ├── MStarkExForcedActionState.sol │ └── MVaultLocks.sol └── toplevel_subcontracts │ ├── ForcedActions.sol │ ├── OnchainVaults.sol │ ├── ProxyUtils.sol │ ├── StarkExState.sol │ └── TokensAndRamping.sol ├── third_party └── EllipticCurve.sol ├── tokens ├── ERC1155 │ ├── IERC1155.sol │ └── IERC1155Receiver.sol ├── ERC20 │ └── IERC20.sol └── ERC721 │ ├── IERC721.sol │ └── IERC721Receiver.sol ├── toplevel_subcontracts └── AllVerifiers.sol └── upgrade ├── Proxy.sol ├── ProxyGovernance.sol ├── ProxyStorage.sol ├── StorageSlots.sol └── eic ├── ChangeVerifiersExternalInitializer.sol ├── ChangeVerifiersZeroTimelockExternalInitializer.sol ├── ModifyConfigurationDelayExternalInitializer.sol ├── ModifyUpgradeDelayExternalInitializer.sol ├── ReplaceEscapeVerifierExternalInitializer.sol ├── UpdatePerpetualConfigExternalInitializer.sol └── V3toV45ChangesExternalInitializer.sol /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019,2020 StarkWare Industries Ltd. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"). 5 | You may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://www.starkware.co/open-source-license/ 9 | 10 | Unless required by applicable law or agreed to in writing, 11 | software distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions 14 | and limitations under the License. 15 | */ 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StarkEx 2 | 3 | StarkEx is a STARK-powered scalability engine for crypto exchanges. StarkEx uses cryptographic 4 | proofs to attest to the validity of a batch of transactions (such as trades and transfers) 5 | and updates a commitment to the state of the exchange onchain. 6 | 7 | StarkEx allows exchanges to provide non-custodial trading at scale with high liquidity and lower 8 | costs. 9 | 10 | ## Modules 11 | 12 | 1. scalable-dex - StarkEx main contract elements 13 | 2. evm-verifier - Cryptographic STARK verifier elements 14 | -------------------------------------------------------------------------------- /audit/Cairo_and_SHARP_Verifiers_v3.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/Cairo_and_SHARP_Verifiers_v3.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/EVM_STARK_Verifier_v4.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/EVM_STARK_Verifier_v4.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkEx_v1.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkEx_v1.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkEx_v2.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkEx_v2.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkEx_v3.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkEx_v3.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkEx_v4.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkEx_v4.0_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkEx_v4.5_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkEx_v4.5_Audit_Report.pdf -------------------------------------------------------------------------------- /audit/StarkPerpetual_v1.0_Audit_Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/starkex-contracts/aecf37f2278b2df233edd13b686d0aa9462ada02/audit/StarkPerpetual_v1.0_Audit_Report.pdf -------------------------------------------------------------------------------- /common-contracts/src/components/FactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/components/FactRegistry.sol -------------------------------------------------------------------------------- /common-contracts/src/components/Governance.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/components/Governance.sol -------------------------------------------------------------------------------- /common-contracts/src/components/GovernanceStorage.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/components/GovernanceStorage.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/BlockDirectCall.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/BlockDirectCall.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/ContractInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | Interface for contract initialization. 6 | The functions it exposes are the app specific parts of the contract initialization, 7 | and are called by the ProxySupport contract that implement the generic part of behind-proxy 8 | initialization. 9 | */ 10 | abstract contract ContractInitializer { 11 | function numOfSubContracts() internal pure virtual returns (uint256); 12 | 13 | function isInitialized() internal view virtual returns (bool); 14 | 15 | function validateInitData(bytes calldata data) internal pure virtual; 16 | 17 | function processSubContractAddresses(bytes calldata subContractAddresses) internal virtual; 18 | 19 | function initializeContractState(bytes calldata data) internal virtual; 20 | } 21 | -------------------------------------------------------------------------------- /common-contracts/src/interfaces/ExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/ExternalInitializer.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/IFactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/IFactRegistry.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/IQueryableFactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/IQueryableFactRegistry.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/Identity.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/Identity.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/MGovernance.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/interfaces/MGovernance.sol -------------------------------------------------------------------------------- /common-contracts/src/interfaces/ProxySupport.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/Governance.sol"; 5 | import "../libraries/Common.sol"; 6 | import "./BlockDirectCall.sol"; 7 | import "./ContractInitializer.sol"; 8 | 9 | /** 10 | This contract contains the code commonly needed for a contract to be deployed behind 11 | an upgradability proxy. 12 | It perform the required semantics of the proxy pattern, 13 | but in a generic manner. 14 | Instantiation of the Governance and of the ContractInitializer, that are the app specific 15 | part of initialization, has to be done by the using contract. 16 | */ 17 | abstract contract ProxySupport is Governance, BlockDirectCall, ContractInitializer { 18 | using Addresses for address; 19 | 20 | // The two function below (isFrozen & initialize) needed to bind to the Proxy. 21 | function isFrozen() external view virtual returns (bool) { 22 | return false; 23 | } 24 | 25 | /* 26 | The initialize() function serves as an alternative constructor for a proxied deployment. 27 | 28 | Flow and notes: 29 | 1. This function cannot be called directly on the deployed contract, but only via 30 | delegate call. 31 | 2. If an EIC is provided - init is passed onto EIC and the standard init flow is skipped. 32 | This true for both first intialization or a later one. 33 | 3. The data passed to this function is as follows: 34 | [sub_contracts addresses, eic address, initData]. 35 | 36 | When calling on an initialized contract (no EIC scenario), initData.length must be 0. 37 | */ 38 | function initialize(bytes calldata data) external notCalledDirectly { 39 | uint256 eicOffset = 32 * numOfSubContracts(); 40 | uint256 expectedBaseSize = eicOffset + 32; 41 | require(data.length >= expectedBaseSize, "INIT_DATA_TOO_SMALL"); 42 | address eicAddress = abi.decode(data[eicOffset:expectedBaseSize], (address)); 43 | 44 | bytes calldata subContractAddresses = data[:eicOffset]; 45 | 46 | processSubContractAddresses(subContractAddresses); 47 | 48 | bytes calldata initData = data[expectedBaseSize:]; 49 | 50 | // EIC Provided - Pass initData to EIC and the skip standard init flow. 51 | if (eicAddress != address(0x0)) { 52 | callExternalInitializer(eicAddress, initData); 53 | return; 54 | } 55 | 56 | if (isInitialized()) { 57 | require(initData.length == 0, "UNEXPECTED_INIT_DATA"); 58 | } else { 59 | // Contract was not initialized yet. 60 | validateInitData(initData); 61 | initializeContractState(initData); 62 | initGovernance(); 63 | } 64 | } 65 | 66 | function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData) 67 | private 68 | { 69 | require(externalInitializerAddr.isContract(), "EIC_NOT_A_CONTRACT"); 70 | 71 | // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. 72 | (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( 73 | abi.encodeWithSelector(this.initialize.selector, eicData) 74 | ); 75 | require(success, string(returndata)); 76 | require(returndata.length == 0, string(returndata)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /common-contracts/src/libraries/Common.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/libraries/Common.sol -------------------------------------------------------------------------------- /common-contracts/src/libraries/NamedStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Library to provide basic storage, in storage location out of the low linear address space. 6 | 7 | New types of storage variables should be added here upon need. 8 | */ 9 | library NamedStorage { 10 | function bytes32ToUint256Mapping(string memory tag_) 11 | internal 12 | pure 13 | returns (mapping(bytes32 => uint256) storage randomVariable) 14 | { 15 | bytes32 location = keccak256(abi.encodePacked(tag_)); 16 | assembly { 17 | randomVariable_slot := location 18 | } 19 | } 20 | 21 | function bytes32ToAddressMapping(string memory tag_) 22 | internal 23 | pure 24 | returns (mapping(bytes32 => address) storage randomVariable) 25 | { 26 | bytes32 location = keccak256(abi.encodePacked(tag_)); 27 | assembly { 28 | randomVariable_slot := location 29 | } 30 | } 31 | 32 | function uintToAddressMapping(string memory tag_) 33 | internal 34 | pure 35 | returns (mapping(uint256 => address) storage randomVariable) 36 | { 37 | bytes32 location = keccak256(abi.encodePacked(tag_)); 38 | assembly { 39 | randomVariable_slot := location 40 | } 41 | } 42 | 43 | function addressToBoolMapping(string memory tag_) 44 | internal 45 | pure 46 | returns (mapping(address => bool) storage randomVariable) 47 | { 48 | bytes32 location = keccak256(abi.encodePacked(tag_)); 49 | assembly { 50 | randomVariable_slot := location 51 | } 52 | } 53 | 54 | function getUintValue(string memory tag_) internal view returns (uint256 retVal) { 55 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 56 | assembly { 57 | retVal := sload(slot) 58 | } 59 | } 60 | 61 | function setUintValue(string memory tag_, uint256 value) internal { 62 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 63 | assembly { 64 | sstore(slot, value) 65 | } 66 | } 67 | 68 | function setUintValueOnce(string memory tag_, uint256 value) internal { 69 | require(getUintValue(tag_) == 0, "ALREADY_SET"); 70 | setUintValue(tag_, value); 71 | } 72 | 73 | function getAddressValue(string memory tag_) internal view returns (address retVal) { 74 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 75 | assembly { 76 | retVal := sload(slot) 77 | } 78 | } 79 | 80 | function setAddressValue(string memory tag_, address value) internal { 81 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 82 | assembly { 83 | sstore(slot, value) 84 | } 85 | } 86 | 87 | function setAddressValueOnce(string memory tag_, address value) internal { 88 | require(getAddressValue(tag_) == address(0x0), "ALREADY_SET"); 89 | setAddressValue(tag_, value); 90 | } 91 | 92 | function getBoolValue(string memory tag_) internal view returns (bool retVal) { 93 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 94 | assembly { 95 | retVal := sload(slot) 96 | } 97 | } 98 | 99 | function setBoolValue(string memory tag_, bool value) internal { 100 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 101 | assembly { 102 | sstore(slot, value) 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /common-contracts/src/upgrade/Proxy.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/upgrade/Proxy.sol -------------------------------------------------------------------------------- /common-contracts/src/upgrade/ProxyGovernance.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/upgrade/ProxyGovernance.sol -------------------------------------------------------------------------------- /common-contracts/src/upgrade/ProxyStorage.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/upgrade/ProxyStorage.sol -------------------------------------------------------------------------------- /common-contracts/src/upgrade/StorageSlots.sol: -------------------------------------------------------------------------------- 1 | ../../../scalable-dex/contracts/src/upgrade/StorageSlots.sol -------------------------------------------------------------------------------- /evm-verifier/README.md: -------------------------------------------------------------------------------- 1 | # STARK Verifier for Cairo Programs 2 | 3 | Cairo is the first production-grade platform for generating STARK proofs for general computation. 4 | It is Turing Complete, and highly efficient. The following set of contracts implements the 5 | verifier of programs written in Cairo, verifying the computational integrity of executing Cairo 6 | program P on input data D, and the correctness of the post-execution state of the system. 7 | 8 | The verifier is composed of multiple contracts as described below. 9 | 10 | ## Contracts 11 | 12 | 1. GpsStatementVerifier - Main verifier contract entry point for verifying Cairo programs wrapped in 13 | the context of a general bootloader. 14 | 2. CpuVerifier - STARK verifier for verifying Cairo statements 15 | 3. MerkleStatementContract - Merkle verifier used by the CpuVerifier. 16 | 4. FriStatementContract - Fri verifier used by the CpuVerifier. 17 | 5. MemoryPageFactRegistry - Fact registry for memory claims used by the CpuVerifier. 18 | 6. Auxilliary contracts used by the above verifiers to calculate polynomial evaluations: 19 | 1. CpuConstraintPoly 20 | 2. EcdsaPointsXColumn 21 | 3. EcdsaPointsYColumn 22 | 4. PedersenHashPointsXColumn 23 | 5. PedersenHashPointsYColumn 24 | 6. CpuOods 25 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/IMerkleVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract IMerkleVerifier { 5 | uint256 internal constant MAX_N_MERKLE_VERIFIER_QUERIES = 128; 6 | 7 | // The size of a SLOT in the verifyMerkle queue. 8 | // Every slot holds a (index, hash) pair. 9 | uint256 internal constant MERKLE_SLOT_SIZE_IN_BYTES = 0x40; 10 | 11 | function verifyMerkle( 12 | uint256 channelPtr, 13 | uint256 queuePtr, 14 | bytes32 root, 15 | uint256 n 16 | ) internal view virtual returns (bytes32 hash); 17 | } 18 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./MemoryMap.sol"; 5 | 6 | contract MemoryAccessUtils is MemoryMap { 7 | function getPtr(uint256[] memory ctx, uint256 offset) internal pure returns (uint256) { 8 | uint256 ctxPtr; 9 | require(offset < MM_CONTEXT_SIZE, "Overflow protection failed"); 10 | assembly { 11 | ctxPtr := add(ctx, 0x20) 12 | } 13 | return ctxPtr + offset * 0x20; 14 | } 15 | 16 | function getProofPtr(uint256[] memory proof) internal pure returns (uint256) { 17 | uint256 proofPtr; 18 | assembly { 19 | proofPtr := proof 20 | } 21 | return proofPtr; 22 | } 23 | 24 | function getChannelPtr(uint256[] memory ctx) internal pure returns (uint256) { 25 | uint256 ctxPtr; 26 | assembly { 27 | ctxPtr := add(ctx, 0x20) 28 | } 29 | return ctxPtr + MM_CHANNEL * 0x20; 30 | } 31 | 32 | function getQueries(uint256[] memory ctx) internal pure returns (uint256[] memory) { 33 | uint256[] memory queries; 34 | // Dynamic array holds length followed by values. 35 | uint256 offset = 0x20 + 0x20 * MM_N_UNIQUE_QUERIES; 36 | assembly { 37 | queries := add(ctx, offset) 38 | } 39 | return queries; 40 | } 41 | 42 | function getMerkleQueuePtr(uint256[] memory ctx) internal pure returns (uint256) { 43 | return getPtr(ctx, MM_MERKLE_QUEUE); 44 | } 45 | 46 | function getFriStepSizes(uint256[] memory ctx) 47 | internal 48 | pure 49 | returns (uint256[] memory friStepSizes) 50 | { 51 | uint256 friStepSizesPtr = getPtr(ctx, MM_FRI_STEP_SIZES_PTR); 52 | assembly { 53 | friStepSizes := mload(friStepSizesPtr) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/MerkleStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./MerkleStatementContract.sol"; 5 | 6 | abstract contract MerkleStatementVerifier is IMerkleVerifier { 7 | MerkleStatementContract merkleStatementContract; 8 | 9 | constructor(address merkleStatementContractAddress) public { 10 | merkleStatementContract = MerkleStatementContract(merkleStatementContractAddress); 11 | } 12 | 13 | // Computes the hash of the Merkle statement, and verifies that it is registered in the 14 | // Merkle Fact Registry. Receives as input the queuePtr (as address), its length 15 | // the numbers of queries n, and the root. The channelPtr is is ignored. 16 | function verifyMerkle( 17 | uint256, /*channelPtr*/ 18 | uint256 queuePtr, 19 | bytes32 root, 20 | uint256 n 21 | ) internal view virtual override returns (bytes32) { 22 | bytes32 statement; 23 | require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); 24 | 25 | assembly { 26 | let dataToHashPtrStart := mload(0x40) // freePtr. 27 | let dataToHashPtrCur := dataToHashPtrStart 28 | 29 | let queEndPtr := add(queuePtr, mul(n, 0x40)) 30 | 31 | for { 32 | 33 | } lt(queuePtr, queEndPtr) { 34 | 35 | } { 36 | mstore(dataToHashPtrCur, mload(queuePtr)) 37 | dataToHashPtrCur := add(dataToHashPtrCur, 0x20) 38 | queuePtr := add(queuePtr, 0x20) 39 | } 40 | 41 | mstore(dataToHashPtrCur, root) 42 | dataToHashPtrCur := add(dataToHashPtrCur, 0x20) 43 | mstore(0x40, dataToHashPtrCur) 44 | 45 | statement := keccak256(dataToHashPtrStart, sub(dataToHashPtrCur, dataToHashPtrStart)) 46 | } 47 | require(merkleStatementContract.isValid(statement), "INVALIDATED_MERKLE_STATEMENT"); 48 | return root; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/PrimeFieldElement0.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | contract PrimeFieldElement0 { 5 | uint256 internal constant K_MODULUS = 6 | 0x800000000000011000000000000000000000000000000000000000000000001; 7 | uint256 internal constant K_MONTGOMERY_R = 8 | 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1; 9 | uint256 internal constant K_MONTGOMERY_R_INV = 10 | 0x40000000000001100000000000012100000000000000000000000000000000; 11 | uint256 internal constant GENERATOR_VAL = 3; 12 | uint256 internal constant ONE_VAL = 1; 13 | 14 | function fromMontgomery(uint256 val) internal pure returns (uint256 res) { 15 | // uint256 res = fmul(val, kMontgomeryRInv); 16 | assembly { 17 | res := mulmod(val, K_MONTGOMERY_R_INV, K_MODULUS) 18 | } 19 | return res; 20 | } 21 | 22 | function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { 23 | // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field 24 | // element. 25 | uint256 res = uint256(bs); 26 | return fromMontgomery(res); 27 | } 28 | 29 | function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { 30 | //uint256 res = fmul(val, kMontgomeryR); 31 | assembly { 32 | res := mulmod(val, K_MONTGOMERY_R, K_MODULUS) 33 | } 34 | return res; 35 | } 36 | 37 | function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { 38 | //uint256 res = mulmod(a, b, kModulus); 39 | assembly { 40 | res := mulmod(a, b, K_MODULUS) 41 | } 42 | return res; 43 | } 44 | 45 | function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { 46 | // uint256 res = addmod(a, b, kModulus); 47 | assembly { 48 | res := addmod(a, b, K_MODULUS) 49 | } 50 | return res; 51 | } 52 | 53 | function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { 54 | // uint256 res = addmod(a, kModulus - b, kModulus); 55 | assembly { 56 | res := addmod(a, sub(K_MODULUS, b), K_MODULUS) 57 | } 58 | return res; 59 | } 60 | 61 | function fpow(uint256 val, uint256 exp) internal view returns (uint256) { 62 | return expmod(val, exp, K_MODULUS); 63 | } 64 | 65 | function expmod( 66 | uint256 base, 67 | uint256 exponent, 68 | uint256 modulus 69 | ) private view returns (uint256 res) { 70 | assembly { 71 | let p := mload(0x40) 72 | mstore(p, 0x20) // Length of Base. 73 | mstore(add(p, 0x20), 0x20) // Length of Exponent. 74 | mstore(add(p, 0x40), 0x20) // Length of Modulus. 75 | mstore(add(p, 0x60), base) // Base. 76 | mstore(add(p, 0x80), exponent) // Exponent. 77 | mstore(add(p, 0xa0), modulus) // Modulus. 78 | // Call modexp precompile. 79 | if iszero(staticcall(gas(), 0x05, p, 0xc0, p, 0x20)) { 80 | revert(0, 0) 81 | } 82 | res := mload(p) 83 | } 84 | } 85 | 86 | function inverse(uint256 val) internal view returns (uint256) { 87 | return expmod(val, K_MODULUS - 2, K_MODULUS); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/Prng.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./PrimeFieldElement0.sol"; 5 | 6 | contract Prng is PrimeFieldElement0 { 7 | function storePrng( 8 | uint256 prngPtr, 9 | bytes32 digest, 10 | uint256 counter 11 | ) internal pure { 12 | assembly { 13 | mstore(prngPtr, digest) 14 | mstore(add(prngPtr, 0x20), counter) 15 | } 16 | } 17 | 18 | function loadPrng(uint256 prngPtr) internal pure returns (bytes32, uint256) { 19 | bytes32 digest; 20 | uint256 counter; 21 | 22 | assembly { 23 | digest := mload(prngPtr) 24 | counter := mload(add(prngPtr, 0x20)) 25 | } 26 | 27 | return (digest, counter); 28 | } 29 | 30 | function initPrng(uint256 prngPtr, bytes32 publicInputHash) internal pure { 31 | storePrng( 32 | prngPtr, 33 | // keccak256(publicInput) 34 | publicInputHash, 35 | 0 36 | ); 37 | } 38 | 39 | /* 40 | Auxiliary function for getRandomBytes. 41 | */ 42 | function getRandomBytesInner(bytes32 digest, uint256 counter) 43 | private 44 | pure 45 | returns ( 46 | bytes32, 47 | uint256, 48 | bytes32 49 | ) 50 | { 51 | // returns 32 bytes (for random field elements or four queries at a time). 52 | bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter)); 53 | 54 | return (digest, counter + 1, randomBytes); 55 | } 56 | 57 | /* 58 | Returns 32 bytes. Used for a random field element, or for 4 query indices. 59 | */ 60 | function getRandomBytes(uint256 prngPtr) internal pure returns (bytes32 randomBytes) { 61 | bytes32 digest; 62 | uint256 counter; 63 | (digest, counter) = loadPrng(prngPtr); 64 | 65 | // returns 32 bytes (for random field elements or four queries at a time). 66 | (digest, counter, randomBytes) = getRandomBytesInner(digest, counter); 67 | 68 | storePrng(prngPtr, digest, counter); 69 | return randomBytes; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/components/FactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../../scalable-dex/contracts/src/components/FactRegistry.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/CairoVerifierContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract CairoVerifierContract { 5 | function verifyProofExternal( 6 | uint256[] calldata proofParams, 7 | uint256[] calldata proof, 8 | uint256[] calldata publicInput 9 | ) external virtual; 10 | 11 | /* 12 | Returns information that is related to the layout. 13 | 14 | publicMemoryOffset is the offset of the public memory pages' information in the public input. 15 | selectedBuiltins is a bit-map of builtins that are present in the layout. 16 | */ 17 | function getLayoutInfo() 18 | external 19 | pure 20 | virtual 21 | returns (uint256 publicMemoryOffset, uint256 selectedBuiltins); 22 | 23 | uint256 internal constant OUTPUT_BUILTIN_BIT = 0; 24 | uint256 internal constant PEDERSEN_BUILTIN_BIT = 1; 25 | uint256 internal constant RANGE_CHECK_BUILTIN_BIT = 2; 26 | uint256 internal constant ECDSA_BUILTIN_BIT = 3; 27 | uint256 internal constant BITWISE_BUILTIN_BIT = 4; 28 | uint256 internal constant EC_OP_BUILTIN_BIT = 5; 29 | } 30 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./CpuVerifier.sol"; 5 | import "./FriStatementVerifier.sol"; 6 | import "../../MerkleStatementVerifier.sol"; 7 | 8 | contract CpuFrilessVerifier is CpuVerifier, MerkleStatementVerifier, FriStatementVerifier { 9 | constructor( 10 | address[] memory auxPolynomials, 11 | address oodsContract, 12 | address memoryPageFactRegistry_, 13 | address merkleStatementContractAddress, 14 | address friStatementContractAddress, 15 | uint256 numSecurityBits_, 16 | uint256 minProofOfWorkBits_ 17 | ) 18 | public 19 | MerkleStatementVerifier(merkleStatementContractAddress) 20 | FriStatementVerifier(friStatementContractAddress) 21 | CpuVerifier( 22 | auxPolynomials, 23 | oodsContract, 24 | memoryPageFactRegistry_, 25 | numSecurityBits_, 26 | minProofOfWorkBits_ 27 | ) 28 | {} 29 | 30 | function verifyMerkle( 31 | uint256 channelPtr, 32 | uint256 queuePtr, 33 | bytes32 root, 34 | uint256 n 35 | ) internal view override(MerkleStatementVerifier, MerkleVerifier) returns (bytes32) { 36 | return MerkleStatementVerifier.verifyMerkle(channelPtr, queuePtr, root, n); 37 | } 38 | 39 | function friVerifyLayers(uint256[] memory ctx) 40 | internal 41 | view 42 | override(FriStatementVerifier, Fri) 43 | { 44 | FriStatementVerifier.friVerifyLayers(ctx); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../CpuPublicInputOffsetsBase.sol"; 5 | 6 | contract CpuPublicInputOffsets is CpuPublicInputOffsetsBase { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; 9 | uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; 10 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_ADDR = 16; 11 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_VALUE = 17; 12 | uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 18; 13 | uint256 internal constant OFFSET_PUBLIC_MEMORY = 19; 14 | } 15 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/CpuPublicInputOffsetsBase.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./PageInfo.sol"; 5 | 6 | contract CpuPublicInputOffsetsBase is PageInfo { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_LOG_N_STEPS = 0; 9 | uint256 internal constant OFFSET_RC_MIN = 1; 10 | uint256 internal constant OFFSET_RC_MAX = 2; 11 | uint256 internal constant OFFSET_LAYOUT_CODE = 3; 12 | uint256 internal constant OFFSET_PROGRAM_BEGIN_ADDR = 4; 13 | uint256 internal constant OFFSET_PROGRAM_STOP_PTR = 5; 14 | uint256 internal constant OFFSET_EXECUTION_BEGIN_ADDR = 6; 15 | uint256 internal constant OFFSET_EXECUTION_STOP_PTR = 7; 16 | uint256 internal constant OFFSET_OUTPUT_BEGIN_ADDR = 8; 17 | uint256 internal constant OFFSET_OUTPUT_STOP_PTR = 9; 18 | uint256 internal constant OFFSET_PEDERSEN_BEGIN_ADDR = 10; 19 | uint256 internal constant OFFSET_PEDERSEN_STOP_PTR = 11; 20 | uint256 internal constant OFFSET_RANGE_CHECK_BEGIN_ADDR = 12; 21 | uint256 internal constant OFFSET_RANGE_CHECK_STOP_PTR = 13; 22 | 23 | // The program segment starts from 1, so that memory address 0 is kept for the null pointer. 24 | uint256 internal constant INITIAL_PC = 1; 25 | // The first Cairo instructions are: 26 | // ap += n_args; call main; jmp rel 0. 27 | // As the first two instructions occupy 2 cells each, the "jmp rel 0" instruction is at 28 | // offset 4 relative to INITIAL_PC. 29 | uint256 internal constant FINAL_PC = INITIAL_PC + 4; 30 | } 31 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/PageInfo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | contract PageInfo { 5 | uint256 public constant PAGE_INFO_SIZE = 3; 6 | // PAGE_INFO_SIZE_IN_BYTES cannot reference PAGE_INFO_SIZE as only direct constants are 7 | // supported in assembly. 8 | uint256 public constant PAGE_INFO_SIZE_IN_BYTES = 3 * 32; 9 | 10 | uint256 public constant PAGE_INFO_ADDRESS_OFFSET = 0; 11 | uint256 public constant PAGE_INFO_SIZE_OFFSET = 1; 12 | uint256 public constant PAGE_INFO_HASH_OFFSET = 2; 13 | 14 | // A regular page entry is a (address, value) pair stored as 2 uint256 words. 15 | uint256 internal constant MEMORY_PAIR_SIZE = 2; 16 | } 17 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/PublicMemoryOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./PageInfo.sol"; 5 | 6 | abstract contract PublicMemoryOffsets is PageInfo { 7 | /* 8 | Returns the offset in the public input where the public memory related information starts. 9 | The offset is layout specific and each layout needs to override this function. 10 | */ 11 | function getPublicMemoryOffset() internal pure virtual returns (uint256); 12 | 13 | // The format of the public input, starting at getPublicMemoryOffset() is as follows: 14 | // * For each page: 15 | // * First address in the page (this field is not included for the first page). 16 | // * Page size. 17 | // * Page hash. 18 | // # All data above this line, appears in the initial seed of the proof. 19 | // * For each page: 20 | // * Cumulative product. 21 | function getOffsetPageSize(uint256 pageId) internal pure returns (uint256) { 22 | return getPublicMemoryOffset() + PAGE_INFO_SIZE * pageId - 1 + PAGE_INFO_SIZE_OFFSET; 23 | } 24 | 25 | function getOffsetPageHash(uint256 pageId) internal pure returns (uint256) { 26 | return getPublicMemoryOffset() + PAGE_INFO_SIZE * pageId - 1 + PAGE_INFO_HASH_OFFSET; 27 | } 28 | 29 | function getOffsetPageAddr(uint256 pageId) internal pure returns (uint256) { 30 | require(pageId >= 1, "Address of page 0 is not part of the public input."); 31 | return getPublicMemoryOffset() + PAGE_INFO_SIZE * pageId - 1 + PAGE_INFO_ADDRESS_OFFSET; 32 | } 33 | 34 | function getOffsetPageProd(uint256 pageId, uint256 nPages) internal pure returns (uint256) { 35 | return getPublicMemoryOffset() + PAGE_INFO_SIZE * nPages - 1 + pageId; 36 | } 37 | 38 | function getPublicInputLength(uint256 nPages) internal pure returns (uint256) { 39 | return getPublicMemoryOffset() + (PAGE_INFO_SIZE + 1) * nPages - 1; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | ../CpuPublicInputOffsets.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 179; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 3; 10 | uint256 constant internal MASK_SIZE = 201; 11 | uint256 constant internal N_ROWS_IN_MASK = 81; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 25; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 23; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 2; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 8; 21 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; 22 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; 23 | uint256 constant internal RC_BUILTIN_RATIO = 8; 24 | uint256 constant internal RC_N_PARTS = 8; 25 | uint256 constant internal ECDSA_BUILTIN_RATIO = 512; 26 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 27 | uint256 constant internal LAYOUT_CODE = 495756340332; 28 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 29 | } 30 | // ---------- End of auto-generated code. ---------- 31 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout0/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | ../CpuPublicInputOffsets.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 179; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 3; 10 | uint256 constant internal MASK_SIZE = 200; 11 | uint256 constant internal N_ROWS_IN_MASK = 81; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 22; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 21; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 1; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 8; 21 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; 22 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; 23 | uint256 constant internal RC_BUILTIN_RATIO = 8; 24 | uint256 constant internal RC_N_PARTS = 8; 25 | uint256 constant internal ECDSA_BUILTIN_RATIO = 512; 26 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 27 | uint256 constant internal LAYOUT_CODE = 6579576; 28 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 29 | } 30 | // ---------- End of auto-generated code. ---------- 31 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout1/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | ../CpuPublicInputOffsets.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 116; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 3; 10 | uint256 constant internal MASK_SIZE = 128; 11 | uint256 constant internal N_ROWS_IN_MASK = 79; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 10; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 9; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 1; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 8; 21 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 32; 22 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 1; 23 | uint256 constant internal RC_BUILTIN_RATIO = 16; 24 | uint256 constant internal RC_N_PARTS = 8; 25 | uint256 constant internal ECDSA_BUILTIN_RATIO = 2048; 26 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 27 | uint256 constant internal LAYOUT_CODE = 2073345364981693374828; 28 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 29 | } 30 | // ---------- End of auto-generated code. ---------- 31 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout2/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../CpuPublicInputOffsetsBase.sol"; 5 | 6 | contract CpuPublicInputOffsets is CpuPublicInputOffsetsBase { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; 9 | uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; 10 | uint256 internal constant OFFSET_BITWISE_BEGIN_ADDR = 16; 11 | uint256 internal constant OFFSET_BITWISE_STOP_ADDR = 17; 12 | uint256 internal constant OFFSET_EC_OP_BEGIN_ADDR = 18; 13 | uint256 internal constant OFFSET_EC_OP_STOP_ADDR = 19; 14 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_ADDR = 20; 15 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_VALUE = 21; 16 | uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 22; 17 | uint256 internal constant OFFSET_PUBLIC_MEMORY = 23; 18 | } 19 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 230; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 6; 10 | uint256 constant internal MASK_SIZE = 286; 11 | uint256 constant internal N_ROWS_IN_MASK = 146; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 27; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 24; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 3; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 16; 21 | uint256 constant internal DILUTED_SPACING = 4; 22 | uint256 constant internal DILUTED_N_BITS = 16; 23 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; 24 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; 25 | uint256 constant internal RC_BUILTIN_RATIO = 8; 26 | uint256 constant internal RC_N_PARTS = 8; 27 | uint256 constant internal ECDSA_BUILTIN_RATIO = 512; 28 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 29 | uint256 constant internal BITWISE__RATIO = 256; 30 | uint256 constant internal EC_OP_BUILTIN_RATIO = 256; 31 | uint256 constant internal EC_OP_SCALAR_HEIGHT = 256; 32 | uint256 constant internal EC_OP_N_BITS = 252; 33 | uint256 constant internal LAYOUT_CODE = 6384748; 34 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 35 | } 36 | // ---------- End of auto-generated code. ---------- 37 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout3/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../CpuPublicInputOffsetsBase.sol"; 5 | 6 | contract CpuPublicInputOffsets is CpuPublicInputOffsetsBase { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; 9 | uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; 10 | uint256 internal constant OFFSET_BITWISE_BEGIN_ADDR = 16; 11 | uint256 internal constant OFFSET_BITWISE_STOP_ADDR = 17; 12 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_ADDR = 18; 13 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_VALUE = 19; 14 | uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 20; 15 | uint256 internal constant OFFSET_PUBLIC_MEMORY = 21; 16 | } 17 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 134; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 6; 10 | uint256 constant internal MASK_SIZE = 174; 11 | uint256 constant internal N_ROWS_IN_MASK = 103; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 10; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 7; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 3; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 16; 21 | uint256 constant internal DILUTED_SPACING = 4; 22 | uint256 constant internal DILUTED_N_BITS = 16; 23 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 256; 24 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 1; 25 | uint256 constant internal RC_BUILTIN_RATIO = 8; 26 | uint256 constant internal RC_N_PARTS = 8; 27 | uint256 constant internal ECDSA_BUILTIN_RATIO = 1024; 28 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 29 | uint256 constant internal BITWISE__RATIO = 8; 30 | uint256 constant internal LAYOUT_CODE = 27700496658166629; 31 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 32 | } 33 | // ---------- End of auto-generated code. ---------- 34 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout4/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../CpuPublicInputOffsetsBase.sol"; 5 | 6 | contract CpuPublicInputOffsets is CpuPublicInputOffsetsBase { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; 9 | uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; 10 | uint256 internal constant OFFSET_BITWISE_BEGIN_ADDR = 16; 11 | uint256 internal constant OFFSET_BITWISE_STOP_ADDR = 17; 12 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_ADDR = 18; 13 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_VALUE = 19; 14 | uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 20; 15 | uint256 internal constant OFFSET_PUBLIC_MEMORY = 21; 16 | 17 | // The format of the public input, starting at OFFSET_PUBLIC_MEMORY is as follows: 18 | // * For each page: 19 | // * First address in the page (this field is not included for the first page). 20 | // * Page size. 21 | // * Page hash. 22 | // # All data above this line, appears in the initial seed of the proof. 23 | // * For each page: 24 | // * Cumulative product. 25 | } 26 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 197; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 6; 10 | uint256 constant internal MASK_SIZE = 246; 11 | uint256 constant internal N_ROWS_IN_MASK = 120; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 22; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 21; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 1; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 8; 21 | uint256 constant internal DILUTED_SPACING = 4; 22 | uint256 constant internal DILUTED_N_BITS = 16; 23 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; 24 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; 25 | uint256 constant internal RC_BUILTIN_RATIO = 8; 26 | uint256 constant internal RC_N_PARTS = 8; 27 | uint256 constant internal ECDSA_BUILTIN_RATIO = 512; 28 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 29 | uint256 constant internal BITWISE__RATIO = 64; 30 | uint256 constant internal LAYOUT_CODE = 133449663013987685036071398930607862629; 31 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 32 | } 33 | // ---------- End of auto-generated code. ---------- 34 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout5/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/CpuFrilessVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuFrilessVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/CpuPublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../CpuPublicInputOffsetsBase.sol"; 5 | 6 | contract CpuPublicInputOffsets is CpuPublicInputOffsetsBase { 7 | // The following constants are offsets of data expected in the public input. 8 | uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; 9 | uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; 10 | uint256 internal constant OFFSET_BITWISE_BEGIN_ADDR = 16; 11 | uint256 internal constant OFFSET_BITWISE_STOP_ADDR = 17; 12 | uint256 internal constant OFFSET_EC_OP_BEGIN_ADDR = 18; 13 | uint256 internal constant OFFSET_EC_OP_STOP_ADDR = 19; 14 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_ADDR = 20; 15 | uint256 internal constant OFFSET_PUBLIC_MEMORY_PADDING_VALUE = 21; 16 | uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 22; 17 | uint256 internal constant OFFSET_PUBLIC_MEMORY = 23; 18 | } 19 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/CpuVerifier.sol: -------------------------------------------------------------------------------- 1 | ../CpuVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/Fri.sol: -------------------------------------------------------------------------------- 1 | ../../Fri.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/FriStatementVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../FriStatementVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/MemoryAccessUtils.sol: -------------------------------------------------------------------------------- 1 | ../../MemoryAccessUtils.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/StarkParameters.sol: -------------------------------------------------------------------------------- 1 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 2 | // SPDX-License-Identifier: Apache-2.0. 3 | pragma solidity ^0.6.12; 4 | 5 | import "../../PrimeFieldElement0.sol"; 6 | 7 | contract StarkParameters is PrimeFieldElement0 { 8 | uint256 constant internal N_COEFFICIENTS = 167; 9 | uint256 constant internal N_INTERACTION_ELEMENTS = 6; 10 | uint256 constant internal MASK_SIZE = 212; 11 | uint256 constant internal N_ROWS_IN_MASK = 149; 12 | uint256 constant internal N_COLUMNS_IN_MASK = 10; 13 | uint256 constant internal N_COLUMNS_IN_TRACE0 = 9; 14 | uint256 constant internal N_COLUMNS_IN_TRACE1 = 1; 15 | uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; 16 | uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; 17 | uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; 18 | 19 | // ---------- // Air specific constants. ---------- 20 | uint256 constant internal PUBLIC_MEMORY_STEP = 8; 21 | uint256 constant internal DILUTED_SPACING = 4; 22 | uint256 constant internal DILUTED_N_BITS = 16; 23 | uint256 constant internal PEDERSEN_BUILTIN_RATIO = 32; 24 | uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 1; 25 | uint256 constant internal RC_BUILTIN_RATIO = 16; 26 | uint256 constant internal RC_N_PARTS = 8; 27 | uint256 constant internal ECDSA_BUILTIN_RATIO = 2048; 28 | uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; 29 | uint256 constant internal BITWISE__RATIO = 64; 30 | uint256 constant internal EC_OP_BUILTIN_RATIO = 1024; 31 | uint256 constant internal EC_OP_SCALAR_HEIGHT = 256; 32 | uint256 constant internal EC_OP_N_BITS = 252; 33 | uint256 constant internal LAYOUT_CODE = 42052439942391375477807157877090637012086313290658661; 34 | uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; 35 | } 36 | // ---------- End of auto-generated code. ---------- 37 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/cpu/layout6/StarkVerifier.sol: -------------------------------------------------------------------------------- 1 | ../../StarkVerifier.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/interfaces/IFactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../../scalable-dex/contracts/src/interfaces/IFactRegistry.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/interfaces/IPeriodicColumn.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IPeriodicColumn { 5 | function compute(uint256 x) external pure returns (uint256 result); 6 | } 7 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/interfaces/IQueryableFactRegistry.sol: -------------------------------------------------------------------------------- 1 | ../../../../scalable-dex/contracts/src/interfaces/IQueryableFactRegistry.sol -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/interfaces/IStarkVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract IStarkVerifier { 5 | function verifyProof( 6 | uint256[] memory proofParams, 7 | uint256[] memory proof, 8 | uint256[] memory publicInput 9 | ) internal view virtual; 10 | } 11 | -------------------------------------------------------------------------------- /evm-verifier/solidity/contracts/interfaces/Identity.sol: -------------------------------------------------------------------------------- 1 | ../../../../scalable-dex/contracts/src/interfaces/Identity.sol -------------------------------------------------------------------------------- /scalable-dex/README.md: -------------------------------------------------------------------------------- 1 | # StarkEx 2 | 3 | StarkEx is a STARK-powered scalability engine for crypto exchanges. StarkEx uses cryptographic 4 | proofs to attest to the validity of a batch of transactions (such as trades and transfers) 5 | and updates a commitment to the state of the exchange onchain. 6 | 7 | StarkEx allows exchanges to provide non-custodial trading at scale with high liquidity and lower 8 | costs. 9 | 10 | Two versions of the StarkEx are implemented: One for spot trading (StarkExchange) and one for 11 | derivates trading (StarkPerpetual). 12 | 13 | ## Contracts 14 | 15 | 1. StarkExchange - The main exchange contract holding the StarkEx spot trading exchange state and 16 | funds. 17 | 2. StarkPerpetual - The main exchange contract holding the StarkEx derivatives exchange state and 18 | funds. 19 | 3. GpsFactRegistryAdapter - An adapter to the STARK verifier fact registry. 20 | 4. Committee - Verifies signatures attesting to off-chain data availability (where applicable). 21 | 5. EscapeVerifier - Verifies that the contents of a StarkEx spot trading vault belong to a certain 22 | Merkle commitment. 23 | 6. PerpetualEscapeVerifier - Verifies that the contents of a StarkEx derivatives position belong to 24 | a certain Merkle commitment and calculates the amount allowed for escape. 25 | 7. Proxy - Implements delegation of calls to other contracts. Used to allow time-locked 26 | StarkExchange/StarkPerpetual updates. 27 | 8. ChangeVerifiersExternalInitializer - Implements an initialization procedure to be used for 28 | contract updates where the only state updates are the verifier contracts to be used. 29 | 9. ModifyUpgradeDelayExternalInitializer - Implements an initialization procedure to be used for 30 | contract updates where the only state update is the Proxy upgrade activation timelock. 31 | 10. UpdatePerpetualConfigExternalInitializer - Implements an initialization procedure to be used for 32 | contract updates where the only state update is the StarkPerpetual configuration hash. 33 | 11. V3toV45ChangesExternalInitializer - Implements an initialization procedure to be used for 34 | StarkEx contract updates from v3/v4 contracts to v4.5 contracts. 35 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/ActionHash.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/MainStorage.sol"; 5 | import "../libraries/LibConstants.sol"; 6 | 7 | /* 8 | Calculation action hash for the various forced actions in a generic manner. 9 | */ 10 | contract ActionHash is MainStorage, LibConstants { 11 | function getActionHash(string memory actionName, bytes memory packedActionParameters) 12 | internal 13 | pure 14 | returns (bytes32 actionHash) 15 | { 16 | actionHash = keccak256(abi.encodePacked(actionName, packedActionParameters)); 17 | } 18 | 19 | function setActionHash(bytes32 actionHash, bool premiumCost) internal { 20 | // The rate of forced trade requests is restricted. 21 | // First restriction is by capping the number of requests in a block. 22 | // User can override this cap by requesting with a permium flag set, 23 | // in this case, the gas cost is high (~1M) but no "technical" limit is set. 24 | // However, the high gas cost creates an obvious limitation due to the block gas limit. 25 | if (premiumCost) { 26 | for (uint256 i = 0; i < 21129; i++) {} 27 | } else { 28 | require( 29 | forcedRequestsInBlock[block.number] < MAX_FORCED_ACTIONS_REQS_PER_BLOCK, 30 | "MAX_REQUESTS_PER_BLOCK_REACHED" 31 | ); 32 | forcedRequestsInBlock[block.number] += 1; 33 | } 34 | forcedActionRequests[actionHash] = block.timestamp; 35 | actionHashList.push(actionHash); 36 | } 37 | 38 | function getActionCount() external view returns (uint256) { 39 | return actionHashList.length; 40 | } 41 | 42 | function getActionHashByIndex(uint256 actionIndex) external view returns (bytes32) { 43 | require(actionIndex < actionHashList.length, "ACTION_INDEX_TOO_HIGH"); 44 | return actionHashList[actionIndex]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/AvailabilityVerifiers.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MApprovalChain.sol"; 5 | import "../libraries/LibConstants.sol"; 6 | import "./MainStorage.sol"; 7 | 8 | /** 9 | A :sol:mod:`Committee` contract is a contract that the exchange service sends committee member 10 | signatures to attesting that they have a copy of the data over which a new Merkel root is to be 11 | accepted as the new state root. In addition, the exchange contract can call an availability 12 | verifier to check if such signatures were indeed provided by a sufficient number of committee 13 | members as hard coded in the :sol:mod:`Committee` contract for a given state transition 14 | (as reflected by the old and new vault and order roots). 15 | 16 | The exchange contract will normally query only one :sol:mod:`Committee` contract for data 17 | availability checks. However, in the event that the committee needs to be updated, additional 18 | availability verifiers may be registered with the exchange contract by the 19 | contract :sol:mod:`MainGovernance`. Such new availability verifiers are then also be required to 20 | attest to the data availability for state transitions and only if all the availability verifiers 21 | attest to it, the state transition is accepted. 22 | 23 | Removal of availability verifiers is also the responsibility of the :sol:mod:`MainGovernance`. 24 | The removal process is more sensitive than availability verifier registration as it may affect the 25 | soundness of the system. Hence, this is performed in two steps: 26 | 27 | 1. The :sol:mod:`MainGovernance` first announces the intent to remove an availability verifier by calling :sol:func:`announceAvailabilityVerifierRemovalIntent` 28 | 2. After the expiration of a `VERIFIER_REMOVAL_DELAY` time lock, actual removal may be performed by calling :sol:func:`removeAvailabilityVerifier` 29 | 30 | The removal delay ensures that a user concerned about the soundness of the system has ample time 31 | to leave the exchange. 32 | */ 33 | abstract contract AvailabilityVerifiers is MainStorage, LibConstants, MApprovalChain { 34 | function getRegisteredAvailabilityVerifiers() 35 | external 36 | view 37 | returns (address[] memory _verifers) 38 | { 39 | return availabilityVerifiersChain.list; 40 | } 41 | 42 | function isAvailabilityVerifier(address verifierAddress) external view returns (bool) { 43 | return findEntry(availabilityVerifiersChain.list, verifierAddress) != ENTRY_NOT_FOUND; 44 | } 45 | 46 | function registerAvailabilityVerifier(address verifier, string calldata identifier) external { 47 | addEntry(availabilityVerifiersChain, verifier, MAX_VERIFIER_COUNT, identifier); 48 | } 49 | 50 | function announceAvailabilityVerifierRemovalIntent(address verifier) external { 51 | announceRemovalIntent(availabilityVerifiersChain, verifier, VERIFIER_REMOVAL_DELAY); 52 | } 53 | 54 | function removeAvailabilityVerifier(address verifier) external { 55 | removeEntry(availabilityVerifiersChain, verifier); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/ECDSA.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../third_party/EllipticCurve.sol"; 5 | 6 | library ECDSA { 7 | using EllipticCurve for uint256; 8 | uint256 constant FIELD_PRIME = 9 | 0x800000000000011000000000000000000000000000000000000000000000001; 10 | uint256 constant ALPHA = 1; 11 | uint256 constant BETA = 12 | 3141592653589793238462643383279502884197169399375105820974944592307816406665; 13 | uint256 constant EC_ORDER = 14 | 3618502788666131213697322783095070105526743751716087489154079457884512865583; 15 | uint256 constant N_ELEMENT_BITS_ECDSA = 251; 16 | uint256 constant EC_GEN_X = 0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca; 17 | uint256 constant EC_GEN_Y = 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f; 18 | 19 | function verify( 20 | uint256 msgHash, 21 | uint256 r, 22 | uint256 s, 23 | uint256 pubX, 24 | uint256 pubY 25 | ) internal pure { 26 | require(msgHash % EC_ORDER == msgHash, "msgHash out of range"); 27 | require((1 <= s) && (s < EC_ORDER), "s out of range"); 28 | uint256 w = s.invMod(EC_ORDER); 29 | require((1 <= r) && (r < (1 << N_ELEMENT_BITS_ECDSA)), "r out of range"); 30 | require((1 <= w) && (w < (1 << N_ELEMENT_BITS_ECDSA)), "w out of range"); 31 | 32 | // Verify that pub is a valid point (y^2 = x^3 + x + BETA). 33 | { 34 | uint256 x3 = mulmod(mulmod(pubX, pubX, FIELD_PRIME), pubX, FIELD_PRIME); 35 | uint256 y2 = mulmod(pubY, pubY, FIELD_PRIME); 36 | require( 37 | y2 == addmod(addmod(x3, pubX, FIELD_PRIME), BETA, FIELD_PRIME), 38 | "INVALID_STARK_KEY" 39 | ); 40 | } 41 | 42 | // Verify signature. 43 | uint256 b_x; 44 | uint256 b_y; 45 | { 46 | (uint256 zG_x, uint256 zG_y) = msgHash.ecMul(EC_GEN_X, EC_GEN_Y, ALPHA, FIELD_PRIME); 47 | 48 | (uint256 rQ_x, uint256 rQ_y) = r.ecMul(pubX, pubY, ALPHA, FIELD_PRIME); 49 | 50 | (b_x, b_y) = zG_x.ecAdd(zG_y, rQ_x, rQ_y, ALPHA, FIELD_PRIME); 51 | } 52 | (uint256 res_x, ) = w.ecMul(b_x, b_y, ALPHA, FIELD_PRIME); 53 | 54 | require(res_x == r, "INVALID_STARK_SIGNATURE"); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/ERC1155Receiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../tokens/ERC1155/IERC1155Receiver.sol"; 5 | 6 | /* 7 | ERC1155 token receiver interface. 8 | EIP-1155 requires any contract receiving ERC1155 tokens to implement IERC1155Receiver interface. 9 | By EIP: 10 | 1. safeTransferFrom API of ERC1155 shall call onERC1155Received on the receiving contract. 11 | 2. safeBatchTransferFrom API of ERC1155 to call onERC1155BatchReceived on the receiving contract. 12 | 13 | Have the receiving contract failed to respond as expected, the safe transfer functions shall be reverted. 14 | */ 15 | contract ERC1155Receiver is IERC1155Receiver { 16 | /** 17 | Handles the receipt of a single ERC1155 token type. 18 | @param `operator` The address which called `safeTransferFrom` function 19 | @param `from` The address which previously owned the token 20 | @param `id` The identifier of the token which is being transferred 21 | @param `value` the amount of token units being transferred 22 | @param `data` Additional data with no specified format 23 | Returns: 24 | When invoked by the receiving contract, satisfying the deposit pattern (i.e. operator == this) 25 | `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` is returned. 26 | In all other cases returns `bytes4(0)`, which should invoke an error of the form 27 | `ERC1155: ERC1155Receiver rejected tokens`. 28 | */ 29 | function onERC1155Received( 30 | address operator, 31 | address, // from 32 | uint256, // id 33 | uint256, // value 34 | bytes calldata // data 35 | ) external override returns (bytes4) { 36 | return (operator == address(this) ? this.onERC1155Received.selector : bytes4(0)); 37 | } 38 | 39 | /** 40 | Handles the receipt of multiple ERC1155 token types. 41 | @param `operator` The address which called `safeBatchTransferFrom` function 42 | @param `from` The address which previously owned the token 43 | @param `ids` The identifier of the token which is being transferred 44 | @param `values` the amount of token units being transferred 45 | @param `data` Additional data with no specified format 46 | Returns: 47 | When invoked by the receiving contract, satisfying the deposit pattern (i.e. operator == this) 48 | `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)"))` is returned. 49 | In all other cases returns `bytes4(0)`, which should invoke an error of the form 50 | `ERC1155: ERC1155Receiver rejected tokens`. 51 | 52 | Note: a rejection value `bytes4(0)` is to be expected. Batch deposits are unsupported by StarkEx. 53 | */ 54 | function onERC1155BatchReceived( 55 | address operator, 56 | address, // from 57 | uint256[] calldata, // ids 58 | uint256[] calldata, // values 59 | bytes calldata // data 60 | ) external override returns (bytes4) { 61 | return (operator == address(this) ? this.onERC1155BatchReceived.selector : bytes4(0)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/ERC721Receiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../tokens/ERC721/IERC721Receiver.sol"; 5 | 6 | /* 7 | ERC721 token receiver interface 8 | EIP-721 requires any contract receiving ERC721 tokens to implement IERC721Receiver interface. 9 | By EIP, safeTransferFrom API of ERC721 shall call onERC721Received on the receiving contract. 10 | 11 | Have the receiving contract failed to respond as expected, the safeTransferFrom shall be reverted. 12 | 13 | Params: 14 | `operator` The address which called `safeTransferFrom` function 15 | `from` The address which previously owned the token 16 | `tokenId` The NFT identifier which is being transferred 17 | `data` Additional data with no specified format 18 | 19 | Returns: 20 | When invoked by the main contract, following the deposit pattern: 21 | `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, which indicates success. 22 | In all other cases: `bytes4(0)`, which should fail ERC721's safeTransferFrom. 23 | */ 24 | contract ERC721Receiver is IERC721Receiver { 25 | function onERC721Received( 26 | address operator, // The address which called `safeTransferFrom` function. 27 | address, // from - The address which previously owned the token. 28 | uint256, // tokenId - The NFT identifier which is being transferred. 29 | bytes calldata // data - Additional data with no specified format. 30 | ) external override returns (bytes4) { 31 | return (operator == address(this) ? this.onERC721Received.selector : bytes4(0)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/FactRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/IQueryableFactRegistry.sol"; 5 | 6 | contract FactRegistry is IQueryableFactRegistry { 7 | // Mapping: fact hash -> true. 8 | mapping(bytes32 => bool) private verifiedFact; 9 | 10 | // Indicates whether the Fact Registry has at least one fact registered. 11 | bool anyFactRegistered; 12 | 13 | /* 14 | Checks if a fact has been verified. 15 | */ 16 | function isValid(bytes32 fact) external view override returns (bool) { 17 | return _factCheck(fact); 18 | } 19 | 20 | /* 21 | This is an internal method to check if the fact is already registered. 22 | In current implementation of FactRegistry it's identical to isValid(). 23 | But the check is against the local fact registry, 24 | So for a derived referral fact registry, it's not the same. 25 | */ 26 | function _factCheck(bytes32 fact) internal view returns (bool) { 27 | return verifiedFact[fact]; 28 | } 29 | 30 | function registerFact(bytes32 factHash) internal { 31 | // This function stores the fact hash in the mapping. 32 | verifiedFact[factHash] = true; 33 | 34 | // Mark first time off. 35 | if (!anyFactRegistered) { 36 | anyFactRegistered = true; 37 | } 38 | } 39 | 40 | /* 41 | Indicates whether at least one fact was registered. 42 | */ 43 | function hasRegisteredFact() external view override returns (bool) { 44 | return anyFactRegistered; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/Freezable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../libraries/LibConstants.sol"; 5 | import "../interfaces/MFreezable.sol"; 6 | import "../interfaces/MGovernance.sol"; 7 | import "./MainStorage.sol"; 8 | 9 | /* 10 | Implements MFreezable. 11 | */ 12 | abstract contract Freezable is MainStorage, LibConstants, MGovernance, MFreezable { 13 | event LogFrozen(); 14 | event LogUnFrozen(); 15 | 16 | function isFrozen() public view override returns (bool) { 17 | return stateFrozen; 18 | } 19 | 20 | function validateFreezeRequest(uint256 requestTime) internal override { 21 | require(requestTime != 0, "FORCED_ACTION_UNREQUESTED"); 22 | // Verify timer on escape request. 23 | uint256 freezeTime = requestTime + FREEZE_GRACE_PERIOD; 24 | 25 | // Prevent wraparound. 26 | assert(freezeTime >= FREEZE_GRACE_PERIOD); 27 | require(block.timestamp >= freezeTime, "FORCED_ACTION_PENDING"); // NOLINT: timestamp. 28 | 29 | // Forced action requests placed before freeze, are no longer valid after the un-freeze. 30 | require(freezeTime > unFreezeTime, "REFREEZE_ATTEMPT"); 31 | } 32 | 33 | function freeze() internal override notFrozen { 34 | unFreezeTime = block.timestamp + UNFREEZE_DELAY; 35 | 36 | // Update state. 37 | stateFrozen = true; 38 | 39 | // Log event. 40 | emit LogFrozen(); 41 | } 42 | 43 | function unFreeze() external onlyFrozen onlyGovernance { 44 | require(block.timestamp >= unFreezeTime, "UNFREEZE_NOT_ALLOWED_YET"); 45 | 46 | // Update state. 47 | stateFrozen = false; 48 | 49 | // Increment roots to invalidate them, w/o losing information. 50 | validiumVaultRoot += 1; 51 | rollupVaultRoot += 1; 52 | orderRoot += 1; 53 | 54 | // Log event. 55 | emit LogUnFrozen(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/GenericGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./Governance.sol"; 5 | 6 | contract GenericGovernance is Governance { 7 | bytes32 immutable GOVERNANCE_INFO_TAG_HASH; 8 | 9 | constructor(string memory governanceContext) public { 10 | GOVERNANCE_INFO_TAG_HASH = keccak256(abi.encodePacked(governanceContext)); 11 | } 12 | 13 | /* 14 | Returns the GovernanceInfoStruct associated with the governance tag. 15 | */ 16 | function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage gub) { 17 | bytes32 location = GOVERNANCE_INFO_TAG_HASH; 18 | assembly { 19 | gub_slot := location 20 | } 21 | } 22 | 23 | function isGovernor(address testGovernor) external view returns (bool) { 24 | return _isGovernor(testGovernor); 25 | } 26 | 27 | function nominateNewGovernor(address newGovernor) external { 28 | _nominateNewGovernor(newGovernor); 29 | } 30 | 31 | function removeGovernor(address governorForRemoval) external { 32 | _removeGovernor(governorForRemoval); 33 | } 34 | 35 | function acceptGovernance() external { 36 | _acceptGovernance(); 37 | } 38 | 39 | function cancelNomination() external { 40 | _cancelNomination(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/GovernanceStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | import "../interfaces/MGovernance.sol"; 4 | 5 | /* 6 | Holds the governance slots for ALL entities, including proxy and the main contract. 7 | */ 8 | contract GovernanceStorage { 9 | // A map from a Governor tag to its own GovernanceInfoStruct. 10 | mapping(string => GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state. 11 | } 12 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/GpsFactRegistryAdapter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/Identity.sol"; 5 | import "../interfaces/IQueryableFactRegistry.sol"; 6 | 7 | /* 8 | The GpsFactRegistryAdapter contract is used as an adapter between a Dapp contract and a GPS fact 9 | registry. An isValid(fact) query is answered by querying the GPS contract about 10 | new_fact := keccak256(programHash, fact). 11 | 12 | The goal of this contract is to simplify the verifier upgradability logic in the Dapp contract 13 | by making the upgrade flow the same regardless of whether the update is to the program hash or 14 | the gpsContractAddress. 15 | */ 16 | contract GpsFactRegistryAdapter is IQueryableFactRegistry, Identity { 17 | IQueryableFactRegistry public gpsContract; 18 | uint256 public programHash; 19 | 20 | constructor(IQueryableFactRegistry gpsStatementContract, uint256 programHash_) public { 21 | gpsContract = gpsStatementContract; 22 | programHash = programHash_; 23 | } 24 | 25 | function identify() external pure virtual override returns (string memory) { 26 | return "StarkWare_GpsFactRegistryAdapter_2020_1"; 27 | } 28 | 29 | /* 30 | Checks if a fact has been verified. 31 | */ 32 | function isValid(bytes32 fact) external view override returns (bool) { 33 | return gpsContract.isValid(keccak256(abi.encode(programHash, fact))); 34 | } 35 | 36 | /* 37 | Indicates whether at least one fact was registered. 38 | */ 39 | function hasRegisteredFact() external view override returns (bool) { 40 | return gpsContract.hasRegisteredFact(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/KeyGetters.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/MainStorage.sol"; 5 | import "../interfaces/MKeyGetters.sol"; 6 | 7 | /* 8 | Implements MKeyGetters. 9 | */ 10 | contract KeyGetters is MainStorage, MKeyGetters { 11 | uint256 internal constant MASK_ADDRESS = (1 << 160) - 1; 12 | 13 | /* 14 | Returns the Ethereum public key (address) that owns the given ownerKey. 15 | If the ownerKey size is within the range of an Ethereum address (i.e. < 2**160) 16 | it returns the owner key itself. 17 | 18 | If the ownerKey is larger than a potential eth address, the eth address for which the starkKey 19 | was registered is returned, and 0 if the starkKey is not registered. 20 | 21 | Note - prior to version 4.0 this function reverted on an unregistered starkKey. 22 | For a variant of this function that reverts on an unregistered starkKey, use strictGetEthKey. 23 | */ 24 | function getEthKey(uint256 ownerKey) public view override returns (address) { 25 | address registeredEth = ethKeys[ownerKey]; 26 | 27 | if (registeredEth != address(0x0)) { 28 | return registeredEth; 29 | } 30 | 31 | return ownerKey == (ownerKey & MASK_ADDRESS) ? address(ownerKey) : address(0x0); 32 | } 33 | 34 | /* 35 | Same as getEthKey, but fails when a stark key is not registered. 36 | */ 37 | function strictGetEthKey(uint256 ownerKey) internal view override returns (address ethKey) { 38 | ethKey = getEthKey(ownerKey); 39 | require(ethKey != address(0x0), "USER_UNREGISTERED"); 40 | } 41 | 42 | function isMsgSenderKeyOwner(uint256 ownerKey) internal view override returns (bool) { 43 | return msg.sender == getEthKey(ownerKey); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/MainGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./Governance.sol"; 5 | import "./GovernanceStorage.sol"; 6 | 7 | /** 8 | The StarkEx contract is governed by one or more Governors of which the initial one is the 9 | deployer of the contract. 10 | 11 | A governor has the sole authority to perform the following operations: 12 | 13 | 1. Nominate additional governors (:sol:func:`mainNominateNewGovernor`) 14 | 2. Remove other governors (:sol:func:`mainRemoveGovernor`) 15 | 3. Add new :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers` 16 | 4. Remove :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers` after a timelock allows it 17 | 5. Nominate Operators (see :sol:mod:`Operator`) and Token Administrators (see :sol:mod:`TokenRegister`) 18 | 19 | Adding governors is performed in a two step procedure: 20 | 21 | 1. First, an existing governor nominates a new governor (:sol:func:`mainNominateNewGovernor`) 22 | 2. Then, the new governor must accept governance to become a governor (:sol:func:`mainAcceptGovernance`) 23 | 24 | This two step procedure ensures that a governor public key cannot be nominated unless there is an 25 | entity that has the corresponding private key. This is intended to prevent errors in the addition 26 | process. 27 | 28 | The governor private key should typically be held in a secure cold wallet. 29 | */ 30 | /* 31 | Implements Governance for the StarkDex main contract. 32 | The wrapper methods (e.g. mainIsGovernor wrapping _isGovernor) are needed to give 33 | the method unique names. 34 | Both Proxy and StarkExchange inherit from Governance. Thus, the logical contract method names 35 | must have unique names in order for the proxy to successfully delegate to them. 36 | */ 37 | contract MainGovernance is GovernanceStorage, Governance { 38 | // The tag is the sting key that is used in the Governance storage mapping. 39 | string public constant MAIN_GOVERNANCE_INFO_TAG = "StarkEx.Main.2019.GovernorsInformation"; 40 | 41 | /* 42 | Returns the GovernanceInfoStruct associated with the governance tag. 43 | */ 44 | function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { 45 | return governanceInfo[MAIN_GOVERNANCE_INFO_TAG]; 46 | } 47 | 48 | function mainIsGovernor(address testGovernor) external view returns (bool) { 49 | return _isGovernor(testGovernor); 50 | } 51 | 52 | function mainNominateNewGovernor(address newGovernor) external { 53 | _nominateNewGovernor(newGovernor); 54 | } 55 | 56 | function mainRemoveGovernor(address governorForRemoval) external { 57 | _removeGovernor(governorForRemoval); 58 | } 59 | 60 | function mainAcceptGovernance() external { 61 | _acceptGovernance(); 62 | } 63 | 64 | function mainCancelNomination() external { 65 | _cancelNomination(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/MessageRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/Identity.sol"; 5 | import "./FactRegistry.sol"; 6 | 7 | contract MessageRegistry is FactRegistry, Identity { 8 | event LogMsgRegistered(address from, address to, bytes32 msgHash); 9 | 10 | function identify() external pure virtual override returns (string memory) { 11 | return "StarkWare_MessageRegistry_2021_1"; 12 | } 13 | 14 | // NOLINTNEXTLINE: external-function. 15 | function registerMessage(address to, bytes32 messageHash) public { 16 | bytes32 messageFact = keccak256(abi.encodePacked(msg.sender, to, messageHash)); 17 | registerFact(messageFact); 18 | emit LogMsgRegistered(msg.sender, to, messageHash); 19 | } 20 | 21 | function isMessageRegistered( 22 | address from, 23 | address to, 24 | bytes32 messageHash 25 | ) external view returns (bool) { 26 | bytes32 messageFact = keccak256(abi.encodePacked(from, to, messageHash)); 27 | return _factCheck(messageFact); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/OnchainDataFactTreeEncoder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | library OnchainDataFactTreeEncoder { 5 | struct DataAvailabilityFact { 6 | uint256 onchainDataHash; 7 | uint256 onchainDataSize; 8 | } 9 | 10 | // The number of additional words appended to the public input when using the 11 | // OnchainDataFactTreeEncoder format. 12 | uint256 internal constant ONCHAIN_DATA_FACT_ADDITIONAL_WORDS = 2; 13 | 14 | /* 15 | Encodes a GPS fact Merkle tree where the root has two children. 16 | The left child contains the data we care about and the right child contains 17 | on-chain data for the fact. 18 | */ 19 | function encodeFactWithOnchainData( 20 | uint256[] calldata programOutput, 21 | DataAvailabilityFact memory factData 22 | ) internal pure returns (bytes32) { 23 | // The state transition fact is computed as a Merkle tree, as defined in 24 | // GpsOutputParser. 25 | // 26 | // In our case the fact tree looks as follows: 27 | // The root has two children. 28 | // The left child is a leaf that includes the main part - the information regarding 29 | // the state transition required by this contract. 30 | // The right child contains the onchain-data which shouldn't be accessed by this 31 | // contract, so we are only given its hash and length 32 | // (it may be a leaf or an inner node, this has no effect on this contract). 33 | 34 | // Compute the hash without the two additional fields. 35 | uint256 mainPublicInputLen = programOutput.length; 36 | bytes32 mainPublicInputHash = keccak256(abi.encodePacked(programOutput)); 37 | 38 | // Compute the hash of the fact Merkle tree. 39 | bytes32 hashResult = keccak256( 40 | abi.encodePacked( 41 | mainPublicInputHash, 42 | mainPublicInputLen, 43 | factData.onchainDataHash, 44 | mainPublicInputLen + factData.onchainDataSize 45 | ) 46 | ); 47 | // Add one to the hash to indicate it represents an inner node, rather than a leaf. 48 | return bytes32(uint256(hashResult) + 1); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/Operator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MOperator.sol"; 5 | import "../interfaces/MGovernance.sol"; 6 | 7 | /** 8 | The Operator of the contract is the entity entitled to submit state update requests 9 | by calling :sol:func:`updateState`. 10 | 11 | An Operator may be instantly appointed or removed by the contract Governor 12 | (see :sol:mod:`Governance`). Typically, the Operator is the hot wallet of the service 13 | submitting proofs for state updates. 14 | */ 15 | abstract contract Operator is MGovernance, MOperator { 16 | function registerOperator(address newOperator) external override onlyGovernance { 17 | getOperators()[newOperator] = true; 18 | emit LogOperatorAdded(newOperator); 19 | } 20 | 21 | function unregisterOperator(address removedOperator) external override onlyGovernance { 22 | getOperators()[removedOperator] = false; 23 | emit LogOperatorRemoved(removedOperator); 24 | } 25 | 26 | function isOperator(address testedOperator) public view override returns (bool) { 27 | return getOperators()[testedOperator]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/StarkExOperator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./Operator.sol"; 5 | import "./MainStorage.sol"; 6 | 7 | /** 8 | Operator implementation for StarkEx (StarkExchange & StarkPerpetual). 9 | */ 10 | abstract contract StarkExOperator is MainStorage, Operator { 11 | function initialize() internal { 12 | getOperators()[msg.sender] = true; 13 | emit LogOperatorAdded(msg.sender); 14 | } 15 | 16 | function getOperators() internal view override returns (mapping(address => bool) storage) { 17 | return operators; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/Verifiers.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MApprovalChain.sol"; 5 | import "../libraries/LibConstants.sol"; 6 | import "./MainStorage.sol"; 7 | 8 | /** 9 | A Verifier contract is an implementation of a STARK verifier that the exchange service sends 10 | STARK proofs to. In addition, the exchange contract can call a verifier to check if a valid proof 11 | has been accepted for a given state transition (typically described as a hash on the public input 12 | of the assumed proof). 13 | 14 | The exchange contract will normally query only one verifier contract for proof validity checks. 15 | However, in the event that the verifier algorithm needs to updated, additional verifiers may be 16 | registered with the exchange contract by the contract :sol:mod:`MainGovernance`. Such new 17 | verifiers are then also be required to attest to the validity of state transitions and only if all 18 | the verifiers attest to the validity the state transition is accepted. 19 | 20 | Removal of verifiers is also the responsibility of the :sol:mod:`MainGovernance`. The removal 21 | process is more sensitive than verifier registration as it may affect the soundness of the system. 22 | Hence, this is performed in two steps: 23 | 24 | 1. The :sol:mod:`MainGovernance` first announces the intent to remove a verifier by calling :sol:func:`announceVerifierRemovalIntent` 25 | 2. After the expiration of a `VERIFIER_REMOVAL_DELAY` time lock, actual removal may be performed by calling :sol:func:`removeVerifier` 26 | 27 | The removal delay ensures that a user concerned about the soundness of the system has ample time 28 | to leave the exchange. 29 | */ 30 | abstract contract Verifiers is MainStorage, LibConstants, MApprovalChain { 31 | function getRegisteredVerifiers() external view returns (address[] memory _verifers) { 32 | return verifiersChain.list; 33 | } 34 | 35 | function isVerifier(address verifierAddress) external view returns (bool) { 36 | return findEntry(verifiersChain.list, verifierAddress) != ENTRY_NOT_FOUND; 37 | } 38 | 39 | function registerVerifier(address verifier, string calldata identifier) external { 40 | addEntry(verifiersChain, verifier, MAX_VERIFIER_COUNT, identifier); 41 | } 42 | 43 | function announceVerifierRemovalIntent(address verifier) external { 44 | announceRemovalIntent(verifiersChain, verifier, VERIFIER_REMOVAL_DELAY); 45 | } 46 | 47 | function removeVerifier(address verifier) external { 48 | removeEntry(verifiersChain, verifier); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/components/VerifyFactChain.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./MainStorage.sol"; 5 | import "../interfaces/IFactRegistry.sol"; 6 | import "../libraries/Common.sol"; 7 | 8 | contract VerifyFactChain is MainStorage { 9 | function verifyFact( 10 | StarkExTypes.ApprovalChainData storage chain, 11 | bytes32 fact, 12 | string memory noVerifiersErrorMessage, 13 | string memory invalidFactErrorMessage 14 | ) internal view { 15 | address[] storage list = chain.list; 16 | uint256 n_entries = list.length; 17 | require(n_entries > 0, noVerifiersErrorMessage); 18 | for (uint256 i = 0; i < n_entries; i++) { 19 | // NOLINTNEXTLINE: calls-loop. 20 | require(IFactRegistry(list[i]).isValid(fact), invalidFactErrorMessage); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/cpu/MemoryPageFactRegistry.sol: -------------------------------------------------------------------------------- 1 | evm-verifier/solidity/contracts/cpu/MemoryPageFactRegistry.sol -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interactions/CompositeActionsV2.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MDeposits.sol"; 5 | import "../interfaces/MUsersV2.sol"; 6 | 7 | abstract contract CompositeActionsV2 is MDeposits, MUsersV2 { 8 | function registerAndDepositERC20( 9 | address ethKey, 10 | uint256 starkKey, 11 | bytes calldata signature, 12 | uint256 assetType, 13 | uint256 vaultId, 14 | uint256 quantizedAmount 15 | ) external { 16 | registerUser(ethKey, starkKey, signature); 17 | depositERC20(starkKey, assetType, vaultId, quantizedAmount); 18 | } 19 | 20 | // NOLINTNEXTLINE locked-ether. 21 | function registerAndDepositEth( 22 | address ethKey, 23 | uint256 starkKey, 24 | bytes calldata signature, 25 | uint256 assetType, 26 | uint256 vaultId 27 | ) external payable { 28 | registerUser(ethKey, starkKey, signature); 29 | depositEth(starkKey, assetType, vaultId); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interactions/StateRoot.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MStateRoot.sol"; 5 | import "../components/MainStorage.sol"; 6 | import "../libraries/LibConstants.sol"; 7 | 8 | contract StateRoot is MainStorage, LibConstants, MStateRoot { 9 | function initialize( 10 | uint256 initialSequenceNumber, 11 | uint256 initialValidiumVaultRoot, 12 | uint256 initialRollupVaultRoot, 13 | uint256 initialOrderRoot, 14 | uint256 initialValidiumTreeHeight, 15 | uint256 initialRollupTreeHeight, 16 | uint256 initialOrderTreeHeight 17 | ) internal { 18 | sequenceNumber = initialSequenceNumber; 19 | validiumVaultRoot = initialValidiumVaultRoot; 20 | rollupVaultRoot = initialRollupVaultRoot; 21 | orderRoot = initialOrderRoot; 22 | validiumTreeHeight = initialValidiumTreeHeight; 23 | rollupTreeHeight = initialRollupTreeHeight; 24 | orderTreeHeight = initialOrderTreeHeight; 25 | } 26 | 27 | function getValidiumVaultRoot() public view override returns (uint256) { 28 | return validiumVaultRoot; 29 | } 30 | 31 | function getValidiumTreeHeight() public view override returns (uint256) { 32 | return validiumTreeHeight; 33 | } 34 | 35 | function getRollupVaultRoot() public view override returns (uint256) { 36 | return rollupVaultRoot; 37 | } 38 | 39 | function getRollupTreeHeight() public view override returns (uint256) { 40 | return rollupTreeHeight; 41 | } 42 | 43 | function getOrderRoot() external view returns (uint256) { 44 | return orderRoot; 45 | } 46 | 47 | function getOrderTreeHeight() external view returns (uint256) { 48 | return orderTreeHeight; 49 | } 50 | 51 | function getSequenceNumber() external view returns (uint256) { 52 | return sequenceNumber; 53 | } 54 | 55 | function getLastBatchId() external view returns (uint256) { 56 | return lastBatchId; 57 | } 58 | 59 | function getGlobalConfigCode() external view returns (uint256) { 60 | return globalConfigCode; 61 | } 62 | 63 | function isVaultInRange(uint256 vaultId) internal view override returns (bool) { 64 | return (isValidiumVault(vaultId) || isRollupVault(vaultId)); 65 | } 66 | 67 | function isValidiumVault(uint256 vaultId) internal view override returns (bool) { 68 | // Return true iff vaultId is in the validium vaults tree. 69 | return vaultId < 2**getValidiumTreeHeight(); 70 | } 71 | 72 | function isRollupVault(uint256 vaultId) internal view override returns (bool) { 73 | // Return true iff vaultId is in the rollup vaults tree. 74 | uint256 rollupLowerBound = 2**ROLLUP_VAULTS_BIT; 75 | uint256 rollupUpperBound = rollupLowerBound + 2**getRollupTreeHeight(); 76 | return (rollupLowerBound <= vaultId && vaultId < rollupUpperBound); 77 | } 78 | 79 | function getVaultLeafIndex(uint256 vaultId) internal pure override returns (uint256) { 80 | // Return the index of vaultId leaf in its tree, which doesn't include the rollup bit flag. 81 | return (vaultId & (2**ROLLUP_VAULTS_BIT - 1)); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interactions/TokenQuantization.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/MainStorage.sol"; 5 | import "../interfaces/MTokenQuantization.sol"; 6 | 7 | contract TokenQuantization is MainStorage, MTokenQuantization { 8 | function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount) 9 | internal 10 | view 11 | override 12 | returns (uint256 amount) 13 | { 14 | uint256 quantum = getQuantum(presumedAssetType); 15 | amount = quantizedAmount * quantum; 16 | require(amount / quantum == quantizedAmount, "DEQUANTIZATION_OVERFLOW"); 17 | } 18 | 19 | function getQuantum(uint256 presumedAssetType) public view override returns (uint256 quantum) { 20 | if (!registeredAssetType[presumedAssetType]) { 21 | // Default quantization, for NFTs etc. 22 | quantum = 1; 23 | } else { 24 | // Retrieve registration. 25 | quantum = assetTypeToQuantum[presumedAssetType]; 26 | } 27 | } 28 | 29 | function toQuantized(uint256 presumedAssetType, uint256 amount) 30 | internal 31 | view 32 | override 33 | returns (uint256 quantizedAmount) 34 | { 35 | uint256 quantum = getQuantum(presumedAssetType); 36 | require(amount % quantum == 0, "INVALID_AMOUNT"); 37 | quantizedAmount = amount / quantum; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/BlockDirectCall.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | This contract provides means to block direct call of an external function. 6 | A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the 7 | notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only calling 8 | using delegate_call. 9 | */ 10 | abstract contract BlockDirectCall { 11 | address immutable this_; 12 | 13 | constructor() internal { 14 | this_ = address(this); 15 | } 16 | 17 | modifier notCalledDirectly() { 18 | require(this_ != address(this), "DIRECT_CALL_DISALLOWED"); 19 | _; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/ContractInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | Interface for contract initialization. 6 | The functions it exposes are the app specific parts of the contract initialization, 7 | and are called by the ProxySupport contract that implement the generic part of behind-proxy 8 | initialization. 9 | */ 10 | abstract contract ContractInitializer { 11 | function numOfSubContracts() internal pure virtual returns (uint256); 12 | 13 | function isInitialized() internal view virtual returns (bool); 14 | 15 | function validateInitData(bytes calldata data) internal pure virtual; 16 | 17 | function processSubContractAddresses(bytes calldata subContractAddresses) internal virtual; 18 | 19 | function initializeContractState(bytes calldata data) internal virtual; 20 | } 21 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/ExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface ExternalInitializer { 5 | event LogExternalInitialize(bytes data); 6 | 7 | function initialize(bytes calldata data) external; 8 | } 9 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IAvailabilityVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IAvailabilityVerifier { 5 | /* 6 | Verifies the availability proof. Reverts if invalid. 7 | */ 8 | function verifyAvailabilityProof(bytes32 claimHash, bytes calldata availabilityProofs) external; 9 | } 10 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IDispatcherBase.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Interface for a generic dispatcher to use, which the concrete dispatcher must implement. 6 | It contains the functions that are specific to the concrete dispatcher instance. 7 | The interface is implemented as contract, because interface implies all methods external. 8 | */ 9 | abstract contract IDispatcherBase { 10 | function getSubContract(bytes4 selector) public view virtual returns (address); 11 | 12 | function setSubContractAddress(uint256 index, address subContract) internal virtual; 13 | 14 | function getNumSubcontracts() internal pure virtual returns (uint256); 15 | 16 | function validateSubContractIndex(uint256 index, address subContract) internal pure virtual; 17 | 18 | /* 19 | Ensures initializer can be called. Reverts otherwise. 20 | */ 21 | function initializationSentinel() internal view virtual; 22 | } 23 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IFactRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | The Fact Registry design pattern is a way to separate cryptographic verification from the 6 | business logic of the contract flow. 7 | 8 | A fact registry holds a hash table of verified "facts" which are represented by a hash of claims 9 | that the registry hash check and found valid. This table may be queried by accessing the 10 | isValid() function of the registry with a given hash. 11 | 12 | In addition, each fact registry exposes a registry specific function for submitting new claims 13 | together with their proofs. The information submitted varies from one registry to the other 14 | depending of the type of fact requiring verification. 15 | 16 | For further reading on the Fact Registry design pattern see this 17 | `StarkWare blog post `_. 18 | */ 19 | interface IFactRegistry { 20 | /* 21 | Returns true if the given fact was previously registered in the contract. 22 | */ 23 | function isValid(bytes32 fact) external view returns (bool); 24 | } 25 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IIdentity.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IIdentity { 5 | /* 6 | Allows a caller to ensure that the provided address is of the expected type and version. 7 | */ 8 | function identify() external pure returns (string memory); 9 | } 10 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IQueryableFactRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./IFactRegistry.sol"; 5 | 6 | /* 7 | Extends the IFactRegistry interface with a query method that indicates 8 | whether the fact registry has successfully registered any fact or is still empty of such facts. 9 | */ 10 | interface IQueryableFactRegistry is IFactRegistry { 11 | /* 12 | Returns true if at least one fact has been registered. 13 | */ 14 | function hasRegisteredFact() external view returns (bool); 15 | } 16 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/IStarkVerifier.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IStarkVerifier { 5 | function verifyProof( 6 | uint256[] calldata proofParams, 7 | uint256[] calldata proof, 8 | uint256[] calldata publicInput 9 | ) external; 10 | } 11 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/Identity.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface Identity { 5 | /* 6 | Allows a caller, typically another contract, 7 | to ensure that the provided address is of the expected type and version. 8 | */ 9 | function identify() external pure returns (string memory); 10 | } 11 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MAcceptModifications.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Interface containing actions a verifier can invoke on the state. 6 | The contract containing the state should implement these and verify correctness. 7 | */ 8 | abstract contract MAcceptModifications { 9 | function acceptDeposit( 10 | uint256 ownerKey, 11 | uint256 vaultId, 12 | uint256 assetId, 13 | uint256 quantizedAmount 14 | ) internal virtual; 15 | 16 | function allowWithdrawal( 17 | uint256 ownerKey, 18 | uint256 assetId, 19 | uint256 quantizedAmount 20 | ) internal virtual; 21 | 22 | function acceptWithdrawal( 23 | uint256 ownerKey, 24 | uint256 assetId, 25 | uint256 quantizedAmount 26 | ) internal virtual; 27 | } 28 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MApprovalChain.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../libraries/Common.sol"; 5 | 6 | /* 7 | Implements a data structure that supports instant registration 8 | and slow time-locked removal of entries. 9 | */ 10 | abstract contract MApprovalChain { 11 | uint256 constant ENTRY_NOT_FOUND = uint256(~0); 12 | 13 | /* 14 | Adds the given verifier (entry) to the chain. 15 | Fails if the size of the chain is already >= maxLength. 16 | Fails if identifier is not identical to the value returned from entry.identify(). 17 | */ 18 | function addEntry( 19 | StarkExTypes.ApprovalChainData storage chain, 20 | address entry, 21 | uint256 maxLength, 22 | string memory identifier 23 | ) internal virtual; 24 | 25 | /* 26 | Returns the index of the verifier in the list if it exists and returns ENTRY_NOT_FOUND 27 | otherwise. 28 | */ 29 | function findEntry(address[] storage list, address entry) 30 | internal 31 | view 32 | virtual 33 | returns (uint256); 34 | 35 | /* 36 | Same as findEntry(), except that it reverts if the verifier is not found. 37 | */ 38 | function safeFindEntry(address[] storage list, address entry) 39 | internal 40 | view 41 | virtual 42 | returns (uint256 idx); 43 | 44 | /* 45 | Updates the unlockedForRemovalTime field of the given verifier to 46 | current time + removalDelay. 47 | Reverts if the verifier is not found. 48 | */ 49 | function announceRemovalIntent( 50 | StarkExTypes.ApprovalChainData storage chain, 51 | address entry, 52 | uint256 removalDelay 53 | ) internal virtual; 54 | 55 | /* 56 | Removes a verifier assuming the expected time has passed. 57 | */ 58 | function removeEntry(StarkExTypes.ApprovalChainData storage chain, address entry) 59 | internal 60 | virtual; 61 | } 62 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MDeposits.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MDeposits { 5 | function depositERC20( 6 | // NOLINT external-function. 7 | uint256 starkKey, 8 | uint256 assetType, 9 | uint256 vaultId, 10 | uint256 quantizedAmount 11 | ) public virtual; 12 | 13 | function depositEth( 14 | // NOLINT external-function. 15 | uint256 starkKey, 16 | uint256 assetType, 17 | uint256 vaultId 18 | ) public payable virtual; 19 | } 20 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MFreezable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MFreezable { 5 | /* 6 | Returns true if the exchange is frozen. 7 | */ 8 | function isFrozen() public view virtual returns (bool); // NOLINT: external-function. 9 | 10 | /* 11 | Forbids calling the function if the exchange is frozen. 12 | */ 13 | modifier notFrozen() { 14 | require(!isFrozen(), "STATE_IS_FROZEN"); 15 | _; 16 | } 17 | 18 | function validateFreezeRequest(uint256 requestTime) internal virtual; 19 | 20 | /* 21 | Allows calling the function only if the exchange is frozen. 22 | */ 23 | modifier onlyFrozen() { 24 | require(isFrozen(), "STATE_NOT_FROZEN"); 25 | _; 26 | } 27 | 28 | /* 29 | Freezes the exchange. 30 | */ 31 | function freeze() internal virtual; 32 | } 33 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | struct GovernanceInfoStruct { 5 | mapping(address => bool) effectiveGovernors; 6 | address candidateGovernor; 7 | bool initialized; 8 | } 9 | 10 | abstract contract MGovernance { 11 | function _isGovernor(address testGovernor) internal view virtual returns (bool); 12 | 13 | /* 14 | Allows calling the function only by a Governor. 15 | */ 16 | modifier onlyGovernance() { 17 | require(_isGovernor(msg.sender), "ONLY_GOVERNANCE"); 18 | _; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MKeyGetters.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MKeyGetters { 5 | // NOLINTNEXTLINE: external-function. 6 | function getEthKey(uint256 ownerKey) public view virtual returns (address); 7 | 8 | function strictGetEthKey(uint256 ownerKey) internal view virtual returns (address); 9 | 10 | function isMsgSenderKeyOwner(uint256 ownerKey) internal view virtual returns (bool); 11 | 12 | /* 13 | Allows calling the function only if ownerKey is registered to msg.sender. 14 | */ 15 | modifier onlyKeyOwner(uint256 ownerKey) { 16 | // Require the calling user to own the stark key. 17 | require(msg.sender == strictGetEthKey(ownerKey), "MISMATCHING_STARK_ETH_KEYS"); 18 | _; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MOperator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./MGovernance.sol"; 5 | 6 | abstract contract MOperator { 7 | event LogOperatorAdded(address operator); 8 | event LogOperatorRemoved(address operator); 9 | 10 | function isOperator(address testedOperator) public view virtual returns (bool); 11 | 12 | modifier onlyOperator() { 13 | require(isOperator(msg.sender), "ONLY_OPERATOR"); 14 | _; 15 | } 16 | 17 | function registerOperator(address newOperator) external virtual; 18 | 19 | function unregisterOperator(address removedOperator) external virtual; 20 | 21 | function getOperators() internal view virtual returns (mapping(address => bool) storage); 22 | } 23 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MStateRoot.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MStateRoot { 5 | function getValidiumVaultRoot() public view virtual returns (uint256); 6 | 7 | function getValidiumTreeHeight() public view virtual returns (uint256); 8 | 9 | function getRollupVaultRoot() public view virtual returns (uint256); 10 | 11 | function getRollupTreeHeight() public view virtual returns (uint256); 12 | 13 | /* 14 | Returns true iff vaultId is in the valid vault ids range, 15 | i.e. could appear in either the validium or rollup vaults trees. 16 | */ 17 | function isVaultInRange(uint256 vaultId) internal view virtual returns (bool); 18 | 19 | /* 20 | Returns true if vaultId is a valid validium vault id. 21 | 22 | Note: when this function returns false it might mean that vaultId is invalid and does not 23 | guarantee that vaultId is a valid rollup vault id. 24 | */ 25 | function isValidiumVault(uint256 vaultId) internal view virtual returns (bool); 26 | 27 | /* 28 | Returns true if vaultId is a valid rollup vault id. 29 | 30 | Note: when this function returns false it might mean that vaultId is invalid and does not 31 | guarantee that vaultId is a valid validium vault id. 32 | */ 33 | function isRollupVault(uint256 vaultId) internal view virtual returns (bool); 34 | 35 | /* 36 | Given a valid vaultId, returns its leaf index in the validium/rollup tree. 37 | 38 | Note: this function does not assert the validity of vaultId, make sure to explicitly assert it 39 | when required. 40 | */ 41 | function getVaultLeafIndex(uint256 vaultId) internal pure virtual returns (uint256); 42 | } 43 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MTokenAssetData.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MTokenAssetData { 5 | // NOLINTNEXTLINE: external-function. 6 | function getAssetInfo(uint256 assetType) public view virtual returns (bytes memory); 7 | 8 | function isEther(uint256 assetType) internal view virtual returns (bool); 9 | 10 | function isERC20(uint256 assetType) internal view virtual returns (bool); 11 | 12 | function isERC721(uint256 assetType) internal view virtual returns (bool); 13 | 14 | function isERC1155(uint256 assetType) internal view virtual returns (bool); 15 | 16 | function isFungibleAssetType(uint256 assetType) internal view virtual returns (bool); 17 | 18 | function isMintableAssetType(uint256 assetType) internal view virtual returns (bool); 19 | 20 | function isAssetTypeWithTokenId(uint256 assetType) internal view virtual returns (bool); 21 | 22 | function extractContractAddress(uint256 assetType) internal view virtual returns (address); 23 | 24 | function verifyAssetInfo(bytes memory assetInfo) internal view virtual; 25 | 26 | function isNonFungibleAssetInfo(bytes memory assetInfo) internal pure virtual returns (bool); 27 | 28 | function calculateAssetIdWithTokenId(uint256 assetType, uint256 tokenId) 29 | public 30 | view 31 | virtual 32 | returns (uint256); 33 | 34 | function calculateMintableAssetId(uint256 assetType, bytes memory mintingBlob) 35 | public 36 | pure 37 | virtual 38 | returns (uint256); 39 | } 40 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MTokenQuantization.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MTokenQuantization { 5 | function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount) 6 | internal 7 | view 8 | virtual 9 | returns (uint256 amount); 10 | 11 | // NOLINTNEXTLINE: external-function. 12 | function getQuantum(uint256 presumedAssetType) public view virtual returns (uint256 quantum); 13 | 14 | function toQuantized(uint256 presumedAssetType, uint256 amount) 15 | internal 16 | view 17 | virtual 18 | returns (uint256 quantizedAmount); 19 | } 20 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MTokenTransfers.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MTokenTransfers { 5 | function transferIn(uint256 assetType, uint256 quantizedAmount) internal virtual; 6 | 7 | function transferInWithTokenId( 8 | uint256 assetType, 9 | uint256 tokenId, 10 | uint256 quantizedAmount 11 | ) internal virtual; 12 | 13 | function transferOut( 14 | address payable recipient, 15 | uint256 assetType, 16 | uint256 quantizedAmount 17 | ) internal virtual; 18 | 19 | function transferOutWithTokenId( 20 | address recipient, 21 | uint256 assetType, 22 | uint256 tokenId, 23 | uint256 quantizedAmount 24 | ) internal virtual; 25 | 26 | function transferOutMint( 27 | uint256 assetType, 28 | uint256 quantizedAmount, 29 | address recipient, 30 | bytes calldata mintingBlob 31 | ) internal virtual; 32 | } 33 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MUsersV2.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MUsersV2 { 5 | function registerUser( 6 | // NOLINT external-function. 7 | address ethKey, 8 | uint256 starkKey, 9 | bytes calldata signature 10 | ) public virtual; 11 | } 12 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/MainDispatcher.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/MainStorage.sol"; 5 | import "./MainDispatcherBase.sol"; 6 | 7 | abstract contract MainDispatcher is MainStorage, MainDispatcherBase { 8 | uint256 constant SUBCONTRACT_BITS = 4; 9 | 10 | function magicSalt() internal pure virtual returns (uint256); 11 | 12 | function handlerMapSection(uint256 section) internal pure virtual returns (uint256); 13 | 14 | function expectedIdByIndex(uint256 index) internal pure virtual returns (string memory id); 15 | 16 | function validateSubContractIndex(uint256 index, address subContract) internal pure override { 17 | string memory id = SubContractor(subContract).identify(); 18 | bytes32 hashed_expected_id = keccak256(abi.encodePacked(expectedIdByIndex(index))); 19 | require( 20 | hashed_expected_id == keccak256(abi.encodePacked(id)), 21 | "MISPLACED_INDEX_OR_BAD_CONTRACT_ID" 22 | ); 23 | 24 | // Gets the list of critical selectors from the sub-contract and checks that the selector 25 | // is mapped to that sub-contract. 26 | bytes4[] memory selectorsToValidate = SubContractor(subContract).validatedSelectors(); 27 | 28 | for (uint256 i = 0; i < selectorsToValidate.length; i++) { 29 | require( 30 | getSubContractIndex(selectorsToValidate[i]) == index, 31 | "INCONSISTENT_DISPATCHER_MAP" 32 | ); 33 | } 34 | } 35 | 36 | function handlingContractId(bytes4 selector) external pure virtual returns (string memory id) { 37 | uint256 index = getSubContractIndex(selector); 38 | return expectedIdByIndex(index); 39 | } 40 | 41 | /* 42 | Returns the index in subContracts where the address of the sub-contract implementing 43 | the function with the queried selector is held. 44 | 45 | Note: The nature of the sub-contracts handler map is such that all the required selectors 46 | are mapped. However, other selectors, such that are not implemented in any subcontract, 47 | may also return a sub-contract address. 48 | This behavior is by-design, and not a problem. 49 | */ 50 | function getSubContractIndex(bytes4 selector) internal pure returns (uint256) { 51 | uint256 location = 0xFF & uint256(keccak256(abi.encodePacked(selector, magicSalt()))); 52 | uint256 offset = (SUBCONTRACT_BITS * location) % 256; 53 | 54 | // We have 64 locations in each register, hence the >> 6 (i.e. location // 64). 55 | return (handlerMapSection(location >> 6) >> offset) & 0xF; 56 | } 57 | 58 | /* 59 | Returns the address of the sub-contract that would be delegated to handle a call 60 | with the queried selector. (see note above). 61 | */ 62 | function getSubContract(bytes4 selector) public view override returns (address) { 63 | return subContracts[getSubContractIndex(selector)]; 64 | } 65 | 66 | function setSubContractAddress(uint256 index, address subContractAddress) internal override { 67 | subContracts[index] = subContractAddress; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/ProxySupport.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/Governance.sol"; 5 | import "../libraries/Common.sol"; 6 | import "./BlockDirectCall.sol"; 7 | import "./ContractInitializer.sol"; 8 | 9 | /** 10 | This contract contains the code commonly needed for a contract to be deployed behind 11 | an upgradability proxy. 12 | It perform the required semantics of the proxy pattern, 13 | but in a generic manner. 14 | Instantiation of the Governance and of the ContractInitializer, that are the app specific 15 | part of initialization, has to be done by the using contract. 16 | */ 17 | abstract contract ProxySupport is Governance, BlockDirectCall, ContractInitializer { 18 | using Addresses for address; 19 | 20 | // The two function below (isFrozen & initialize) needed to bind to the Proxy. 21 | function isFrozen() external view virtual returns (bool) { 22 | return false; 23 | } 24 | 25 | /* 26 | The initialize() function serves as an alternative constructor for a proxied deployment. 27 | 28 | Flow and notes: 29 | 1. This function cannot be called directly on the deployed contract, but only via 30 | delegate call. 31 | 2. If an EIC is provided - init is passed onto EIC and the standard init flow is skipped. 32 | This true for both first intialization or a later one. 33 | 3. The data passed to this function is as follows: 34 | [sub_contracts addresses, eic address, initData]. 35 | 36 | When calling on an initialized contract (no EIC scenario), initData.length must be 0. 37 | */ 38 | function initialize(bytes calldata data) external notCalledDirectly { 39 | uint256 eicOffset = 32 * numOfSubContracts(); 40 | uint256 expectedBaseSize = eicOffset + 32; 41 | require(data.length >= expectedBaseSize, "INIT_DATA_TOO_SMALL"); 42 | address eicAddress = abi.decode(data[eicOffset:expectedBaseSize], (address)); 43 | 44 | bytes calldata subContractAddresses = data[:eicOffset]; 45 | 46 | processSubContractAddresses(subContractAddresses); 47 | 48 | bytes calldata initData = data[expectedBaseSize:]; 49 | 50 | // EIC Provided - Pass initData to EIC and the skip standard init flow. 51 | if (eicAddress != address(0x0)) { 52 | callExternalInitializer(eicAddress, initData); 53 | return; 54 | } 55 | 56 | if (isInitialized()) { 57 | require(initData.length == 0, "UNEXPECTED_INIT_DATA"); 58 | } else { 59 | // Contract was not initialized yet. 60 | validateInitData(initData); 61 | initializeContractState(initData); 62 | initGovernance(); 63 | } 64 | } 65 | 66 | function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData) 67 | private 68 | { 69 | require(externalInitializerAddr.isContract(), "EIC_NOT_A_CONTRACT"); 70 | 71 | // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. 72 | (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( 73 | abi.encodeWithSelector(this.initialize.selector, eicData) 74 | ); 75 | require(success, string(returndata)); 76 | require(returndata.length == 0, string(returndata)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/interfaces/SubContractor.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./Identity.sol"; 5 | 6 | interface SubContractor is Identity { 7 | function initialize(bytes calldata data) external; 8 | 9 | function initializerSize() external view returns (uint256); 10 | 11 | /* 12 | Returns an array with selectors for validation. 13 | These selectors are the critical ones for maintaining self custody and anti censorship. 14 | During the upgrade process, as part of the sub-contract validation, the MainDispatcher 15 | validates that the selectos are mapped to the correct sub-contract. 16 | */ 17 | function validatedSelectors() external pure returns (bytes4[] memory); 18 | } 19 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/libraries/Common.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Common Utility librarries. 6 | I. Addresses (extending address). 7 | */ 8 | library Addresses { 9 | function isContract(address account) internal view returns (bool) { 10 | uint256 size; 11 | assembly { 12 | size := extcodesize(account) 13 | } 14 | return size > 0; 15 | } 16 | 17 | function performEthTransfer(address recipient, uint256 amount) internal { 18 | (bool success, ) = recipient.call{value: amount}(""); // NOLINT: low-level-calls. 19 | require(success, "ETH_TRANSFER_FAILED"); 20 | } 21 | 22 | /* 23 | Safe wrapper around ERC20/ERC721 calls. 24 | This is required because many deployed ERC20 contracts don't return a value. 25 | See https://github.com/ethereum/solidity/issues/4116. 26 | */ 27 | function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { 28 | require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); 29 | // NOLINTNEXTLINE: low-level-calls. 30 | (bool success, bytes memory returndata) = tokenAddress.call(callData); 31 | require(success, string(returndata)); 32 | 33 | if (returndata.length > 0) { 34 | require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); 35 | } 36 | } 37 | 38 | /* 39 | Validates that the passed contract address is of a real contract, 40 | and that its id hash (as infered fromn identify()) matched the expected one. 41 | */ 42 | function validateContractId(address contractAddress, bytes32 expectedIdHash) internal { 43 | require(isContract(contractAddress), "ADDRESS_NOT_CONTRACT"); 44 | (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls. 45 | abi.encodeWithSignature("identify()") 46 | ); 47 | require(success, "FAILED_TO_IDENTIFY_CONTRACT"); 48 | string memory realContractId = abi.decode(returndata, (string)); 49 | require( 50 | keccak256(abi.encodePacked(realContractId)) == expectedIdHash, 51 | "UNEXPECTED_CONTRACT_IDENTIFIER" 52 | ); 53 | } 54 | } 55 | 56 | /* 57 | II. StarkExTypes - Common data types. 58 | */ 59 | library StarkExTypes { 60 | // Structure representing a list of verifiers (validity/availability). 61 | // A statement is valid only if all the verifiers in the list agree on it. 62 | // Adding a verifier to the list is immediate - this is used for fast resolution of 63 | // any soundness issues. 64 | // Removing from the list is time-locked, to ensure that any user of the system 65 | // not content with the announced removal has ample time to leave the system before it is 66 | // removed. 67 | struct ApprovalChainData { 68 | address[] list; 69 | // Represents the time after which the verifier with the given address can be removed. 70 | // Removal of the verifier with address A is allowed only in the case the value 71 | // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] < (current time). 72 | mapping(address => uint256) unlockedForRemovalTime; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/libraries/LibConstants.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | contract LibConstants { 5 | // Durations for time locked mechanisms (in seconds). 6 | // Note that it is known that miners can manipulate block timestamps 7 | // up to a deviation of a few seconds. 8 | // This mechanism should not be used for fine grained timing. 9 | 10 | // The time required to cancel a deposit, in the case the operator does not move the funds 11 | // to the off-chain storage. 12 | uint256 public constant DEPOSIT_CANCEL_DELAY = 2 days; 13 | 14 | // The time required to freeze the exchange, in the case the operator does not execute a 15 | // requested full withdrawal. 16 | uint256 public constant FREEZE_GRACE_PERIOD = 7 days; 17 | 18 | // The time after which the exchange may be unfrozen after it froze. This should be enough time 19 | // for users to perform escape hatches to get back their funds. 20 | uint256 public constant UNFREEZE_DELAY = 365 days; 21 | 22 | // Maximal number of verifiers which may co-exist. 23 | uint256 public constant MAX_VERIFIER_COUNT = uint256(64); 24 | 25 | // The time required to remove a verifier in case of a verifier upgrade. 26 | uint256 public constant VERIFIER_REMOVAL_DELAY = FREEZE_GRACE_PERIOD + (21 days); 27 | 28 | address constant ZERO_ADDRESS = address(0x0); 29 | 30 | uint256 constant K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; 31 | 32 | uint256 constant K_BETA = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89; 33 | 34 | uint256 internal constant MASK_250 = 35 | 0x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; 36 | uint256 internal constant MASK_240 = 37 | 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; 38 | 39 | uint256 public constant MAX_FORCED_ACTIONS_REQS_PER_BLOCK = 10; 40 | 41 | uint256 constant QUANTUM_UPPER_BOUND = 2**128; 42 | uint256 internal constant MINTABLE_ASSET_ID_FLAG = 1 << 250; 43 | 44 | // The 64th bit (indexed 63, counting from 0) is a flag indicating a rollup vault id. 45 | uint256 constant ROLLUP_VAULTS_BIT = 63; 46 | } 47 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/libraries/NamedStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Library to provide basic storage, in storage location out of the low linear address space. 6 | 7 | New types of storage variables should be added here upon need. 8 | */ 9 | library NamedStorage { 10 | function bytes32ToUint256Mapping(string memory tag_) 11 | internal 12 | pure 13 | returns (mapping(bytes32 => uint256) storage randomVariable) 14 | { 15 | bytes32 location = keccak256(abi.encodePacked(tag_)); 16 | assembly { 17 | randomVariable_slot := location 18 | } 19 | } 20 | 21 | function bytes32ToAddressMapping(string memory tag_) 22 | internal 23 | pure 24 | returns (mapping(bytes32 => address) storage randomVariable) 25 | { 26 | bytes32 location = keccak256(abi.encodePacked(tag_)); 27 | assembly { 28 | randomVariable_slot := location 29 | } 30 | } 31 | 32 | function uintToAddressMapping(string memory tag_) 33 | internal 34 | pure 35 | returns (mapping(uint256 => address) storage randomVariable) 36 | { 37 | bytes32 location = keccak256(abi.encodePacked(tag_)); 38 | assembly { 39 | randomVariable_slot := location 40 | } 41 | } 42 | 43 | function addressToBoolMapping(string memory tag_) 44 | internal 45 | pure 46 | returns (mapping(address => bool) storage randomVariable) 47 | { 48 | bytes32 location = keccak256(abi.encodePacked(tag_)); 49 | assembly { 50 | randomVariable_slot := location 51 | } 52 | } 53 | 54 | function getUintValue(string memory tag_) internal view returns (uint256 retVal) { 55 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 56 | assembly { 57 | retVal := sload(slot) 58 | } 59 | } 60 | 61 | function setUintValue(string memory tag_, uint256 value) internal { 62 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 63 | assembly { 64 | sstore(slot, value) 65 | } 66 | } 67 | 68 | function setUintValueOnce(string memory tag_, uint256 value) internal { 69 | require(getUintValue(tag_) == 0, "ALREADY_SET"); 70 | setUintValue(tag_, value); 71 | } 72 | 73 | function getAddressValue(string memory tag_) internal view returns (address retVal) { 74 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 75 | assembly { 76 | retVal := sload(slot) 77 | } 78 | } 79 | 80 | function setAddressValue(string memory tag_, address value) internal { 81 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 82 | assembly { 83 | sstore(slot, value) 84 | } 85 | } 86 | 87 | function setAddressValueOnce(string memory tag_, address value) internal { 88 | require(getAddressValue(tag_) == address(0x0), "ALREADY_SET"); 89 | setAddressValue(tag_, value); 90 | } 91 | 92 | function getBoolValue(string memory tag_) internal view returns (bool retVal) { 93 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 94 | assembly { 95 | retVal := sload(slot) 96 | } 97 | } 98 | 99 | function setBoolValue(string memory tag_, bool value) internal { 100 | bytes32 slot = keccak256(abi.encodePacked(tag_)); 101 | assembly { 102 | sstore(slot, value) 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/PerpetualConstants.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../libraries/LibConstants.sol"; 5 | 6 | contract PerpetualConstants is LibConstants { 7 | uint256 constant PERPETUAL_POSITION_ID_UPPER_BOUND = 2**64; 8 | uint256 constant PERPETUAL_AMOUNT_UPPER_BOUND = 2**64; 9 | uint256 constant PERPETUAL_TIMESTAMP_BITS = 32; 10 | uint256 constant PERPETUAL_ASSET_ID_UPPER_BOUND = 2**120; 11 | uint256 constant PERPETUAL_SYSTEM_TIME_LAG_BOUND = 7 days; 12 | uint256 constant PERPETUAL_SYSTEM_TIME_ADVANCE_BOUND = 4 hours; 13 | uint256 constant PERPETUAL_CONFIGURATION_DELAY = 0; 14 | } 15 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/ProgramOutputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | contract ProgramOutputOffsets { 5 | // The following constants are offsets of data expected in the program output. 6 | // The offsets here are of the fixed fields. 7 | uint256 internal constant PROG_OUT_GENERAL_CONFIG_HASH = 0; 8 | uint256 internal constant PROG_OUT_N_ASSET_CONFIGS = 1; 9 | uint256 internal constant PROG_OUT_ASSET_CONFIG_HASHES = 2; 10 | 11 | /* 12 | Additional mandatory fields of a single word: 13 | - Previous state size 2 14 | - New state size 3 15 | - Vault tree height 4 16 | - Order tree height 5 17 | - Expiration timestamp 6 18 | - No. of Modifications 7. 19 | */ 20 | uint256 internal constant PROG_OUT_N_WORDS_MIN_SIZE = 8; 21 | 22 | uint256 internal constant PROG_OUT_N_WORDS_PER_ASSET_CONFIG = 2; 23 | uint256 internal constant PROG_OUT_N_WORDS_PER_MODIFICATION = 3; 24 | 25 | uint256 internal constant ASSET_CONFIG_OFFSET_ASSET_ID = 0; 26 | uint256 internal constant ASSET_CONFIG_OFFSET_CONFIG_HASH = 1; 27 | 28 | uint256 internal constant MODIFICATIONS_OFFSET_STARKKEY = 0; 29 | uint256 internal constant MODIFICATIONS_OFFSET_POS_ID = 1; 30 | uint256 internal constant MODIFICATIONS_OFFSET_BIASED_DIFF = 2; 31 | 32 | uint256 internal constant STATE_OFFSET_VAULTS_ROOT = 0; 33 | uint256 internal constant STATE_OFFSET_VAULTS_HEIGHT = 1; 34 | uint256 internal constant STATE_OFFSET_ORDERS_ROOT = 2; 35 | uint256 internal constant STATE_OFFSET_ORDERS_HEIGHT = 3; 36 | uint256 internal constant STATE_OFFSET_N_FUNDING = 4; 37 | uint256 internal constant STATE_OFFSET_FUNDING = 5; 38 | 39 | // The following constants are offsets of data expected in the application data. 40 | uint256 internal constant APP_DATA_BATCH_ID_OFFSET = 0; 41 | uint256 internal constant APP_DATA_PREVIOUS_BATCH_ID_OFFSET = 1; 42 | uint256 internal constant APP_DATA_N_CONDITIONAL_TRANSFER = 2; 43 | uint256 internal constant APP_DATA_CONDITIONAL_TRANSFER_DATA_OFFSET = 3; 44 | uint256 internal constant APP_DATA_N_WORDS_PER_CONDITIONAL_TRANSFER = 2; 45 | } 46 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/StarkPerpetual.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MainDispatcher.sol"; 5 | import "./components/PerpetualStorage.sol"; 6 | 7 | contract StarkPerpetual is MainDispatcher, PerpetualStorage { 8 | string public constant VERSION = "3.0.0"; 9 | 10 | // Salt for a 8 bit unique spread of all relevant selectors. Pre-caclulated. 11 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 12 | uint256 constant MAGIC_SALT = 349548; 13 | uint256 constant IDX_MAP_0 = 0x2124100000000202022040002000000020022010011100002003000001000000; 14 | uint256 constant IDX_MAP_1 = 0x10003203010020002002200030330000100020300002001003030000100202; 15 | uint256 constant IDX_MAP_2 = 0x3000002000310000040022000010000000100013430002033100300200000302; 16 | uint256 constant IDX_MAP_3 = 0x1103103010020000102000000400320031030100023000004000300000000000; 17 | 18 | // ---------- End of auto-generated code. ---------- 19 | 20 | function getNumSubcontracts() internal pure override returns (uint256) { 21 | return 4; 22 | } 23 | 24 | function magicSalt() internal pure override returns (uint256) { 25 | return MAGIC_SALT; 26 | } 27 | 28 | function handlerMapSection(uint256 section) internal pure override returns (uint256) { 29 | if (section == 0) { 30 | return IDX_MAP_0; 31 | } else if (section == 1) { 32 | return IDX_MAP_1; 33 | } else if (section == 2) { 34 | return IDX_MAP_2; 35 | } else if (section == 3) { 36 | return IDX_MAP_3; 37 | } 38 | revert("BAD_IDX_MAP_SECTION"); 39 | } 40 | 41 | function expectedIdByIndex(uint256 index) internal pure override returns (string memory id) { 42 | if (index == 1) { 43 | id = "StarkWare_AllVerifiers_2022_2"; 44 | } else if (index == 2) { 45 | id = "StarkWare_PerpetualTokensAndRamping_2022_2"; 46 | } else if (index == 3) { 47 | id = "StarkWare_PerpetualState_2022_2"; 48 | } else if (index == 4) { 49 | id = "StarkWare_PerpetualForcedActions_2022_2"; 50 | } else { 51 | revert("UNEXPECTED_INDEX"); 52 | } 53 | } 54 | 55 | function initializationSentinel() internal view override { 56 | string memory REVERT_MSG = "INITIALIZATION_BLOCKED"; 57 | // This initializer sets state etc. It must not be applied twice. 58 | // I.e. it can run only when the state is still empty. 59 | require(int256(sharedStateHash) == 0, REVERT_MSG); 60 | require(int256(globalConfigurationHash) == 0, REVERT_MSG); 61 | require(systemAssetType == 0, REVERT_MSG); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/StarkPerpetualV2.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MainDispatcher.sol"; 5 | import "./components/PerpetualStorage.sol"; 6 | 7 | contract StarkPerpetualV2 is MainDispatcher, PerpetualStorage { 8 | string public constant VERSION = "2.0.0"; 9 | 10 | // Salt for a 8 bit unique spread of all relevant selectors. Pre-caclulated. 11 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 12 | uint256 constant MAGIC_SALT = 349548; 13 | uint256 constant IDX_MAP_0 = 0x2124100000000202022040002000000020022010011100002003000001000000; 14 | uint256 constant IDX_MAP_1 = 0x10003203010020002002200030330000100020300002001003030000100202; 15 | uint256 constant IDX_MAP_2 = 0x3200002000310000040022000010000000100013430202033100300200000302; 16 | uint256 constant IDX_MAP_3 = 0x1103103010220000102000000400320031030100023000004000302000000000; 17 | 18 | // ---------- End of auto-generated code. ---------- 19 | 20 | function getNumSubcontracts() internal pure override returns (uint256) { 21 | return 4; 22 | } 23 | 24 | function magicSalt() internal pure override returns (uint256) { 25 | return MAGIC_SALT; 26 | } 27 | 28 | function handlerMapSection(uint256 section) internal pure override returns (uint256) { 29 | if (section == 0) { 30 | return IDX_MAP_0; 31 | } else if (section == 1) { 32 | return IDX_MAP_1; 33 | } else if (section == 2) { 34 | return IDX_MAP_2; 35 | } else if (section == 3) { 36 | return IDX_MAP_3; 37 | } 38 | revert("BAD_IDX_MAP_SECTION"); 39 | } 40 | 41 | function expectedIdByIndex(uint256 index) internal pure override returns (string memory id) { 42 | if (index == 1) { 43 | id = "StarkWare_AllVerifiers_2022_2"; 44 | } else if (index == 2) { 45 | id = "StarkWare_PerpetualTokensAndRampingV2_2022_2"; 46 | } else if (index == 3) { 47 | id = "StarkWare_PerpetualState_2022_2"; 48 | } else if (index == 4) { 49 | id = "StarkWare_PerpetualForcedActions_2022_2"; 50 | } else { 51 | revert("UNEXPECTED_INDEX"); 52 | } 53 | } 54 | 55 | function initializationSentinel() internal view override { 56 | string memory REVERT_MSG = "INITIALIZATION_BLOCKED"; 57 | // This initializer sets state etc. It must not be applied twice. 58 | // I.e. it can run only when the state is still empty. 59 | require(int256(sharedStateHash) == 0, REVERT_MSG); 60 | require(int256(globalConfigurationHash) == 0, REVERT_MSG); 61 | require(systemAssetType == 0, REVERT_MSG); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/components/PerpetualEscapes.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../libraries/LibConstants.sol"; 5 | import "../../interfaces/MAcceptModifications.sol"; 6 | import "../../interfaces/MFreezable.sol"; 7 | import "../../interfaces/IFactRegistry.sol"; 8 | import "./PerpetualStorage.sol"; 9 | 10 | /** 11 | Escaping the exchange is the last resort for users that wish to withdraw their funds without 12 | relying on off-chain exchange services. The Escape functionality may only be invoked once the 13 | contract has become frozen. This will be as the result of an unserviced forcedAction request 14 | At that point, any escaper entity may perform an escape operation as follows: 15 | 16 | 1. Escapers call the :sol:mod:`PerpetualEscapeVerifier` contract with the Merkle proof for the vault to be evicted and the shared state. If the proof is valid, this results in the registration of said proof. 17 | 2. Escapers call :sol:func:`escape` function with the starkKey, vaultId and quantizedAmount matching the proof from step 1. 18 | 3. The owner of the vault may then withdraw this amount from the pending withdrawals account by calling the normal withdraw function (see :sol:mod:`Withdrawals`) to transfer the funds to the users ERC20 account. 19 | 20 | Note that while anyone can perform the initial steps of the escape operation (including the 21 | exchange operator, for example), only the owner of the vault may perform the final step of 22 | transferring the funds. 23 | */ 24 | abstract contract PerpetualEscapes is PerpetualStorage, MAcceptModifications, MFreezable { 25 | function initialize(address escapeVerifier) internal { 26 | escapeVerifierAddress = escapeVerifier; 27 | } 28 | 29 | /* 30 | Escape when the contract is frozen. 31 | */ 32 | function escape( 33 | uint256 starkKey, 34 | uint256 vaultId, 35 | uint256 quantizedAmount 36 | ) external onlyFrozen { 37 | require(!escapesUsed[vaultId], "ESCAPE_ALREADY_USED"); 38 | 39 | // Escape can be used only once. 40 | escapesUsed[vaultId] = true; 41 | escapesUsedCount += 1; 42 | 43 | bytes32 claimHash = keccak256( 44 | abi.encode(starkKey, quantizedAmount, sharedStateHash, vaultId) 45 | ); 46 | IFactRegistry escapeVerifier = IFactRegistry(escapeVerifierAddress); 47 | require(escapeVerifier.isValid(claimHash), "ESCAPE_LACKS_PROOF"); 48 | 49 | allowWithdrawal(starkKey, systemAssetType, quantizedAmount); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/components/PerpetualStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../components/MainStorage.sol"; 5 | 6 | /* 7 | Extends MainStorage, holds Perpetual App specific state (storage) variables. 8 | 9 | ALL State variables that are common to all applications, reside in MainStorage, 10 | whereas ALL the Perpetual app specific ones reside here. 11 | */ 12 | contract PerpetualStorage is MainStorage { 13 | uint256 systemAssetType; // NOLINT: constable-states uninitialized-state. 14 | 15 | bytes32 public globalConfigurationHash; // NOLINT: constable-states uninitialized-state. 16 | 17 | mapping(uint256 => bytes32) public configurationHash; // NOLINT: uninitialized-state. 18 | 19 | bytes32 sharedStateHash; // NOLINT: constable-states uninitialized-state. 20 | 21 | // Configuration apply time-lock. 22 | // The delay is held in storage (and not constant) 23 | // So that it can be modified during upgrade. 24 | uint256 public configurationDelay; // NOLINT: constable-states. 25 | 26 | // Reserved storage space for Extensibility. 27 | // Every added MUST be added above the end gap, and the __endGap size must be reduced 28 | // accordingly. 29 | // NOLINTNEXTLINE: naming-convention shadowing-abstract. 30 | uint256[LAYOUT_LENGTH - 5] private __endGap; // __endGap complements layout to LAYOUT_LENGTH. 31 | } 32 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/components/PerpetualTokenRegister.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../components/TokenRegister.sol"; 5 | import "./PerpetualStorage.sol"; 6 | 7 | /** 8 | Extension of the TokenRegister contract for StarkPerpetual. 9 | 10 | The change is that asset registration defines the system asset, 11 | and permitted only once. 12 | */ 13 | abstract contract PerpetualTokenRegister is PerpetualStorage, TokenRegister { 14 | event LogSystemAssetType(uint256 assetType); 15 | 16 | function registerToken( 17 | uint256, /* assetType */ 18 | bytes calldata /* assetInfo */ 19 | ) external override { 20 | revert("UNSUPPORTED_FUNCTION"); 21 | } 22 | 23 | function registerToken( 24 | uint256, /* assetType */ 25 | bytes memory, /* assetInfo */ 26 | uint256 /* quantum */ 27 | ) public override { 28 | revert("UNSUPPORTED_FUNCTION"); 29 | } 30 | 31 | // NOLINTNEXTLINE external-function. 32 | function getSystemAssetType() public view returns (uint256) { 33 | return systemAssetType; 34 | } 35 | 36 | function registerSystemAssetType(uint256 assetType, bytes calldata assetInfo) 37 | external 38 | onlyTokensAdmin 39 | { 40 | require(systemAssetType == uint256(0), "SYSTEM_ASSET_TYPE_ALREADY_SET"); 41 | systemAssetType = assetType; 42 | super.registerToken(assetType, assetInfo, 1); 43 | emit LogSystemAssetType(assetType); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/interactions/ForcedWithdrawalActionState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/PerpetualStorage.sol"; 5 | import "../interfaces/MForcedWithdrawalActionState.sol"; 6 | import "../../components/ActionHash.sol"; 7 | 8 | /* 9 | ForcedWithdrawal specific action hashses. 10 | */ 11 | contract ForcedWithdrawalActionState is PerpetualStorage, ActionHash, MForcedWithdrawalActionState { 12 | function forcedWithdrawActionHash( 13 | uint256 starkKey, 14 | uint256 vaultId, 15 | uint256 quantizedAmount 16 | ) internal pure override returns (bytes32) { 17 | return getActionHash("FORCED_WITHDRAWAL", abi.encode(starkKey, vaultId, quantizedAmount)); 18 | } 19 | 20 | function clearForcedWithdrawalRequest( 21 | uint256 starkKey, 22 | uint256 vaultId, 23 | uint256 quantizedAmount 24 | ) internal override { 25 | bytes32 actionHash = forcedWithdrawActionHash(starkKey, vaultId, quantizedAmount); 26 | require(forcedActionRequests[actionHash] != 0, "NON_EXISTING_ACTION"); 27 | delete forcedActionRequests[actionHash]; 28 | } 29 | 30 | function getForcedWithdrawalRequest( 31 | uint256 starkKey, 32 | uint256 vaultId, 33 | uint256 quantizedAmount 34 | ) public view override returns (uint256) { 35 | // Return request value. Expect zero if the request doesn't exist or has been serviced, and 36 | // a non-zero value otherwise. 37 | return forcedActionRequests[forcedWithdrawActionHash(starkKey, vaultId, quantizedAmount)]; 38 | } 39 | 40 | function setForcedWithdrawalRequest( 41 | uint256 starkKey, 42 | uint256 vaultId, 43 | uint256 quantizedAmount, 44 | bool premiumCost 45 | ) internal override { 46 | setActionHash(forcedWithdrawActionHash(starkKey, vaultId, quantizedAmount), premiumCost); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/interactions/ForcedWithdrawals.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MForcedWithdrawalActionState.sol"; 5 | import "../PerpetualConstants.sol"; 6 | import "../../interfaces/MFreezable.sol"; 7 | import "../../interfaces/MKeyGetters.sol"; 8 | 9 | abstract contract ForcedWithdrawals is 10 | PerpetualConstants, 11 | MForcedWithdrawalActionState, 12 | MFreezable, 13 | MKeyGetters 14 | { 15 | event LogForcedWithdrawalRequest(uint256 starkKey, uint256 vaultId, uint256 quantizedAmount); 16 | 17 | function forcedWithdrawalRequest( 18 | uint256 starkKey, 19 | uint256 vaultId, 20 | uint256 quantizedAmount, 21 | bool premiumCost 22 | ) external notFrozen onlyKeyOwner(starkKey) { 23 | // Verify vault ID in range. 24 | require(vaultId < PERPETUAL_POSITION_ID_UPPER_BOUND, "OUT_OF_RANGE_POSITION_ID"); 25 | require(quantizedAmount < PERPETUAL_AMOUNT_UPPER_BOUND, "ILLEGAL_AMOUNT"); 26 | 27 | // We cannot handle two identical forced withdraw request at the same time. 28 | // User can either wait for pending one to be cleared, or issue one with different amount. 29 | require( 30 | getForcedWithdrawalRequest(starkKey, vaultId, quantizedAmount) == 0, 31 | "REQUEST_ALREADY_PENDING" 32 | ); 33 | 34 | // Start timer on escape request. 35 | setForcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost); 36 | 37 | // Log request. 38 | emit LogForcedWithdrawalRequest(starkKey, vaultId, quantizedAmount); 39 | } 40 | 41 | function freezeRequest( 42 | uint256 starkKey, 43 | uint256 vaultId, 44 | uint256 quantizedAmount 45 | ) external notFrozen { 46 | // Verify vaultId in range. 47 | require(vaultId < PERPETUAL_POSITION_ID_UPPER_BOUND, "OUT_OF_RANGE_POSITION_ID"); 48 | 49 | // Load request time. 50 | uint256 requestTime = getForcedWithdrawalRequest(starkKey, vaultId, quantizedAmount); 51 | 52 | validateFreezeRequest(requestTime); 53 | freeze(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/interfaces/MForcedTradeActionState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MForcedTradeActionState { 5 | function forcedTradeActionHash( 6 | uint256 starkKeyA, 7 | uint256 starkKeyB, 8 | uint256 vaultIdA, 9 | uint256 vaultIdB, 10 | uint256 collateralAssetId, 11 | uint256 syntheticAssetId, 12 | uint256 amountCollateral, 13 | uint256 amountSynthetic, 14 | bool aIsBuyingSynthetic, 15 | uint256 nonce 16 | ) internal pure virtual returns (bytes32); 17 | 18 | function clearForcedTradeRequest( 19 | uint256 starkKeyA, 20 | uint256 starkKeyB, 21 | uint256 vaultIdA, 22 | uint256 vaultIdB, 23 | uint256 collateralAssetId, 24 | uint256 syntheticAssetId, 25 | uint256 amountCollateral, 26 | uint256 amountSynthetic, 27 | bool aIsBuyingSynthetic, 28 | uint256 nonce 29 | ) internal virtual; 30 | 31 | // NOLINTNEXTLINE: external-function. 32 | function getForcedTradeRequest( 33 | uint256 starkKeyA, 34 | uint256 starkKeyB, 35 | uint256 vaultIdA, 36 | uint256 vaultIdB, 37 | uint256 collateralAssetId, 38 | uint256 syntheticAssetId, 39 | uint256 amountCollateral, 40 | uint256 amountSynthetic, 41 | bool aIsBuyingSynthetic, 42 | uint256 nonce 43 | ) public view virtual returns (uint256 res); 44 | 45 | function setForcedTradeRequest( 46 | uint256 starkKeyA, 47 | uint256 starkKeyB, 48 | uint256 vaultIdA, 49 | uint256 vaultIdB, 50 | uint256 collateralAssetId, 51 | uint256 syntheticAssetId, 52 | uint256 amountCollateral, 53 | uint256 amountSynthetic, 54 | bool aIsBuyingSynthetic, 55 | uint256 nonce, 56 | bool premiumCost 57 | ) internal virtual; 58 | } 59 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/interfaces/MForcedWithdrawalActionState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MForcedWithdrawalActionState { 5 | function forcedWithdrawActionHash( 6 | uint256 starkKey, 7 | uint256 vaultId, 8 | uint256 quantizedAmount 9 | ) internal pure virtual returns (bytes32); 10 | 11 | function clearForcedWithdrawalRequest( 12 | uint256 starkKey, 13 | uint256 vaultId, 14 | uint256 quantizedAmount 15 | ) internal virtual; 16 | 17 | // NOLINTNEXTLINE: external-function. 18 | function getForcedWithdrawalRequest( 19 | uint256 starkKey, 20 | uint256 vaultId, 21 | uint256 quantizedAmount 22 | ) public view virtual returns (uint256 res); 23 | 24 | function setForcedWithdrawalRequest( 25 | uint256 starkKey, 26 | uint256 vaultId, 27 | uint256 quantizedAmount, 28 | bool premiumCost 29 | ) internal virtual; 30 | } 31 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/toplevel_subcontracts/PerpetualForcedActions.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interactions/ForcedTrades.sol"; 5 | import "../interactions/ForcedTradeActionState.sol"; 6 | import "../interactions/ForcedWithdrawals.sol"; 7 | import "../interactions/ForcedWithdrawalActionState.sol"; 8 | import "../../components/Freezable.sol"; 9 | import "../../components/KeyGetters.sol"; 10 | import "../../components/MainGovernance.sol"; 11 | import "../../components/Users.sol"; 12 | import "../../interfaces/SubContractor.sol"; 13 | 14 | contract PerpetualForcedActions is 15 | SubContractor, 16 | MainGovernance, 17 | Freezable, 18 | KeyGetters, 19 | Users, 20 | ForcedTrades, 21 | ForcedTradeActionState, 22 | ForcedWithdrawals, 23 | ForcedWithdrawalActionState 24 | { 25 | function initialize( 26 | bytes calldata /* data */ 27 | ) external override { 28 | revert("NOT_IMPLEMENTED"); 29 | } 30 | 31 | function initializerSize() external view override returns (uint256) { 32 | return 0; 33 | } 34 | 35 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 36 | uint256 len_ = 5; 37 | uint256 index_ = 0; 38 | 39 | selectors = new bytes4[](len_); 40 | selectors[index_++] = ForcedTrades.forcedTradeRequest.selector; 41 | selectors[index_++] = ForcedTrades.freezeRequest.selector; 42 | selectors[index_++] = ForcedWithdrawals.forcedWithdrawalRequest.selector; 43 | selectors[index_++] = ForcedWithdrawals.freezeRequest.selector; 44 | selectors[index_++] = Users.registerEthAddress.selector; 45 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 46 | } 47 | 48 | function identify() external pure override returns (string memory) { 49 | return "StarkWare_PerpetualForcedActions_2022_2"; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/toplevel_subcontracts/PerpetualState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/PerpetualEscapes.sol"; 5 | import "../components/UpdatePerpetualState.sol"; 6 | import "../components/Configuration.sol"; 7 | import "../interactions/ForcedTradeActionState.sol"; 8 | import "../interactions/ForcedWithdrawalActionState.sol"; 9 | import "../../components/Freezable.sol"; 10 | import "../../components/MainGovernance.sol"; 11 | import "../../components/StarkExOperator.sol"; 12 | import "../../interactions/AcceptModifications.sol"; 13 | import "../../interactions/StateRoot.sol"; 14 | import "../../interactions/TokenQuantization.sol"; 15 | import "../../interfaces/SubContractor.sol"; 16 | 17 | contract PerpetualState is 18 | MainGovernance, 19 | SubContractor, 20 | Configuration, 21 | StarkExOperator, 22 | Freezable, 23 | AcceptModifications, 24 | TokenQuantization, 25 | ForcedTradeActionState, 26 | ForcedWithdrawalActionState, 27 | StateRoot, 28 | PerpetualEscapes, 29 | UpdatePerpetualState 30 | { 31 | // Empty state is 8 words (256 bytes) To pass as uint[] we need also head & len fields (64). 32 | uint256 constant INITIALIZER_SIZE = 384; // Padded address(32), uint(32), Empty state(256+64). 33 | 34 | /* 35 | Initialization flow: 36 | 1. Extract initialization parameters from data. 37 | 2. Call internalInitializer with those parameters. 38 | */ 39 | function initialize(bytes calldata data) external override { 40 | // This initializer sets roots etc. It must not be applied twice. 41 | // I.e. it can run only when the state is still empty. 42 | require(sharedStateHash == bytes32(0x0), "STATE_ALREADY_INITIALIZED"); 43 | require(configurationHash[GLOBAL_CONFIG_KEY] == bytes32(0x0), "STATE_ALREADY_INITIALIZED"); 44 | 45 | require(data.length == INITIALIZER_SIZE, "INCORRECT_INIT_DATA_SIZE_384"); 46 | 47 | ( 48 | address escapeVerifierAddress_, 49 | uint256 initialSequenceNumber, 50 | uint256[] memory initialState 51 | ) = abi.decode(data, (address, uint256, uint256[])); 52 | 53 | initGovernance(); 54 | Configuration.initialize(PERPETUAL_CONFIGURATION_DELAY); 55 | StarkExOperator.initialize(); 56 | // Validium tree is not utilized in Perpetual. Initializing its root and height to -1. 57 | StateRoot.initialize( 58 | initialSequenceNumber, 59 | uint256(-1), // validiumVaultRoot. 60 | initialState[0], // rollupVaultRoot. 61 | initialState[2], // orderRoot. 62 | uint256(-1), // validiumTreeHeight. 63 | initialState[1], // rollupTreeHeight. 64 | initialState[3] // orderTreeHeight. 65 | ); 66 | sharedStateHash = keccak256(abi.encodePacked(initialState)); 67 | PerpetualEscapes.initialize(escapeVerifierAddress_); 68 | } 69 | 70 | /* 71 | The call to initializerSize is done from MainDispatcherBase using delegatecall, 72 | thus the existing state is already accessible. 73 | */ 74 | function initializerSize() external view override returns (uint256) { 75 | return INITIALIZER_SIZE; 76 | } 77 | 78 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 79 | uint256 len_ = 1; 80 | uint256 index_ = 0; 81 | 82 | selectors = new bytes4[](len_); 83 | selectors[index_++] = PerpetualEscapes.escape.selector; 84 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 85 | } 86 | 87 | function identify() external pure override returns (string memory) { 88 | return "StarkWare_PerpetualState_2022_2"; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/toplevel_subcontracts/PerpetualTokensAndRamping.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/PerpetualTokenRegister.sol"; 5 | import "../../components/TokenTransfers.sol"; 6 | import "../../components/ERC721Receiver.sol"; 7 | import "../../components/Freezable.sol"; 8 | import "../../components/KeyGetters.sol"; 9 | import "../../components/MainGovernance.sol"; 10 | import "../../interactions/AcceptModifications.sol"; 11 | import "../../interactions/Deposits.sol"; 12 | import "../../interactions/TokenAssetData.sol"; 13 | import "../../interactions/TokenQuantization.sol"; 14 | import "../../interactions/Withdrawals.sol"; 15 | import "../../interfaces/SubContractor.sol"; 16 | 17 | contract PerpetualTokensAndRamping is 18 | ERC721Receiver, 19 | SubContractor, 20 | Freezable, 21 | MainGovernance, 22 | AcceptModifications, 23 | TokenAssetData, 24 | TokenQuantization, 25 | TokenTransfers, 26 | PerpetualTokenRegister, 27 | KeyGetters, 28 | Deposits, 29 | Withdrawals 30 | { 31 | function initialize( 32 | bytes calldata /* data */ 33 | ) external override { 34 | revert("NOT_IMPLEMENTED"); 35 | } 36 | 37 | function initializerSize() external view override returns (uint256) { 38 | return 0; 39 | } 40 | 41 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 42 | uint256 len_ = 3; 43 | uint256 index_ = 0; 44 | 45 | selectors = new bytes4[](len_); 46 | selectors[index_++] = Deposits.depositCancel.selector; 47 | selectors[index_++] = Deposits.depositReclaim.selector; 48 | selectors[index_++] = Withdrawals.withdraw.selector; 49 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 50 | } 51 | 52 | function identify() external pure override returns (string memory) { 53 | return "StarkWare_PerpetualTokensAndRamping_2022_2"; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/perpetual/toplevel_subcontracts/PerpetualTokensAndRampingV2.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/PerpetualTokenRegister.sol"; 5 | import "../../components/TokenTransfers.sol"; 6 | import "../../components/ERC721Receiver.sol"; 7 | import "../../components/Freezable.sol"; 8 | import "../../components/KeyGetters.sol"; 9 | import "../../components/UsersV2.sol"; 10 | import "../../components/MainGovernance.sol"; 11 | import "../../interactions/AcceptModifications.sol"; 12 | import "../../interactions/CompositeActionsV2.sol"; 13 | import "../../interactions/Deposits.sol"; 14 | import "../../interactions/TokenAssetData.sol"; 15 | import "../../interactions/TokenQuantization.sol"; 16 | import "../../interactions/Withdrawals.sol"; 17 | import "../../interfaces/SubContractor.sol"; 18 | 19 | contract PerpetualTokensAndRampingV2 is 20 | ERC721Receiver, 21 | SubContractor, 22 | Freezable, 23 | MainGovernance, 24 | AcceptModifications, 25 | TokenAssetData, 26 | TokenQuantization, 27 | TokenTransfers, 28 | PerpetualTokenRegister, 29 | KeyGetters, 30 | UsersV2, 31 | Deposits, 32 | CompositeActionsV2, 33 | Withdrawals 34 | { 35 | function initialize( 36 | bytes calldata /* data */ 37 | ) external override { 38 | revert("NOT_IMPLEMENTED"); 39 | } 40 | 41 | function initializerSize() external view override returns (uint256) { 42 | return 0; 43 | } 44 | 45 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 46 | uint256 len_ = 3; 47 | uint256 index_ = 0; 48 | 49 | selectors = new bytes4[](len_); 50 | selectors[index_++] = Deposits.depositCancel.selector; 51 | selectors[index_++] = Deposits.depositReclaim.selector; 52 | selectors[index_++] = Withdrawals.withdraw.selector; 53 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 54 | } 55 | 56 | function identify() external pure override returns (string memory) { 57 | return "StarkWare_PerpetualTokensAndRampingV2_2022_2"; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/PublicInputOffsets.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | contract PublicInputOffsets { 5 | // The following constants are offsets of data expected in the public input. 6 | uint256 internal constant PUB_IN_GLOBAL_CONFIG_CODE_OFFSET = 0; 7 | uint256 internal constant PUB_IN_INITIAL_VALIDIUM_VAULT_ROOT_OFFSET = 1; 8 | uint256 internal constant PUB_IN_FINAL_VALIDIUM_VAULT_ROOT_OFFSET = 2; 9 | uint256 internal constant PUB_IN_INITIAL_ROLLUP_VAULT_ROOT_OFFSET = 3; 10 | uint256 internal constant PUB_IN_FINAL_ROLLUP_VAULT_ROOT_OFFSET = 4; 11 | uint256 internal constant PUB_IN_INITIAL_ORDER_ROOT_OFFSET = 5; 12 | uint256 internal constant PUB_IN_FINAL_ORDER_ROOT_OFFSET = 6; 13 | uint256 internal constant PUB_IN_GLOBAL_EXPIRATION_TIMESTAMP_OFFSET = 7; 14 | uint256 internal constant PUB_IN_VALIDIUM_VAULT_TREE_HEIGHT_OFFSET = 8; 15 | uint256 internal constant PUB_IN_ROLLUP_VAULT_TREE_HEIGHT_OFFSET = 9; 16 | uint256 internal constant PUB_IN_ORDER_TREE_HEIGHT_OFFSET = 10; 17 | uint256 internal constant PUB_IN_N_MODIFICATIONS_OFFSET = 11; 18 | uint256 internal constant PUB_IN_N_CONDITIONAL_TRANSFERS_OFFSET = 12; 19 | uint256 internal constant PUB_IN_N_ONCHAIN_VAULT_UPDATES_OFFSET = 13; 20 | uint256 internal constant PUB_IN_N_ONCHAIN_ORDERS_OFFSET = 14; 21 | uint256 internal constant PUB_IN_TRANSACTIONS_DATA_OFFSET = 15; 22 | 23 | uint256 internal constant PUB_IN_N_WORDS_PER_MODIFICATION = 3; 24 | uint256 internal constant PUB_IN_N_WORDS_PER_CONDITIONAL_TRANSFER = 1; 25 | uint256 internal constant PUB_IN_N_WORDS_PER_ONCHAIN_VAULT_UPDATE = 3; 26 | uint256 internal constant PUB_IN_N_MIN_WORDS_PER_ONCHAIN_ORDER = 3; 27 | 28 | // The following constants are offsets of data expected in the application data. 29 | uint256 internal constant APP_DATA_BATCH_ID_OFFSET = 0; 30 | uint256 internal constant APP_DATA_PREVIOUS_BATCH_ID_OFFSET = 1; 31 | uint256 internal constant APP_DATA_TRANSACTIONS_DATA_OFFSET = 2; 32 | 33 | uint256 internal constant APP_DATA_N_WORDS_PER_CONDITIONAL_TRANSFER = 2; 34 | } 35 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/StarkExConstants.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../libraries/LibConstants.sol"; 5 | 6 | contract StarkExConstants is LibConstants { 7 | uint256 constant STARKEX_EXPIRATION_TIMESTAMP_BITS = 22; 8 | uint256 public constant STARKEX_MAX_DEFAULT_VAULT_LOCK = 7 days; 9 | } 10 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/StarkExchange.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interfaces/MainDispatcher.sol"; 5 | 6 | contract StarkExchange is MainDispatcher { 7 | string public constant VERSION = "4.5.1"; 8 | 9 | // Salt for a 8 bit unique spread of all relevant selectors. Pre-caclulated. 10 | // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- 11 | uint256 constant MAGIC_SALT = 1527414; 12 | uint256 constant IDX_MAP_0 = 0x2010501100000010050000002511000000220005410030200200200000552010; 13 | uint256 constant IDX_MAP_1 = 0x3000030005000050020012003000010604300000002420501003000010000300; 14 | uint256 constant IDX_MAP_2 = 0x1003112030002130000200100020000320202001020001001000040200200020; 15 | uint256 constant IDX_MAP_3 = 0x2000000050000012000013100002002002032050020002020002050000201003; 16 | 17 | // ---------- End of auto-generated code. ---------- 18 | 19 | function getNumSubcontracts() internal pure override returns (uint256) { 20 | return 6; 21 | } 22 | 23 | function magicSalt() internal pure override returns (uint256) { 24 | return MAGIC_SALT; 25 | } 26 | 27 | function handlerMapSection(uint256 section) internal pure override returns (uint256) { 28 | if (section == 0) { 29 | return IDX_MAP_0; 30 | } else if (section == 1) { 31 | return IDX_MAP_1; 32 | } else if (section == 2) { 33 | return IDX_MAP_2; 34 | } else if (section == 3) { 35 | return IDX_MAP_3; 36 | } 37 | revert("BAD_IDX_MAP_SECTION"); 38 | } 39 | 40 | function expectedIdByIndex(uint256 index) internal pure override returns (string memory id) { 41 | if (index == 1) { 42 | id = "StarkWare_AllVerifiers_2022_2"; 43 | } else if (index == 2) { 44 | id = "StarkWare_TokensAndRamping_2022_2"; 45 | } else if (index == 3) { 46 | id = "StarkWare_StarkExState_2022_5"; 47 | } else if (index == 4) { 48 | id = "StarkWare_ForcedActions_2022_3"; 49 | } else if (index == 5) { 50 | id = "StarkWare_OnchainVaults_2022_2"; 51 | } else if (index == 6) { 52 | id = "StarkWare_ProxyUtils_2022_2"; 53 | } else { 54 | revert("UNEXPECTED_INDEX"); 55 | } 56 | } 57 | 58 | function initializationSentinel() internal view override { 59 | string memory REVERT_MSG = "INITIALIZATION_BLOCKED"; 60 | // This initializer sets roots etc. It must not be applied twice. 61 | // I.e. it can run only when the state is still empty. 62 | require(validiumVaultRoot == 0, REVERT_MSG); 63 | require(validiumTreeHeight == 0, REVERT_MSG); 64 | require(rollupVaultRoot == 0, REVERT_MSG); 65 | require(rollupTreeHeight == 0, REVERT_MSG); 66 | require(orderRoot == 0, REVERT_MSG); 67 | require(orderTreeHeight == 0, REVERT_MSG); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/components/StarkExStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../components/MainStorage.sol"; 5 | 6 | /* 7 | Extends MainStorage, holds StarkEx App specific state (storage) variables. 8 | 9 | ALL State variables that are common to all applications, reside in MainStorage, 10 | whereas ALL the StarkEx app specific ones reside here. 11 | */ 12 | contract StarkExStorage is MainStorage { 13 | // Onchain vaults balances. 14 | // A map eth_address => asset_id => vault_id => quantized amount. 15 | mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsBalances; 16 | 17 | // Onchain vaults withdrawal lock time. 18 | // A map eth_address => asset_id => vault_id => lock expiration timestamp. 19 | mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsWithdrawalLocks; 20 | 21 | // Enforces the minimal balance requirement (as output by Cairo) on onchain vault updates. 22 | // When disabled, flash loans are enabled. 23 | bool strictVaultBalancePolicy; // NOLINT: constable-states, uninitialized-state. 24 | 25 | // The default time, in seconds, that an onchain vault is locked for withdrawal after a deposit. 26 | uint256 public defaultVaultWithdrawalLock; // NOLINT: constable-states. 27 | 28 | // Address of the message registry contract that is used to sign and verify L1 orders. 29 | address public orderRegistryAddress; // NOLINT: constable-states. 30 | 31 | // Reserved storage space for Extensibility. 32 | // Every added MUST be added above the end gap, and the __endGap size must be reduced 33 | // accordingly. 34 | // NOLINTNEXTLINE: naming-convention shadowing-abstract. 35 | uint256[LAYOUT_LENGTH - 5] private __endGap; // __endGap complements layout to LAYOUT_LENGTH. 36 | } 37 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/components/VaultLocks.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./StarkExStorage.sol"; 5 | import "../StarkExConstants.sol"; 6 | import "../interfaces/MVaultLocks.sol"; 7 | import "../../interfaces/MGovernance.sol"; 8 | 9 | /* 10 | Onchain vaults' lock functionality. 11 | */ 12 | abstract contract VaultLocks is StarkExStorage, StarkExConstants, MGovernance, MVaultLocks { 13 | event LogDefaultVaultWithdrawalLockSet(uint256 newDefaultLockTime); 14 | event LogVaultWithdrawalLockSet( 15 | address ethKey, 16 | uint256 assetId, 17 | uint256 vaultId, 18 | uint256 timeRelease 19 | ); 20 | 21 | function initialize(uint256 defaultLockTime) internal { 22 | setDefaultVaultWithdrawalLock(defaultLockTime); 23 | } 24 | 25 | function setDefaultVaultWithdrawalLock(uint256 newDefaultTime) public onlyGovernance { 26 | require(newDefaultTime <= STARKEX_MAX_DEFAULT_VAULT_LOCK, "DEFAULT_LOCK_TIME_TOO_LONG"); 27 | defaultVaultWithdrawalLock = newDefaultTime; 28 | emit LogDefaultVaultWithdrawalLockSet(newDefaultTime); 29 | } 30 | 31 | function getVaultWithdrawalLock( 32 | address ethKey, 33 | uint256 assetId, 34 | uint256 vaultId 35 | ) public view returns (uint256) { 36 | return vaultsWithdrawalLocks[ethKey][assetId][vaultId]; 37 | } 38 | 39 | function lockVault( 40 | uint256 assetId, 41 | uint256 vaultId, 42 | uint256 lockTime 43 | ) public { 44 | uint256 currentLockRelease = getVaultWithdrawalLock(msg.sender, assetId, vaultId); 45 | uint256 timeRelease = block.timestamp + lockTime; 46 | require(timeRelease >= currentLockRelease, "INVALID_LOCK_TIME"); 47 | 48 | vaultsWithdrawalLocks[msg.sender][assetId][vaultId] = timeRelease; 49 | emit LogVaultWithdrawalLockSet(msg.sender, assetId, vaultId, timeRelease); 50 | } 51 | 52 | function applyDefaultLock(uint256 assetId, uint256 vaultId) internal override { 53 | uint256 currentLockRelease = getVaultWithdrawalLock(msg.sender, assetId, vaultId); 54 | if (currentLockRelease < block.timestamp + defaultVaultWithdrawalLock) { 55 | lockVault(assetId, vaultId, defaultVaultWithdrawalLock); 56 | } 57 | } 58 | 59 | function isVaultLocked( 60 | address ethKey, 61 | uint256 assetId, 62 | uint256 vaultId 63 | ) public view override returns (bool) { 64 | uint256 timeRelease = getVaultWithdrawalLock(ethKey, assetId, vaultId); 65 | return (block.timestamp < timeRelease); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/interactions/StarkExForcedActionState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/StarkExStorage.sol"; 5 | import "../interfaces/MStarkExForcedActionState.sol"; 6 | import "../../components/ActionHash.sol"; 7 | 8 | /* 9 | StarkExchange specific action hashses. 10 | */ 11 | contract StarkExForcedActionState is StarkExStorage, ActionHash, MStarkExForcedActionState { 12 | function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId) 13 | internal 14 | pure 15 | override 16 | returns (bytes32) 17 | { 18 | return getActionHash("FULL_WITHDRAWAL", abi.encode(ownerKey, vaultId)); 19 | } 20 | 21 | /* 22 | Implemented in the FullWithdrawal contracts. 23 | */ 24 | function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) 25 | internal 26 | virtual 27 | override 28 | { 29 | // Reset escape request. 30 | delete forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)]; 31 | } 32 | 33 | function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) 34 | public 35 | view 36 | override 37 | returns (uint256) 38 | { 39 | // Return request value. Expect zero if the request doesn't exist or has been serviced, and 40 | // a non-zero value otherwise. 41 | return forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)]; 42 | } 43 | 44 | function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal override { 45 | // FullWithdrawal is always at premium cost, hence the `true`. 46 | setActionHash(fullWithdrawActionHash(ownerKey, vaultId), true); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/interfaces/MStarkExForcedActionState.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | abstract contract MStarkExForcedActionState { 5 | function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId) 6 | internal 7 | pure 8 | virtual 9 | returns (bytes32); 10 | 11 | function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual; 12 | 13 | // NOLINTNEXTLINE: external-function. 14 | function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) 15 | public 16 | view 17 | virtual 18 | returns (uint256); 19 | 20 | function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual; 21 | } 22 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/interfaces/MVaultLocks.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Onchain vaults' lock functionality. 6 | */ 7 | abstract contract MVaultLocks { 8 | function applyDefaultLock(uint256 assetId, uint256 vaultId) internal virtual; 9 | 10 | function isVaultLocked( 11 | address ethKey, 12 | uint256 assetId, 13 | uint256 vaultId 14 | ) public view virtual returns (bool); 15 | } 16 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/toplevel_subcontracts/ForcedActions.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interactions/FullWithdrawals.sol"; 5 | import "../interactions/StarkExForcedActionState.sol"; 6 | import "../../components/Freezable.sol"; 7 | import "../../components/KeyGetters.sol"; 8 | import "../../components/MainGovernance.sol"; 9 | import "../../components/Users.sol"; 10 | import "../../interfaces/SubContractor.sol"; 11 | 12 | contract ForcedActions is 13 | SubContractor, 14 | MainGovernance, 15 | Freezable, 16 | KeyGetters, 17 | Users, 18 | FullWithdrawals, 19 | StarkExForcedActionState 20 | { 21 | function initialize( 22 | bytes calldata /* data */ 23 | ) external override { 24 | revert("NOT_IMPLEMENTED"); 25 | } 26 | 27 | function initializerSize() external view override returns (uint256) { 28 | return 0; 29 | } 30 | 31 | function validatedSelectors() 32 | external 33 | pure 34 | virtual 35 | override 36 | returns (bytes4[] memory selectors) 37 | { 38 | uint256 len_ = 3; 39 | uint256 index_ = 0; 40 | 41 | selectors = new bytes4[](len_); 42 | selectors[index_++] = FullWithdrawals.freezeRequest.selector; 43 | selectors[index_++] = FullWithdrawals.fullWithdrawalRequest.selector; 44 | selectors[index_++] = Users.registerEthAddress.selector; 45 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 46 | } 47 | 48 | function identify() external pure override returns (string memory) { 49 | return "StarkWare_ForcedActions_2022_3"; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/toplevel_subcontracts/OnchainVaults.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/VaultDepositWithdrawal.sol"; 5 | import "../components/VaultLocks.sol"; 6 | import "../../components/MainGovernance.sol"; 7 | import "../../components/TokenTransfers.sol"; 8 | import "../../interactions/TokenAssetData.sol"; 9 | import "../../interactions/TokenQuantization.sol"; 10 | import "../../interfaces/SubContractor.sol"; 11 | 12 | contract OnchainVaults is 13 | SubContractor, 14 | MainGovernance, 15 | VaultLocks, 16 | TokenAssetData, 17 | TokenTransfers, 18 | TokenQuantization, 19 | VaultDepositWithdrawal 20 | { 21 | function initialize(bytes calldata) external override { 22 | revert("NOT_IMPLEMENTED"); 23 | } 24 | 25 | function initializerSize() external view override returns (uint256) { 26 | return 0; 27 | } 28 | 29 | function isStrictVaultBalancePolicy() external view returns (bool) { 30 | return strictVaultBalancePolicy; 31 | } 32 | 33 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 34 | uint256 len_ = 2; 35 | uint256 index_ = 0; 36 | 37 | selectors = new bytes4[](len_); 38 | selectors[index_++] = VaultDepositWithdrawal.withdrawErc1155FromVault.selector; 39 | selectors[index_++] = VaultDepositWithdrawal.withdrawFromVault.selector; 40 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 41 | } 42 | 43 | function identify() external pure override returns (string memory) { 44 | return "StarkWare_OnchainVaults_2022_2"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/toplevel_subcontracts/ProxyUtils.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/SubContractor.sol"; 5 | import "../../upgrade/ProxyGovernance.sol"; 6 | import "../../upgrade/ProxyStorage.sol"; 7 | import "../../upgrade/StorageSlots.sol"; 8 | 9 | contract ProxyUtils is SubContractor, StorageSlots, ProxyGovernance, ProxyStorage { 10 | event ImplementationActivationRescheduled( 11 | address indexed implementation, 12 | uint256 updatedActivationTime 13 | ); 14 | 15 | function initialize( 16 | bytes calldata /* data */ 17 | ) external override { 18 | revert("NOT_IMPLEMENTED"); 19 | } 20 | 21 | function initializerSize() external view override returns (uint256) { 22 | return 0; 23 | } 24 | 25 | function storedActivationDelay() internal view returns (uint256 delay) { 26 | bytes32 slot = UPGRADE_DELAY_SLOT; 27 | assembly { 28 | delay := sload(slot) 29 | } 30 | return delay; 31 | } 32 | 33 | function updateImplementationActivationTime( 34 | address implementation, 35 | bytes calldata data, 36 | bool finalize 37 | ) external onlyGovernance { 38 | uint256 updatedActivationTime = block.timestamp + storedActivationDelay(); 39 | 40 | // We assume the Proxy is of the old format. 41 | bytes32 oldFormatInitHash = keccak256(abi.encode(data, finalize)); 42 | require( 43 | initializationHash_DEPRECATED[implementation] == oldFormatInitHash, 44 | "IMPLEMENTATION_NOT_PENDING" 45 | ); 46 | 47 | // Converting address to bytes32 to match the mapping key type. 48 | bytes32 implementationKey; 49 | assembly { 50 | implementationKey := implementation 51 | } 52 | uint256 pendingActivationTime = enabledTime[implementationKey]; 53 | 54 | require(pendingActivationTime > 0, "IMPLEMENTATION_NOT_PENDING"); 55 | 56 | // Current value is checked to be within a reasonable delay. If it's over 6 months from now, 57 | // it's assumed that the activation time is configured under a different set of rules. 58 | require( 59 | pendingActivationTime < block.timestamp + 180 days, 60 | "INVALID_PENDING_ACTIVATION_TIME" 61 | ); 62 | 63 | if (updatedActivationTime < pendingActivationTime) { 64 | enabledTime[implementationKey] = updatedActivationTime; 65 | emit ImplementationActivationRescheduled(implementation, updatedActivationTime); 66 | } 67 | } 68 | 69 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 70 | // This sub-contract has no selectors to validate. 71 | selectors = new bytes4[](0); 72 | } 73 | 74 | function identify() external pure override returns (string memory) { 75 | return "StarkWare_ProxyUtils_2022_2"; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/starkex/toplevel_subcontracts/TokensAndRamping.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../interactions/StarkExForcedActionState.sol"; 5 | import "../../components/ERC721Receiver.sol"; 6 | import "../../components/ERC1155Receiver.sol"; 7 | import "../../components/Freezable.sol"; 8 | import "../../components/KeyGetters.sol"; 9 | import "../../components/TokenRegister.sol"; 10 | import "../../components/TokenTransfers.sol"; 11 | import "../../components/MainGovernance.sol"; 12 | import "../../interactions/AcceptModifications.sol"; 13 | import "../../interactions/Deposits.sol"; 14 | import "../../interactions/TokenAssetData.sol"; 15 | import "../../interactions/TokenQuantization.sol"; 16 | import "../../interactions/Withdrawals.sol"; 17 | import "../../interfaces/SubContractor.sol"; 18 | 19 | contract TokensAndRamping is 20 | ERC1155Receiver, 21 | ERC721Receiver, 22 | SubContractor, 23 | Freezable, 24 | MainGovernance, 25 | AcceptModifications, 26 | StarkExForcedActionState, 27 | TokenAssetData, 28 | TokenQuantization, 29 | TokenRegister, 30 | TokenTransfers, 31 | KeyGetters, 32 | Deposits, 33 | Withdrawals 34 | { 35 | function initialize( 36 | bytes calldata /* data */ 37 | ) external override { 38 | revert("NOT_IMPLEMENTED"); 39 | } 40 | 41 | function initializerSize() external view override returns (uint256) { 42 | return 0; 43 | } 44 | 45 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 46 | uint256 len_ = 6; 47 | uint256 index_ = 0; 48 | 49 | selectors = new bytes4[](len_); 50 | selectors[index_++] = Deposits.depositCancel.selector; 51 | selectors[index_++] = Deposits.depositWithTokenIdReclaim.selector; 52 | selectors[index_++] = Deposits.depositReclaim.selector; 53 | selectors[index_++] = Withdrawals.withdraw.selector; 54 | selectors[index_++] = Withdrawals.withdrawAndMint.selector; 55 | selectors[index_++] = Withdrawals.withdrawWithTokenId.selector; 56 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 57 | } 58 | 59 | function identify() external pure override returns (string memory) { 60 | return "StarkWare_TokensAndRamping_2022_2"; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/tokens/ERC1155/IERC1155Receiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | Note: The ERC-165 identifier for this interface is 0x4e2312e0. 6 | */ 7 | interface IERC1155Receiver { 8 | /** 9 | Handles the receipt of a single ERC1155 token type. 10 | @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. 11 | This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. 12 | This function MUST revert if it rejects the transfer. 13 | Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. 14 | @param operator The address which initiated the transfer (i.e. msg.sender) 15 | @param from The address which previously owned the token 16 | @param id The ID of the token being transferred 17 | @param value The amount of tokens being transferred 18 | @param data Additional data with no specified format 19 | @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` . 20 | */ 21 | function onERC1155Received( 22 | address operator, 23 | address from, 24 | uint256 id, 25 | uint256 value, 26 | bytes calldata data 27 | ) external returns (bytes4); 28 | 29 | /** 30 | Handles the receipt of multiple ERC1155 token types. 31 | @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. 32 | This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). 33 | This function MUST revert if it rejects the transfer(s). 34 | Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. 35 | @param operator The address which initiated the batch transfer (i.e. msg.sender) 36 | @param from The address which previously owned the token 37 | @param ids An array containing ids of each token being transferred (order and length must match values array) 38 | @param values An array containing amounts of each token being transferred (order and length must match ids array) 39 | @param data Additional data with no specified format 40 | @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` . 41 | */ 42 | function onERC1155BatchReceived( 43 | address operator, 44 | address from, 45 | uint256[] calldata ids, 46 | uint256[] calldata values, 47 | bytes calldata data 48 | ) external returns (bytes4); 49 | } 50 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/tokens/ERC20/IERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /* 5 | Interface of the ERC20 standard as defined in the EIP. Does not include 6 | the optional functions; to access them see {ERC20Detailed}. 7 | */ 8 | interface IERC20 { 9 | function name() external view returns (string memory); 10 | 11 | function symbol() external view returns (string memory); 12 | 13 | function decimals() external view returns (uint8); 14 | 15 | function totalSupply() external view returns (uint256); 16 | 17 | function balanceOf(address account) external view returns (uint256); 18 | 19 | function transfer(address recipient, uint256 amount) external returns (bool); 20 | 21 | function allowance(address owner, address spender) external view returns (uint256); 22 | 23 | function approve(address spender, uint256 amount) external returns (bool); 24 | 25 | function transferFrom( 26 | address sender, 27 | address recipient, 28 | uint256 amount 29 | ) external returns (bool); 30 | 31 | event Transfer(address indexed from, address indexed to, uint256 value); 32 | 33 | event Approval(address indexed owner, address indexed spender, uint256 value); 34 | } 35 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/tokens/ERC721/IERC721.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | Required interface of an ERC721 compliant contract. 6 | */ 7 | interface IERC721 { 8 | event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); 9 | event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); 10 | event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 11 | 12 | /** 13 | Returns the number of NFTs in ``owner``'s account. 14 | */ 15 | function balanceOf(address owner) external view returns (uint256 balance); 16 | 17 | /** 18 | Returns the owner of the NFT specified by `tokenId`. 19 | */ 20 | function ownerOf(uint256 tokenId) external view returns (address owner); 21 | 22 | /** 23 | Transfers a specific NFT (`tokenId`) from one account (`from`) to 24 | another (`to`). 25 | 26 | 27 | 28 | Requirements: 29 | - `from`, `to` cannot be zero. 30 | - `tokenId` must be owned by `from`. 31 | - If the caller is not `from`, it must be have been allowed to move this 32 | NFT by either {approve} or {setApprovalForAll}. 33 | */ 34 | function safeTransferFrom( 35 | address from, 36 | address to, 37 | uint256 tokenId 38 | ) external; 39 | 40 | /** 41 | Transfers a specific NFT (`tokenId`) from one account (`from`) to 42 | another (`to`). 43 | Requirements: 44 | - If the caller is not `from`, it must be approved to move this NFT by 45 | either {approve} or {setApprovalForAll}. 46 | */ 47 | function transferFrom( 48 | address from, 49 | address to, 50 | uint256 tokenId 51 | ) external; 52 | 53 | function approve(address to, uint256 tokenId) external; 54 | 55 | function getApproved(uint256 tokenId) external view returns (address operator); 56 | 57 | function setApprovalForAll(address operator, bool _approved) external; 58 | 59 | function isApprovedForAll(address owner, address operator) external view returns (bool); 60 | 61 | function safeTransferFrom( 62 | address from, 63 | address to, 64 | uint256 tokenId, 65 | bytes calldata data 66 | ) external; 67 | } 68 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/tokens/ERC721/IERC721Receiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IERC721Receiver { 5 | function onERC721Received( 6 | address operator, 7 | address from, 8 | uint256 tokenId, 9 | bytes calldata data 10 | ) external returns (bytes4); 11 | } 12 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/toplevel_subcontracts/AllVerifiers.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/ApprovalChain.sol"; 5 | import "../components/AvailabilityVerifiers.sol"; 6 | import "../components/Freezable.sol"; 7 | import "../components/MainGovernance.sol"; 8 | import "../components/Verifiers.sol"; 9 | import "../interfaces/SubContractor.sol"; 10 | 11 | contract AllVerifiers is 12 | SubContractor, 13 | MainGovernance, 14 | Freezable, 15 | ApprovalChain, 16 | AvailabilityVerifiers, 17 | Verifiers 18 | { 19 | function initialize( 20 | bytes calldata /* data */ 21 | ) external override { 22 | revert("NOT_IMPLEMENTED"); 23 | } 24 | 25 | function initializerSize() external view override returns (uint256) { 26 | return 0; 27 | } 28 | 29 | function validatedSelectors() external pure override returns (bytes4[] memory selectors) { 30 | uint256 len_ = 1; 31 | uint256 index_ = 0; 32 | 33 | selectors = new bytes4[](len_); 34 | selectors[index_++] = Freezable.unFreeze.selector; 35 | require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); 36 | } 37 | 38 | function identify() external pure override returns (string memory) { 39 | return "StarkWare_AllVerifiers_2022_2"; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/ProxyGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/Governance.sol"; 5 | import "../components/GovernanceStorage.sol"; 6 | 7 | /** 8 | The Proxy contract is governed by one or more Governors of which the initial one is the 9 | deployer of the contract. 10 | 11 | A governor has the sole authority to perform the following operations: 12 | 13 | 1. Nominate additional governors (:sol:func:`proxyNominateNewGovernor`) 14 | 2. Remove other governors (:sol:func:`proxyRemoveGovernor`) 15 | 3. Add new `implementations` (proxied contracts) 16 | 4. Remove (new or old) `implementations` 17 | 5. Update `implementations` after a timelock allows it 18 | 19 | Adding governors is performed in a two step procedure: 20 | 21 | 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`) 22 | 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`) 23 | 24 | This two step procedure ensures that a governor public key cannot be nominated unless there is an 25 | entity that has the corresponding private key. This is intended to prevent errors in the addition 26 | process. 27 | 28 | The governor private key should typically be held in a secure cold wallet or managed via a 29 | multi-sig contract. 30 | */ 31 | /* 32 | Implements Governance for the proxy contract. 33 | It is a thin wrapper to the Governance contract, 34 | which is needed so that it can have non-colliding function names, 35 | and a specific tag (key) to allow unique state storage. 36 | */ 37 | contract ProxyGovernance is GovernanceStorage, Governance { 38 | // The tag is the string key that is used in the Governance storage mapping. 39 | string public constant PROXY_GOVERNANCE_TAG = "StarkEx.Proxy.2019.GovernorsInformation"; 40 | 41 | /* 42 | Returns the GovernanceInfoStruct associated with the governance tag. 43 | */ 44 | function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { 45 | return governanceInfo[PROXY_GOVERNANCE_TAG]; 46 | } 47 | 48 | function proxyIsGovernor(address testGovernor) external view returns (bool) { 49 | return _isGovernor(testGovernor); 50 | } 51 | 52 | function proxyNominateNewGovernor(address newGovernor) external { 53 | _nominateNewGovernor(newGovernor); 54 | } 55 | 56 | function proxyRemoveGovernor(address governorForRemoval) external { 57 | _removeGovernor(governorForRemoval); 58 | } 59 | 60 | function proxyAcceptGovernance() external { 61 | _acceptGovernance(); 62 | } 63 | 64 | function proxyCancelNomination() external { 65 | _cancelNomination(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/ProxyStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../components/GovernanceStorage.sol"; 5 | 6 | /* 7 | Holds the Proxy-specific state variables. 8 | This contract is inherited by the GovernanceStorage (and indirectly by MainStorage) 9 | to prevent collision hazard. 10 | */ 11 | contract ProxyStorage is GovernanceStorage { 12 | // NOLINTNEXTLINE: naming-convention uninitialized-state. 13 | mapping(address => bytes32) internal initializationHash_DEPRECATED; 14 | 15 | // The time after which we can switch to the implementation. 16 | // Hash(implementation, data, finalize) => time. 17 | mapping(bytes32 => uint256) internal enabledTime; 18 | 19 | // A central storage of the flags whether implementation has been initialized. 20 | // Note - it can be used flexibly enough to accommodate multiple levels of initialization 21 | // (i.e. using different key salting schemes for different initialization levels). 22 | mapping(bytes32 => bool) internal initialized; 23 | } 24 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/StorageSlots.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern. 6 | Storage address slots are a mechanism to define an arbitrary location, that will not be 7 | overlapped by the logical contracts. 8 | */ 9 | contract StorageSlots { 10 | // Storage slot with the address of the current implementation. 11 | // The address of the slot is keccak256("StarkWare2019.implemntation-slot"). 12 | // We need to keep this variable stored outside of the commonly used space, 13 | // so that it's not overrun by the logical implementation (the proxied contract). 14 | bytes32 internal constant IMPLEMENTATION_SLOT = 15 | 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24; 16 | 17 | // Storage slot with the address of the call-proxy current implementation. 18 | // The address of the slot is keccak256("'StarkWare2020.CallProxy.Implemntation.Slot'"). 19 | // We need to keep this variable stored outside of the commonly used space. 20 | // so that it's not overrun by the logical implementation (the proxied contract). 21 | bytes32 internal constant CALL_PROXY_IMPL_SLOT = 22 | 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be; 23 | 24 | // This storage slot stores the finalization flag. 25 | // Once the value stored in this slot is set to non-zero 26 | // the proxy blocks implementation upgrades. 27 | // The current implementation is then referred to as Finalized. 28 | // Web3.solidityKeccak(['string'], ["StarkWare2019.finalization-flag-slot"]). 29 | bytes32 internal constant FINALIZED_STATE_SLOT = 30 | 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2; 31 | 32 | // Storage slot to hold the upgrade delay (time-lock). 33 | // The intention of this slot is to allow modification using an EIC. 34 | // Web3.solidityKeccak(['string'], ['StarkWare.Upgradibility.Delay.Slot']). 35 | bytes32 public constant UPGRADE_DELAY_SLOT = 36 | 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f; 37 | } 38 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/ChangeVerifiersExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/ExternalInitializer.sol"; 5 | import "../../interfaces/Identity.sol"; 6 | import "../../components/MainStorage.sol"; 7 | import "../../libraries/Common.sol"; 8 | import "../../libraries/LibConstants.sol"; 9 | 10 | /* 11 | This contract is a simple implementation of an external initializing contract 12 | that removes all existing verifiers and committees and install the ones provided in parameters. 13 | */ 14 | contract ChangeVerifiersExternalInitializer is ExternalInitializer, MainStorage, LibConstants { 15 | using Addresses for address; 16 | uint256 constant ENTRY_NOT_FOUND = uint256(~0); 17 | 18 | /* 19 | The initiatialize function gets four parameters in the bytes array: 20 | 1. New verifier address, 21 | 2. Keccak256 of the expected verifier id. 22 | 3. New availability verifier address, 23 | 4. Keccak256 of the expected availability verifier id. 24 | */ 25 | function initialize(bytes calldata data) public virtual override { 26 | require(data.length == 128, "UNEXPECTED_DATA_SIZE"); 27 | address newVerifierAddress; 28 | bytes32 verifierIdHash; 29 | address newAvailabilityVerifierAddress; 30 | bytes32 availabilityVerifierIdHash; 31 | 32 | // Extract sub-contract address and hash of verifierId. 33 | ( 34 | newVerifierAddress, 35 | verifierIdHash, 36 | newAvailabilityVerifierAddress, 37 | availabilityVerifierIdHash 38 | ) = abi.decode(data, (address, bytes32, address, bytes32)); 39 | 40 | // Flush the entire verifiers list. 41 | delete verifiersChain.list; 42 | delete availabilityVerifiersChain.list; 43 | 44 | // ApprovalChain addEntry performs all the required checks for us. 45 | addEntry(verifiersChain, newVerifierAddress, MAX_VERIFIER_COUNT, verifierIdHash); 46 | addEntry( 47 | availabilityVerifiersChain, 48 | newAvailabilityVerifierAddress, 49 | MAX_VERIFIER_COUNT, 50 | availabilityVerifierIdHash 51 | ); 52 | 53 | emit LogExternalInitialize(data); 54 | } 55 | 56 | /* 57 | The functions below are taken from ApprovalChain.sol, with minor changes: 58 | 1. No governance needed (we are under the context where proxy governance is granted). 59 | 2. The verifier ID is passed as hash, and not as string. 60 | */ 61 | function addEntry( 62 | StarkExTypes.ApprovalChainData storage chain, 63 | address entry, 64 | uint256 maxLength, 65 | bytes32 hashExpectedId 66 | ) internal { 67 | address[] storage list = chain.list; 68 | require(entry.isContract(), "ADDRESS_NOT_CONTRACT"); 69 | bytes32 hashRealId = keccak256(abi.encodePacked(Identity(entry).identify())); 70 | require(hashRealId == hashExpectedId, "UNEXPECTED_CONTRACT_IDENTIFIER"); 71 | require(list.length < maxLength, "CHAIN_AT_MAX_CAPACITY"); 72 | require(findEntry(list, entry) == ENTRY_NOT_FOUND, "ENTRY_ALREADY_EXISTS"); 73 | chain.list.push(entry); // NOLINT controlled-array-length; 74 | chain.unlockedForRemovalTime[entry] = 0; 75 | } 76 | 77 | function findEntry(address[] storage list, address entry) internal view returns (uint256) { 78 | uint256 n_entries = list.length; 79 | for (uint256 i = 0; i < n_entries; i++) { 80 | if (list[i] == entry) { 81 | return i; 82 | } 83 | } 84 | return ENTRY_NOT_FOUND; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/ChangeVerifiersZeroTimelockExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "./ChangeVerifiersExternalInitializer.sol"; 5 | import "./ModifyUpgradeDelayExternalInitializer.sol"; 6 | 7 | /* 8 | This contract is a simple implementation of an external initializing contract 9 | that removes all existing verifiers and committees and install the ones provided in parameters. 10 | 11 | It also sets the Proxy upgrade timelock to zero. 12 | */ 13 | contract ChangeVerifiersZeroTimelockExternalInitializer is 14 | ChangeVerifiersExternalInitializer, 15 | ModifyUpgradeDelayExternalInitializer 16 | { 17 | function initialize(bytes calldata data) 18 | public 19 | override(ChangeVerifiersExternalInitializer, ModifyUpgradeDelayExternalInitializer) 20 | { 21 | ChangeVerifiersExternalInitializer.initialize(data); 22 | 23 | setUpgradeDelay(0); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/ModifyConfigurationDelayExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/ExternalInitializer.sol"; 5 | import "../../perpetual/components/PerpetualStorage.sol"; 6 | 7 | /* 8 | This contract is an external initializing contract that modifies the upgradability proxy 9 | upgrade activation delay. 10 | */ 11 | contract ModifyConfigurationDelayExternalInitializer is ExternalInitializer, PerpetualStorage { 12 | uint256 constant MAX_CONFIG_DELAY = 28 days; 13 | 14 | function initialize(bytes calldata data) external override { 15 | require(data.length == 32, "INCORRECT_INIT_DATA_SIZE_32"); 16 | uint256 delayInSeconds; 17 | (delayInSeconds) = abi.decode(data, (uint256)); 18 | 19 | require(delayInSeconds <= MAX_CONFIG_DELAY, "DELAY_TIME_TOO_LONG"); 20 | configurationDelay = delayInSeconds; 21 | 22 | emit LogExternalInitialize(data); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/ModifyUpgradeDelayExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/ExternalInitializer.sol"; 5 | 6 | /* 7 | This contract is an external initializing contract that modifies the upgradability proxy 8 | upgrade activation delay. 9 | */ 10 | contract ModifyUpgradeDelayExternalInitializer is ExternalInitializer { 11 | uint256 constant MAX_DELAY = 28 days; 12 | 13 | // Web3.solidityKeccak(['string'], ['StarkWare.Upgradibility.Delay.Slot']). 14 | bytes32 constant UPGRADE_DELAY_SLOT = 15 | 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f; 16 | 17 | function initialize(bytes calldata data) external virtual override { 18 | require(data.length == 32, "INCORRECT_INIT_DATA_SIZE_32"); 19 | uint256 delayInSeconds; 20 | (delayInSeconds) = abi.decode(data, (uint256)); 21 | 22 | setUpgradeDelay(delayInSeconds); 23 | 24 | emit LogExternalInitialize(data); 25 | } 26 | 27 | function setUpgradeDelay(uint256 delayInSeconds) internal virtual { 28 | require(delayInSeconds <= MAX_DELAY, "DELAY_TOO_LONG"); 29 | 30 | // To support V1 Proxy - we use the expected slot. 31 | // For V2+ we query the Proxy to provide a slot. 32 | bytes32 slot = UPGRADE_DELAY_SLOT; 33 | 34 | //NOLINTNEXTLINE low-level-calls reentrancy-events. 35 | (bool success, bytes memory returndata) = address(this).staticcall( 36 | abi.encodeWithSignature("UPGRADE_DELAY_SLOT()") 37 | ); 38 | 39 | if (success) { 40 | slot = abi.decode(returndata, (bytes32)); 41 | } 42 | 43 | assembly { 44 | sstore(slot, delayInSeconds) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/ReplaceEscapeVerifierExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/ExternalInitializer.sol"; 5 | import "../../interfaces/Identity.sol"; 6 | import "../../interfaces/IFactRegistry.sol"; 7 | import "../../components/MainStorage.sol"; 8 | import "../../libraries/Common.sol"; 9 | import "../../libraries/LibConstants.sol"; 10 | 11 | /* 12 | This contract is an external initializing contract that replaces the escape verifier used by 13 | the main contract. 14 | */ 15 | contract ReplaceEscapeVerifierExternalInitializer is 16 | ExternalInitializer, 17 | MainStorage, 18 | LibConstants 19 | { 20 | using Addresses for address; 21 | 22 | /* 23 | The initiatialize function gets two parameters in the bytes array: 24 | 1. New escape verifier address, 25 | 2. Keccak256 of the expected id of the contract provied in (1). 26 | */ 27 | function initialize(bytes calldata data) external override { 28 | require(data.length == 64, "UNEXPECTED_DATA_SIZE"); 29 | 30 | // Extract sub-contract address and hash of verifierId. 31 | (address newEscapeVerifierAddress, bytes32 escapeVerifierIdHash) = abi.decode( 32 | data, 33 | (address, bytes32) 34 | ); 35 | 36 | require(newEscapeVerifierAddress.isContract(), "ADDRESS_NOT_CONTRACT"); 37 | bytes32 contractIdHash = keccak256( 38 | abi.encodePacked(Identity(newEscapeVerifierAddress).identify()) 39 | ); 40 | require(contractIdHash == escapeVerifierIdHash, "UNEXPECTED_CONTRACT_IDENTIFIER"); 41 | 42 | // Replace the escape verifier address in storage. 43 | escapeVerifierAddress = newEscapeVerifierAddress; 44 | 45 | emit LogExternalInitialize(data); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /scalable-dex/contracts/src/upgrade/eic/UpdatePerpetualConfigExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "../../interfaces/ExternalInitializer.sol"; 5 | import "../../perpetual/PerpetualConstants.sol"; 6 | import "../../perpetual/components/PerpetualStorage.sol"; 7 | 8 | /* 9 | This contract is simple impelementation of an external initializing contract 10 | that configures/reconfigures main contract configuration. 11 | */ 12 | contract UpdatePerpetualConfigExternalInitializer is 13 | ExternalInitializer, 14 | PerpetualStorage, 15 | PerpetualConstants 16 | { 17 | event LogGlobalConfigurationApplied(bytes32 configHash); 18 | event LogAssetConfigurationApplied(uint256 assetId, bytes32 configHash); 19 | 20 | function initialize(bytes calldata data) external override { 21 | require(data.length % 64 == 0, "NOT_WORDS_PAIRS_DATA_LENGTH_ERROR"); 22 | uint256 GLOBAL_CONFIG_KEY = uint256(~0); 23 | uint256 nConfigPairs = data.length / 64; 24 | uint256 offset = 32; 25 | bytes memory _data = data; 26 | for (uint256 pair = 0; pair < nConfigPairs; pair++) { 27 | uint256 configKey; 28 | bytes32 configHash; 29 | assembly { 30 | configKey := mload(add(_data, offset)) 31 | configHash := mload(add(_data, add(32, offset))) 32 | } 33 | require(uint256(configHash) < K_MODULUS, "INVALID_CONFIG_HASH"); 34 | 35 | if (configKey == GLOBAL_CONFIG_KEY) { 36 | globalConfigurationHash = configHash; // NOLINT costly-loop. 37 | emit LogGlobalConfigurationApplied(configHash); 38 | } else { 39 | require(configKey < PERPETUAL_ASSET_ID_UPPER_BOUND, "INVALID_ASSET_ID"); 40 | configurationHash[configKey] = configHash; // NOLINT costly-loop. 41 | emit LogAssetConfigurationApplied(configKey, configHash); 42 | } 43 | 44 | offset += 64; 45 | } 46 | emit LogExternalInitialize(data); 47 | } 48 | } 49 | --------------------------------------------------------------------------------