├── .debug.env ├── .env.example ├── .github ├── template │ └── create-pull-request.md └── workflows │ ├── create-PR-deploy-to-release.yml │ ├── create-PR-implement-to-feature.yml │ ├── create-PR-release-to-feature.yml │ ├── create-PR-release-to-network.yml │ ├── create-release-tag.yml │ └── test.yml ├── .gitignore ├── .gitmodules ├── .husky ├── .gitignore ├── generate-layout.sh ├── pre-commit ├── pre-push └── storage-logger.js ├── .npmrc.example ├── .prettierrc.json ├── README.md ├── broadcast.sh ├── broadcast ├── 20231130_DeployDevnet.s.sol │ └── 2022 │ │ ├── run-1701407131.json │ │ ├── run-1701407139.json │ │ └── run-latest.json ├── 20232811_ChangeGovernanceAdmin_AlreadyHardfork.s.sol │ └── 2021 │ │ ├── run-1704869823.json │ │ └── run-latest.json ├── 20240121_Upgrade_ReleaseV0.7.2_Testnet.s.sol │ └── 2021 │ │ ├── run-1706002779.json │ │ ├── run-1706526586.json │ │ └── run-latest.json ├── 20240219_Upgrade_ReleaseV0.7.2_Patch_Testnet.s.sol │ └── 2021 │ │ ├── run-1708327267.json │ │ └── run-latest.json ├── 20240220_Full_mainnet_Miko_Hardfork.s.sol │ └── 2020 │ │ ├── run-1709535738.json │ │ ├── run-1709799883.json │ │ ├── run-1709800022.json │ │ └── run-latest.json ├── 20240223_UpgradeTestnet_v0_7_5.s.sol │ └── 2021 │ │ ├── run-1709202436.json │ │ └── run-latest.json ├── 2024022_UpgradeTestnet_v0_7_3.s.sol │ └── 2021 │ │ ├── run-1708575999.json │ │ ├── run-1708576197.json │ │ ├── run-1708662131.json │ │ └── run-latest.json ├── 20240301_UpgradeTestnet_v0_7_6.s.sol │ └── 2021 │ │ ├── run-1709285545.json │ │ └── run-latest.json ├── 20242103_UpgradeTestnet_v0_7_7.s.sol │ └── 2021 │ │ ├── run-1711094054.json │ │ └── run-latest.json ├── 20242203_UpgradeMainnet_v0_7_7.s.sol │ └── 2020 │ │ ├── run-1711425945.json │ │ ├── run-1711426116.json │ │ ├── run-1711427088.json │ │ ├── run-1711427230.json │ │ └── run-1711428512.json ├── ClearNonce.s.sol │ └── 2020 │ │ └── run-1709541316.json └── OnchainExecutor.s.sol │ └── 2021 │ ├── run-1706004590.json │ ├── run-1706004597.json │ └── run-latest.json ├── contracts ├── extensions │ ├── GatewayV3.sol │ ├── GovernanceAdmin.sol │ ├── MinimumWithdrawal.sol │ ├── RONTransferHelper.sol │ ├── TransparentUpgradeableProxyV2.sol │ ├── WithdrawalLimitation.sol │ ├── bridge-operator-governance │ │ ├── BridgeManager.sol │ │ ├── BridgeManagerCallbackRegister.sol │ │ └── BridgeTrackingHelper.sol │ ├── collections │ │ ├── HasContracts.sol │ │ └── HasProxyAdmin.sol │ ├── consumers │ │ ├── GlobalConfigConsumer.sol │ │ └── PercentageConsumer.sol │ ├── forwarder │ │ └── Forwarder.sol │ ├── sequential-governance │ │ ├── CoreGovernance.sol │ │ ├── GlobalCoreGovernance.sol │ │ ├── governance-proposal │ │ │ ├── CommonGovernanceProposal.sol │ │ │ ├── GlobalGovernanceProposal.sol │ │ │ └── GovernanceProposal.sol │ │ └── governance-relay │ │ │ ├── CommonGovernanceRelay.sol │ │ │ ├── GlobalGovernanceRelay.sol │ │ │ └── GovernanceRelay.sol │ └── version-control │ │ └── ConditionalImplementControl.sol ├── interfaces │ ├── IBridge.sol │ ├── IBridgeAdminProposal.sol │ ├── IERC20Mintable.sol │ ├── IERC721Mintable.sol │ ├── IFastFinalityTracking.sol │ ├── IMainchainGatewayV3.sol │ ├── IMaintenance.sol │ ├── IPauseTarget.sol │ ├── IProfile.sol │ ├── IQuorum.sol │ ├── IRoninGatewayV3.sol │ ├── IRoninGovernanceAdmin.sol │ ├── IRoninTrustedOrganization.sol │ ├── IStakingVesting.sol │ ├── IWETH.sol │ ├── bridge │ │ ├── IBridgeManager.sol │ │ ├── IBridgeManagerCallback.sol │ │ ├── IBridgeManagerCallbackRegister.sol │ │ ├── IBridgeReward.sol │ │ ├── IBridgeSlash.sol │ │ ├── IBridgeTracking.sol │ │ └── events │ │ │ ├── IBridgeManagerEvents.sol │ │ │ ├── IBridgeRewardEvents.sol │ │ │ └── IBridgeSlashEvents.sol │ ├── collections │ │ └── IHasContracts.sol │ ├── consumers │ │ ├── ChainTypeConsumer.sol │ │ ├── MappedTokenConsumer.sol │ │ ├── PeriodWrapperConsumer.sol │ │ ├── SignatureConsumer.sol │ │ ├── VoteStatusConsumer.sol │ │ └── WeightedAddressConsumer.sol │ ├── slash-indicator │ │ ├── IBaseSlash.sol │ │ ├── ICreditScore.sol │ │ ├── ISlashDoubleSign.sol │ │ ├── ISlashFastFinality.sol │ │ ├── ISlashIndicator.sol │ │ └── ISlashUnavailability.sol │ ├── staking │ │ ├── IBaseStaking.sol │ │ ├── ICandidateStaking.sol │ │ ├── IDelegatorStaking.sol │ │ ├── IRewardPool.sol │ │ ├── IStaking.sol │ │ └── IStakingCallback.sol │ ├── validator │ │ ├── ICandidateManager.sol │ │ ├── ICandidateManagerCallback.sol │ │ ├── ICoinbaseExecution.sol │ │ ├── IEmergencyExit.sol │ │ ├── IRoninValidatorSet.sol │ │ ├── ISlashingExecution.sol │ │ └── info-fragments │ │ │ ├── ICommonInfo.sol │ │ │ ├── IJailingInfo.sol │ │ │ ├── ITimingInfo.sol │ │ │ └── IValidatorInfoV2.sol │ └── version-control │ │ └── IConditionalImplementControl.sol ├── libraries │ ├── AddressArrayUtils.sol │ ├── Ballot.sol │ ├── BridgeOperatorsBallot.sol │ ├── EmergencyExitBallot.sol │ ├── EnumFlags.sol │ ├── ErrorHandler.sol │ ├── GlobalProposal.sol │ ├── IsolatedGovernance.sol │ ├── Math.sol │ ├── Proposal.sol │ ├── Token.sol │ └── Transfer.sol ├── mainchain │ ├── MainchainBridgeManager.sol │ └── MainchainGatewayV3.sol ├── mocks │ ├── MockBridge.sol │ ├── MockGatewayForTracking.sol │ ├── MockPrecompile.sol │ ├── MockProfile.sol │ ├── MockSlashIndicatorExtended.sol │ ├── MockStaking.sol │ ├── MockTransferFallback.sol │ ├── forwarder │ │ └── MockForwarderTarget.sol │ ├── libraries │ │ └── Sorting.sol │ ├── precompile-usages │ │ ├── MockPCUPickValidatorSet.sol │ │ ├── MockPCUSortValidators.sol │ │ ├── MockPCUValidateDoubleSign.sol │ │ └── MockPCUValidateFastFinality.sol │ ├── ronin │ │ ├── MockBridgeManager.sol │ │ ├── MockBridgeReward.sol │ │ ├── MockBridgeSlash.sol │ │ ├── MockBridgeTracking.sol │ │ ├── MockRoninBridgeManager.sol │ │ ├── MockRoninGatewayV3Extended.sol │ │ └── MockValidatorContract.sol │ ├── sorting │ │ └── MockSorting.sol │ ├── types │ │ └── MockTUint256Slot.sol │ ├── utils │ │ └── version-control │ │ │ ├── MockActor.sol │ │ │ ├── MockConditionalImplementControl.sol │ │ │ ├── MockLogic.sol │ │ │ └── MockLogicValidatorSet.sol │ └── validator │ │ ├── MockRoninValidatorSetExtended.sol │ │ ├── MockRoninValidatorSetOverridePrecompile.sol │ │ └── MockValidatorSet.sol ├── multi-chains │ └── RoninTrustedOrganization.sol ├── precompile-usages │ ├── PCUPickValidatorSet.sol │ ├── PCUSortValidators.sol │ ├── PCUValidateDoubleSign.sol │ ├── PCUValidateFastFinality.sol │ ├── PCUVerifyBLSPublicKey.sol │ └── PrecompiledUsage.sol ├── ronin │ ├── Maintenance.sol │ ├── RoninGovernanceAdmin.sol │ ├── StakingVesting.sol │ ├── VaultForwarder.sol │ ├── fast-finality │ │ └── FastFinalityTracking.sol │ ├── gateway │ │ ├── BridgeReward.sol │ │ ├── BridgeSlash.sol │ │ ├── BridgeTracking.sol │ │ ├── PauseEnforcer.sol │ │ ├── RoninBridgeManager.sol │ │ └── RoninGatewayV3.sol │ ├── profile │ │ ├── Profile.sol │ │ ├── ProfileHandler.sol │ │ ├── ProfileStorage.sol │ │ ├── ProfileXComponents.sol │ │ └── Profile_Mainnet.sol │ ├── slash-indicator │ │ ├── CreditScore.sol │ │ ├── DeprecatedSlashBridgeOperator.sol │ │ ├── DeprecatedSlashBridgeVoting.sol │ │ ├── SlashDoubleSign.sol │ │ ├── SlashFastFinality.sol │ │ ├── SlashIndicator.sol │ │ └── SlashUnavailability.sol │ ├── staking │ │ ├── BaseStaking.sol │ │ ├── CandidateStaking.sol │ │ ├── DelegatorStaking.sol │ │ ├── RewardCalculation.sol │ │ ├── Staking.sol │ │ └── StakingCallback.sol │ └── validator │ │ ├── CandidateManager.sol │ │ ├── CandidateManagerCallback.sol │ │ ├── CoinbaseExecution.sol │ │ ├── EmergencyExit.sol │ │ ├── RoninValidatorSet.sol │ │ ├── SlashingExecution.sol │ │ ├── migrations │ │ ├── NotifiedMigrator.sol │ │ └── RoninValidatorSetTimedMigrator.sol │ │ └── storage-fragments │ │ ├── CommonStorage.sol │ │ ├── JailingStorage.sol │ │ ├── TimingStorage.sol │ │ └── ValidatorInfoStorageV2.sol ├── types │ ├── Types.sol │ └── operations │ │ └── LibTUint256Slot.sol ├── udvts │ └── Types.sol └── utils │ ├── CommonErrors.sol │ ├── ContractType.sol │ ├── DeprecatedSlots.sol │ ├── IdentityGuard.sol │ └── RoleAccess.sol ├── debug.sh ├── deployments ├── ethereum │ ├── .chainId │ ├── MainchainBridgeManager.json │ ├── MainchainGatewayPauseEnforcer.json │ ├── MainchainGatewayV2Logic.json │ ├── MainchainGatewayV3Logic.json │ ├── MainchainGatewayV3Proxy.json │ ├── MainchainGovernanceAdmin.json │ ├── MainchainRoninTrustedOrganizationProxy.json │ ├── RoninTrustedOrganizationLogic.json │ └── solcInputs │ │ ├── a50a3f056fa24c0b5a230a9cb29a1cb4.json │ │ ├── d5751a51f1eb067d18a7dec1633f85eb.json │ │ └── f9f5036294d35a88da21dae55fc8b26c.json ├── goerli-for-devnet │ ├── .chainId │ ├── MainchainGatewayV2Logic.json │ ├── MainchainGatewayV2Proxy.json │ ├── MainchainGovernanceAdmin.json │ ├── MainchainRoninTrustedOrganizationProxy.json │ ├── RoninTrustedOrganizationLogic.json │ └── solcInputs │ │ └── a595501ecf8849639d4423c21e560992.json ├── goerli │ ├── .chainId │ ├── MainchainBridgeManager.json │ ├── MainchainGatewayV2Logic.json │ ├── MainchainGatewayV3Proxy.json │ ├── MainchainGovernanceAdmin.json │ ├── MainchainRoninTrustedOrganizationProxy.json │ ├── RoninTrustedOrganizationLogic.json │ └── solcInputs │ │ ├── 0e0029e5f6489210962bd9d9c865993b.json │ │ ├── 1d53902dd90cd91eebd679fc038e76a6.json │ │ ├── 4a6c2d91e409e6ff92e726e537003433.json │ │ ├── 5bb29245382eed46bc25ba7e9a5b8468.json │ │ ├── 649d75c35df9aa0a1c5d1e3d0fd3d7f0.json │ │ ├── 69cdeb5d1a6643a104aa4e9d6c9c4474.json │ │ ├── 6c219cc499cc18168de5a543cc795d09.json │ │ ├── 91c86e27ca97788283e420647ecde76c.json │ │ ├── 95f7f074e14fa276eae26f8589bbed19.json │ │ ├── b3df7cb649c86d7664793a52a614dd89.json │ │ ├── bc351f4dba527ae648ad8fe83fbf45f7.json │ │ ├── d00a46919a8595a1f6b347cca5808c82.json │ │ └── e5433e92544a5ed2fdcde3db287143e0.json ├── ronin-devnet │ ├── .chainId │ ├── FastFinalityTrackingLogic.json │ ├── FastFinalityTrackingProxy.json │ ├── MaintenanceLogic.json │ ├── MaintenanceProxy.json │ ├── MockPrecompileLogic.json │ ├── ProfileLogic.json │ ├── ProfileProxy.json │ ├── RoninGatewayV2Proxy.json │ ├── RoninGovernanceAdmin.json │ ├── RoninTrustedOrganizationLogic.json │ ├── RoninTrustedOrganizationProxy.json │ ├── RoninValidatorSetLogic.json │ ├── RoninValidatorSetProxy.json │ ├── SlashIndicatorLogic.json │ ├── SlashIndicatorProxy.json │ ├── StakingLogic.json │ ├── StakingProxy.json │ ├── StakingVestingLogic.json │ ├── StakingVestingProxy.json │ └── solcInputs │ │ ├── 18ec66ad9c9493b539428af6024664b9.json │ │ └── 33a5e775040e895cdb45bd3122ed5a59.json ├── ronin-mainnet │ ├── .chainId │ ├── BridgeRewardLogic.json │ ├── BridgeRewardProxy.json │ ├── BridgeSlashLogic.json │ ├── BridgeSlashProxy.json │ ├── BridgeTrackingLogic.json │ ├── BridgeTrackingProxy.json │ ├── FastFinalityTrackingLogic.json │ ├── FastFinalityTrackingProxy.json │ ├── MaintenanceLogic.json │ ├── MaintenanceProxy.json │ ├── ProfileLogic.json │ ├── ProfileProxy.json │ ├── RoninBridgeManager.json │ ├── RoninGatewayPauseEnforcer.json │ ├── RoninGatewayV2Logic.json │ ├── RoninGatewayV3Logic.json │ ├── RoninGatewayV3Proxy.json │ ├── RoninGovernanceAdmin.json │ ├── RoninTrustedOrganizationLogic.json │ ├── RoninTrustedOrganizationProxy.json │ ├── RoninValidatorSetLogic.json │ ├── RoninValidatorSetProxy.json │ ├── SlashIndicatorLogic.json │ ├── SlashIndicatorProxy.json │ ├── StakingLogic.json │ ├── StakingProxy.json │ ├── StakingVestingLogic.json │ ├── StakingVestingProxy.json │ └── solcInputs │ │ ├── 03301f9cfaf1eb8782a7c2a7b1973053.json │ │ ├── 03f80198b6fb66d528e408eabca5a782.json │ │ ├── 0e13282b1de32a862f3ea9c3dc0543e9.json │ │ ├── 20f35804d80bd26382f04e7db0eee067.json │ │ ├── 2a8db5de0d3bfe0cb40ba15ae8460f16.json │ │ ├── 422111e5f86a477b6b848406a53c66fd.json │ │ ├── 85b953b22882c536a643bf4b61b3153b.json │ │ ├── 8a10de68ec323e5be85b46f42143fc19.json │ │ ├── a50a3f056fa24c0b5a230a9cb29a1cb4.json │ │ ├── c681844a462c08b610099ffca6511819.json │ │ ├── cee8587b26e080f856978a2f78dd6e87.json │ │ ├── d5751a51f1eb067d18a7dec1633f85eb.json │ │ ├── d621ebdfe20690422990472986e02493.json │ │ ├── dc057a85cb82f6c5109f62edfa65ae8d.json │ │ ├── e5a25d4d8d73a1ea3c0b389e9873eeb5.json │ │ └── f9f5036294d35a88da21dae55fc8b26c.json └── ronin-testnet │ ├── .chainId │ ├── BridgeRewardLogic.json │ ├── BridgeRewardProxy.json │ ├── BridgeSlashLogic.json │ ├── BridgeSlashProxy.json │ ├── BridgeTrackingLogic.json │ ├── BridgeTrackingProxy.json │ ├── FastFinalityTrackingLogic.json │ ├── FastFinalityTrackingProxy.json │ ├── ForwarderLogic-0.json │ ├── ForwarderLogic-1.json │ ├── ForwarderLogic-2.json │ ├── ForwarderLogic-3.json │ ├── ForwarderLogic-4.json │ ├── MaintenanceLogic.json │ ├── MaintenanceProxy.json │ ├── ProfileLogic.json │ ├── ProfileProxy.json │ ├── RoninBridgeManager.json │ ├── RoninGatewayPauseEnforcer.json │ ├── RoninGatewayPauseEnforcerLogic.json │ ├── RoninGatewayPauseEnforcerProxy.json │ ├── RoninGatewayV2Logic.json │ ├── RoninGovernanceAdmin.json │ ├── RoninTrustedOrganizationLogic.json │ ├── RoninTrustedOrganizationProxy.json │ ├── RoninTrustedOrganizationTempLogic.json │ ├── RoninValidatorSetLogic.json │ ├── RoninValidatorSetProxy.json │ ├── RoninValidatorSetTimedMigrator.json │ ├── SlashIndicatorLogic.json │ ├── SlashIndicatorProxy.json │ ├── StakingLogic.json │ ├── StakingProxy.json │ ├── StakingVestingLogic.json │ ├── StakingVestingProxy.json │ ├── VaultForwarder-qc-test.json │ └── solcInputs │ ├── 04a9bbd243a024f931581fbb384106a3.json │ ├── 0f25a5224eeb8772a3c38ebf9ab9bb4c.json │ ├── 178fd61415a2f08ac5a40f24b2de13c7.json │ ├── 1abe3fccfa260ef2553161b857d04cdf.json │ ├── 1c9545b53bd05cedc4599c9295449bf2.json │ ├── 1fd2739e5c5a547bccbf26ee45f48ee5.json │ ├── 28b4851e3868f34350c9d7d76cba2b15.json │ ├── 2a8db5de0d3bfe0cb40ba15ae8460f16.json │ ├── 2dccd829348aefebbef587667549cd38.json │ ├── 306cfcffeca66af05c8925f3663c976b.json │ ├── 3299d34e365adc9e996c392b1b635253.json │ ├── 32a7e9e9c4483168440a504f53411aa2.json │ ├── 391431ae2d12b53e8d8ece51e5badeb1.json │ ├── 3c352db0d062e062f7c0c18610e9070b.json │ ├── 5bb29245382eed46bc25ba7e9a5b8468.json │ ├── 620e7fce96c816676611b10f2eff3c99.json │ ├── 69cdeb5d1a6643a104aa4e9d6c9c4474.json │ ├── 6bc16cc8f779fe2f1f4f2733e87f867e.json │ ├── 6c219cc499cc18168de5a543cc795d09.json │ ├── 6d67256db1844d3deb1c932d686229ba.json │ ├── 6da162a003a00b6a8800b1f2bcac773f.json │ ├── 7ee7c0f941167beb3dcb34451beb8d74.json │ ├── 7fade609df5c39259a798d63a8b44cf7.json │ ├── 85b953b22882c536a643bf4b61b3153b.json │ ├── 8de8f567dee21c26fd39413b873c2cc0.json │ ├── 95921af9e3b453fd5a2d5edf43163a69.json │ ├── 95f7f074e14fa276eae26f8589bbed19.json │ ├── 9c14b324033beb5ee990c4b68d9e780e.json │ ├── 9ed9cfd78768299e018b7787a7a517a7.json │ ├── a796d73067aeba8c0972d7c98e4ac22f.json │ ├── a9bab0335465d2e01ea22d5aa6e9c8ee.json │ ├── b469203c60a069be0ec276c20622629d.json │ ├── c822a4eaf18578f72a5b51dc23e569e1.json │ ├── cd4cbfe79902eedb96cb295a21718e7c.json │ ├── cdde56eaaab588da535ec1bdc2df93c0.json │ ├── d00a46919a8595a1f6b347cca5808c82.json │ ├── d85d6f97c6f4b4f4d9c883d9b13849c8.json │ ├── df83b9bf4eb9555928fe59c42cc1073a.json │ ├── e0bf9fd4a684fe34b60b71a3b24ddf73.json │ ├── e42cb5445b9a1c41a9e185b53bac5bc7.json │ ├── ee86aabd57580622aa8c089c61bb4d3f.json │ ├── f5939ebe47e4086c92eac99ab2681ceb.json │ └── fe93f1bdb589f17fa072eb15176e0821.json ├── docs ├── CHEATSHEET.md ├── HACK.md ├── README.md └── assets │ ├── Deposit.png │ ├── Governance.png │ ├── Validator Contract Overview.png │ └── Withdrawal.png ├── foundry.toml ├── hardhat.config.ts ├── logs ├── .gas-snapshot ├── contract_code_sizes.log ├── migrations │ └── REP002-REP003 │ │ ├── 20231003_REP002AndREP003_RON.log │ │ ├── 20231003_REP002AndREP003_RON_NonConditional.log │ │ └── 20231003_REP002AndREP003_RON_NonConditional_Wrapup2Periods.log ├── storageLayout │ ├── maintenance-v0.7.6.txt │ └── maintenance-v0.7.7.txt └── storage_layout.log ├── package.json ├── pull_request_template.md ├── remappings.txt ├── run.sh ├── script ├── 20231003-rep-002-rep-003 │ ├── 20231003_REP002AndREP003_Base.s.sol │ ├── 20231003_REP002AndREP003_ETH.s.sol │ ├── 20231003_REP002AndREP003_RON.s.sol │ ├── 20231003_REP002AndREP003_RON_NonConditional.s.sol │ ├── 20231003_REP002AndREP003_RON_NonConditional_GatewayUpgrade.s.sol │ ├── 20231003_REP002AndREP003_RON_NonConditional_GatewayUpgrade_ActualProposals.s.sol │ ├── 20231003_REP002AndREP003_RON_NonConditional_GatewayUpgrade_Approve.sol │ ├── 20231003_REP002AndREP003_RON_NonConditional_Wrapup2Periods.s.sol │ ├── 20231003_REP002_AddBridgeOperators_ActualProposal.s.sol │ └── 20231016_ReconfigBridgeTracking.sol ├── 20231019-recover-fund │ ├── 20231019_RecoverFund.s.sol │ └── contracts │ │ └── BridgeTrackingRecoveryLogic.sol ├── 20231130-deploy-devnet │ ├── 20231130_DeployDevnet.s.sol │ ├── DevnetMigration.s.sol │ ├── contracts │ │ ├── FastFinalityTrackingDeploy.s.sol │ │ ├── MaintenanceDeploy.s.sol │ │ ├── ProfileDeploy.s.sol │ │ ├── RoninGovernanceAdminDeploy.s.sol │ │ ├── RoninTrustedOrganizationDeploy.s.sol │ │ ├── RoninValidatorSetDeploy.s.sol │ │ ├── SlashIndicatorDeploy.s.sol │ │ ├── StakingDeploy.s.sol │ │ └── StakingVestingDeploy.s.sol │ └── interfaces │ │ └── ISharedArgument.sol ├── 20231212-deploy-testnet │ ├── 20231212_DeployTestnet.s.sol │ ├── TestnetMigration.s.sol │ ├── contracts │ │ ├── FastFinalityTrackingDeploy.s.sol │ │ ├── MaintenanceDeploy.s.sol │ │ ├── ProfileDeploy.s.sol │ │ ├── RoninGovernanceAdminDeploy.s.sol │ │ ├── RoninTrustedOrganizationDeploy.s.sol │ │ ├── RoninValidatorSetDeploy.s.sol │ │ ├── SlashIndicatorDeploy.s.sol │ │ ├── StakingDeploy.s.sol │ │ └── StakingVestingDeploy.s.sol │ └── interfaces │ │ └── ISharedArgument.sol ├── 20232811-prepare-hardfork │ ├── 20232811_ChangeGovernanceAdmin_AlreadyHardfork.s.sol │ ├── 20232811_ChangeGovernanceAdmin_Common.s.sol │ └── 20232811_ChangeGovernanceAdmin_NotYetHardfork.s.sol ├── 20233011-deploy-devnet │ ├── 20233011_DeployDevnet.s.sol │ ├── DevnetMigration.s.sol │ ├── contracts │ │ ├── FastFinalityTrackingDeploy.s.sol │ │ ├── MaintenanceDeploy.s.sol │ │ ├── ProfileDeploy.s.sol │ │ ├── RoninGovernanceAdminDeploy.s.sol │ │ ├── RoninTrustedOrganizationDeploy.s.sol │ │ ├── RoninValidatorSetDeploy.s.sol │ │ ├── SlashIndicatorDeploy.s.sol │ │ ├── StakingDeploy.s.sol │ │ └── StakingVestingDeploy.s.sol │ └── interfaces │ │ └── ISharedArgument.sol ├── 20240121-upgrade-testnet-release-v0.7.2 │ └── 20240121_Upgrade_ReleaseV0.7.2_Testnet.s.sol ├── 20240123-migrate-admin-staking │ └── 20240123_MigrateAdmin_Staking.s.sol ├── 20240219-upgrade-testnet-release-v0.7.2-patch │ └── 20240219_Upgrade_ReleaseV0.7.2_Patch_Testnet.s.sol ├── 20240220-miko-hardfork │ ├── 20240220_Base_Miko_Hardfork.s.sol │ ├── 20240220_Full_mainnet_Miko_Hardfork.s.sol │ ├── 20240220_Full_shadow_Miko_Hardfork.s.sol │ ├── 20240220_p1_Miko_before.s.sol │ ├── 20240220_p2A_mainnet_Miko_propose_proposal.s.sol │ ├── 20240220_p2B_shadow_Miko_propose_proposal.s.sol │ ├── 20240220_p2_Miko_build_proposal.s.sol │ ├── 20240220_p4_Miko_after.s.sol │ ├── 20240220_p5_Miko_stable.s.sol │ ├── 20240220_p6_postcheck.s.sol │ ├── 20240220_p9999_shadow_Miko_change_all_admins.s.sol │ ├── ArrayReplaceLib.sol │ ├── MikoConfig.s.sol │ └── README.md ├── 20240222-upgrade-testnet-release-v0.7.3 │ └── 2024022_UpgradeTestnet_v0_7_3.s.sol ├── 20240223-upgrade-testnet-release-v0.7.4 │ └── 20240223_UpgradeTestnet_v0_7_4.s.sol ├── 20240229-upgrade-testnet-release-v0.7.5 │ └── 20240223_UpgradeTestnet_v0_7_5.s.sol ├── 20240301-upgrade-testnet-release-v0.7.6 │ └── 20240301_UpgradeTestnet_v0_7_6.s.sol ├── 20242103-upgrade-testnet-release-v0.7.7 │ ├── 20242103_UpgradeTestnet_v0_7_7.s.sol │ └── 20242203_UpgradeMainnet_v0_7_7.s.sol ├── GeneralConfig.sol ├── PostChecker.sol ├── RoninMigration.s.sol ├── contracts │ ├── BridgeRewardDeploy.s.sol │ ├── BridgeSlashDeploy.s.sol │ ├── FastFinalityTrackingDeploy.s.sol │ ├── HardForkRoninGovernanceAdminDeploy.s.sol │ ├── NotifiedMigratorUpgrade.s.sol │ ├── ProfileDeploy.s.sol │ ├── RoninBridgeManagerDeploy.s.sol │ ├── RoninValidatorSetTimedMigratorUpgrade.s.sol │ └── TemporalRoninTrustedOrganizationDeploy.s.sol ├── data │ └── cid.json ├── deploy-dpos │ ├── DPoSMigration.s.sol │ ├── DeployDPoS.s.sol │ ├── contracts │ │ ├── FastFinalityTrackingDeploy.s.sol │ │ ├── MaintenanceDeploy.s.sol │ │ ├── ProfileDeploy.s.sol │ │ ├── RoninGovernanceAdminDeploy.s.sol │ │ ├── RoninTrustedOrganizationDeploy.s.sol │ │ ├── RoninValidatorSetDeploy.s.sol │ │ ├── SlashIndicatorDeploy.s.sol │ │ ├── StakingDeploy.s.sol │ │ └── StakingVestingDeploy.s.sol │ └── interfaces │ │ └── ISharedArgument.sol ├── interfaces │ └── ISharedArgument.sol ├── post-check │ ├── PostChecker_ApplyCandidate.sol │ ├── PostChecker_EmergencyExit.sol │ ├── PostChecker_GovernanceAdmin.s.sol │ ├── PostChecker_Helper.sol │ ├── PostChecker_Maintenance.sol │ ├── PostChecker_Renounce.sol │ ├── PostChecker_Slash.sol │ └── PostChecker_Staking.sol └── utils │ ├── Contract.sol │ └── Network.sol ├── src ├── configs │ ├── addresses.ts │ ├── bridge-manager.ts │ ├── config.ts │ └── gateway.ts ├── dashboard │ ├── dashboard-helper.ts │ ├── query-proxy-admin-mainchain.ts │ └── query-proxy-admin-ronin.ts ├── deploy │ ├── calculate-address │ │ ├── calculate-bridge.ts │ │ ├── calculate-dpos.ts │ │ └── helper.ts │ ├── logic │ │ ├── bridge-reward.ts │ │ ├── bridge-slash.ts │ │ ├── bridge-tracking.ts │ │ ├── fast-finality-tracking.ts │ │ ├── mainchain-gateway-pause-enforcer-logic.ts │ │ ├── mainchain-gateway-v3.ts │ │ ├── maintenance.ts │ │ ├── profile.ts │ │ ├── ronin-gateway-pause-enforcer-logic.ts │ │ ├── ronin-gateway-v3.ts │ │ ├── ronin-trusted-organization-temp.ts │ │ ├── ronin-trusted-organization.ts │ │ ├── slash-indicator.ts │ │ ├── staking-vesting.ts │ │ ├── staking.ts │ │ └── validator-set.ts │ ├── mainchain-bridge-manager.ts │ ├── migrations │ │ ├── ronin-trusted-organization-notified-migrator.ts │ │ ├── slash-indicator-notified-migrator.ts │ │ ├── staking-notified-migrator.ts │ │ └── timed-migrator-ronin-validator-set.ts │ ├── proxy │ │ ├── bridge-reward-proxy.ts │ │ ├── bridge-slash-proxy.ts │ │ ├── bridge-tracking-proxy.ts │ │ ├── fast-finality-tracking-proxy.ts │ │ ├── mainchain-gateway-pause-enforcer-proxy.ts │ │ ├── mainchain-gateway-v3-proxy.ts │ │ ├── mainchain-ronin-trusted-organization-proxy.ts │ │ ├── maintenance-proxy.ts │ │ ├── profile-proxy.ts │ │ ├── ronin-gateway-pause-enforcer-proxy.ts │ │ ├── ronin-gateway-v3-proxy.ts │ │ ├── ronin-trusted-organization-proxy.ts │ │ ├── slash-indicator-proxy.ts │ │ ├── staking-proxy.ts │ │ ├── staking-vesting-proxy.ts │ │ └── validator-set-proxy.ts │ ├── ronin-bridge-manager.ts │ ├── ronin-governance-admin.ts │ └── vault-forwarder.ts ├── script │ ├── bridge-admin-interface.ts │ ├── bridge.ts │ ├── governance-admin-interface.ts │ ├── proposal.ts │ ├── ronin-validator-set.ts │ ├── slash-indicator.ts │ └── verify-address.ts ├── tasks │ └── generate-storage-layout.ts ├── upgrades │ ├── 230406-update-slash-conditions.ts │ ├── 230411-add-GVs.ts │ ├── 230515-change-min-commission-rate-5-percent.ts │ ├── 230516-set-pause-enforcer-mainchain-gateway.ts │ ├── 230627-upgrade-v0.5.2-testnet.ts │ ├── 230628-upgrade-GA.ts │ ├── 230704-upgrade-v0.5.2-testnet-3.ts │ ├── 230704-vote-v0.5.2-testnet-3.ts │ ├── REP-002-REP-003--v0.6.4--mainnet │ │ ├── 20231013-proposal-on-mainchain.ts │ │ ├── 20231013-proposal-on-roninchain.ts │ │ ├── 20231016-reconfig-bridge-tracking-for-bridge-set.ts │ │ ├── 20231017-add-bridge-operators-both-chains.ts │ │ └── TODO │ ├── REP-002 │ │ ├── 230801-s1-upgrade-ronin-bridge-v0.6.0-testnet.ts │ │ ├── 230801-s1t2-upgrade-ronin-bridge-v0.6.0-testnet.ts │ │ ├── 230801-s2-upgrade-mainchain-bridge-v0.6.0-goerli.ts │ │ ├── 230801-s3-change-bridge-and-bridge-tracking-admin-v0.6.0-testnet.ts │ │ ├── 230801-s4-change-mainchain-bridge-admin-v0.6.0-goerli.ts │ │ ├── 230801-s5-conditional-upgrade-validator-set-testnet.ts │ │ ├── 230808-rollback-s1-bridge-tracking-v0.6.0-testnet.ts │ │ ├── 230808-rollback-s1t2-bridge-tracking-v0.6.0-testnet.ts │ │ ├── 230808-rollback-s1t3-bridge-tracking-v0.6.0-testnet.ts │ │ ├── 230808-vote-rollback-s1-bridge-tracking-v0.6.0-testnet.ts │ │ ├── 230808-vote-rollback-s1t3-bridge-tracking-v0.6.0-testnet.ts │ │ ├── 230814-hotfix-change-mainchain-bridge-manager.ts │ │ ├── 230814-s7-upgrade-missing-dpos-contract-v0.6.1-testnet.ts │ │ ├── 230814-vote-s7-upgrade-missing-dpos-contract-v0.6.1-testnet.ts │ │ ├── 230821-modified-s3-change-bridge-admin-v0.6.0-testnet.ts │ │ ├── 230824-set-min-threshold-testnet.ts │ │ └── 231103-upgrade-maintenance-contract.ts │ ├── REP-003 │ │ ├── 230907-upgrade-and-init-slash-indicator-and-staking-vesting-testnet.ts │ │ ├── 230907-upgrade-and-init-validator-set-contract-v0.6.2-testnet.ts │ │ ├── 230912-upgrade-and-init-slash-indicator.ts │ │ ├── 230925-upgrade-and-init-profile-contract.ts │ │ ├── 230929-upgrade-and-init-profile-contract.ts │ │ └── TODO.ts │ ├── REP-004--testnet │ │ └── 20231109-proposal-on-roninchain.ts │ └── upgradeUtils.ts └── utils.ts ├── storageLayout ├── profile-after.txt └── profile-before.txt ├── test ├── foundry │ ├── Base.t.sol │ ├── bridge │ │ └── unit │ │ │ ├── concrete │ │ │ ├── bridge-manager │ │ │ │ ├── BridgeManager.t.sol │ │ │ │ ├── add │ │ │ │ │ ├── add.t.sol │ │ │ │ │ └── add.tree │ │ │ │ ├── constructor.t.sol │ │ │ │ ├── remove │ │ │ │ │ ├── remove.t.sol │ │ │ │ │ └── remove.tree │ │ │ │ └── update │ │ │ │ │ ├── update.t.sol │ │ │ │ │ └── update.tree │ │ │ └── bridge-reward │ │ │ │ ├── BridgeReward.t.sol │ │ │ │ └── execSyncReward │ │ │ │ ├── execSyncReward.t.sol │ │ │ │ └── execSyncReward.tree │ │ │ └── fuzz │ │ │ ├── bridge-manager │ │ │ ├── BridgeManagerCRUD.t.sol │ │ │ ├── BridgeReward.t.sol │ │ │ └── BridgeSlash.t.sol │ │ │ └── utils │ │ │ └── BridgeManagerUtils.t.sol │ ├── finality │ │ └── Profile.t.sol │ ├── forking │ │ ├── REP-002 │ │ │ ├── DebugTestnetWrapupPeriod.t.sol │ │ │ ├── NewBridgeForkTest.t.sol │ │ │ └── UnattachBridgeForkTest.t.sol │ │ ├── REP-004 │ │ │ └── ChangeConsensusAddress.t.sol │ │ ├── RoninTest.t.sol │ │ ├── extensions │ │ │ └── TransparentUpgradeableProxyV3.sol │ │ └── utils │ │ │ └── Consts.sol │ ├── helpers │ │ ├── LibArrayUtils.t.sol │ │ └── Randomizer.t.sol │ ├── mocks │ │ ├── MockBridgeManager.sol │ │ ├── MockBridgeSlash.sol │ │ ├── MockBridgeTracking.sol │ │ ├── MockValidatorSet.sol │ │ └── README.md │ ├── overview.tree │ ├── ronin │ │ └── Maintenance.t.sol │ ├── types │ │ └── TUint256Slot.t.sol │ └── utils │ │ ├── Assertions.sol │ │ ├── Types.sol │ │ ├── Utils.sol │ │ └── version-control │ │ ├── ConditionalVersionControl.t.sol │ │ └── RoninValidatorSetTimedMigrator.t.sol └── hardhat_test │ ├── bridge │ ├── BridgeManager.test.ts │ ├── BridgeTracking.test.ts │ ├── GatewayPauseEnforcer.test.ts │ └── RoninGatewayV3.test.ts │ ├── forwarder │ └── VaultForwarder.test.ts │ ├── governance-admin │ └── GovernanceAdmin.test.ts │ ├── helpers │ ├── address-set-types │ │ ├── operator-tuple-type.ts │ │ ├── trusted-org-set-type.ts │ │ ├── validator-candidate-set-type.ts │ │ └── whitelisted-candidate-set-type.ts │ ├── candidate-manager.ts │ ├── encoder.ts │ ├── fixture.ts │ ├── governance-admin.ts │ ├── initializer.ts │ ├── ronin-validator-set.ts │ ├── slash.ts │ ├── staking-vesting.ts │ ├── staking.ts │ └── utils.ts │ ├── integration │ ├── ActionBridgeTracking.test.ts │ ├── ActionSlashValidators.test.ts │ ├── ActionSubmitReward.test.ts │ ├── ActionWrapUpEpoch.test.ts │ └── Configuration.test.ts │ ├── maintainance │ └── Maintenance.test.ts │ ├── precompile-usages │ ├── PrecompileUsageSortValidators.test.ts │ ├── PrecompileUsageValidateDoubleSign.test.ts │ └── PrecompileUsageValidateFastFinality.test.ts │ ├── profile │ ├── Profile-ChangeAdmin-DelegatorReward-IgnoreValidatorReward.test.ts │ ├── Profile-ChangeAdmin-DelegatorReward.test.ts │ ├── Profile-ChangeAdmin-ValidatorStake-IgnoreValidatorReward.test.ts │ ├── Profile-ChangeAdmin-ValidatorStake.test.ts │ ├── Profile-ChangeConsensus.test.ts │ └── Profile-Cooldown.test.ts │ ├── slash │ ├── CreditScore.test.ts │ └── SlashIndicator.test.ts │ ├── sorting │ └── QuickSort.test.ts │ ├── staking │ ├── RewardCalculation.test.ts │ └── Staking.test.ts │ ├── transfer │ └── PaymentFallback.test.ts │ └── validator │ ├── ArrangeValidators.test.ts │ ├── EmergencyExit.test.ts │ ├── RoninValidatorSet-Candidate.test.ts │ ├── RoninValidatorSet-CoinbaseExecution.test.ts │ └── RoninValidatorSet-FastFinality.test.ts ├── tsconfig.build.json ├── tsconfig.json ├── upload-sig.sh ├── verify.sh └── yarn.lock /.debug.env: -------------------------------------------------------------------------------- 1 | BLOCK=0 2 | FROM=0x69a063b5711C09E9139a3cCBE60FA6c22bAeB922 3 | TO=0x545edb750eB8769C868429BE9586F5857A768758 4 | VALUE=0x34f086f3b33b68400000 5 | CALLDATA=0x2baae12500000000000000000000000069a063b5711c09e9139a3ccbe60fa6c22baeb9220000000000000000000000004125217ce8868553e1f61bb030426efd330c2d6800000000000000000000000069a063b5711c09e9139a3ccbe60fa6c22baeb92200000000000000000000000000000000000000000000000000000000000003e8 6 | TX=0xed1a45c8bbd2fc90fda7e114a65df767eafc7db944088a29d92b093b7fb9d2f0 -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # Devnet configs 2 | DEVNET_PK=0x0000000000000000000000000000000000000000000000000000000000000000 3 | DEVNET_URL=http://localhost:8545 4 | 5 | # Testnet configs 6 | TESTNET_PK=0x0000000000000000000000000000000000000000000000000000000000000000 7 | TESTNET_URL=https://testnet.skymavis.one/rpc 8 | 9 | # Mainnet configs 10 | MAINNET_PK=0x0000000000000000000000000000000000000000000000000000000000000000 11 | MAINNET_URL=https://api.roninchain.com/rpc 12 | 13 | # Report gas 14 | REPORT_GAS=false -------------------------------------------------------------------------------- /.github/template/create-pull-request.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | 3 | PR to merge from [{{ .fromBranch }}](/ronin-chain/dpos-contract/tree/{{ .fromBranch }}) to [{{ .toBranch }}](/ronin-chain/dpos-contract/tree/{{ .toBranch }}). 4 | -------------------------------------------------------------------------------- /.github/workflows/create-PR-implement-to-feature.yml: -------------------------------------------------------------------------------- 1 | name: Create Pull Request From Implement To Feature 2 | on: 3 | push: 4 | branches: 5 | - "implement-feature/**" 6 | - "implement-feature/**/**" 7 | 8 | concurrency: 9 | group: ${{ github.workflow }}-${{ github.ref || github.run_id }} 10 | cancel-in-progress: true 11 | 12 | env: 13 | HEAD_BRANCH: ${{ github.head_ref || github.ref_name }} 14 | 15 | jobs: 16 | createPullRequest: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Set env 20 | run: | 21 | echo "FEATURE_NAME=$(echo ${HEAD_BRANCH} | cut -d'/' -f2)" >> $GITHUB_ENV 22 | echo "FEATURE_BRANCH=feature/$(echo ${HEAD_BRANCH} | cut -d'/' -f2)" >> $GITHUB_ENV 23 | echo "IMPLEMENT_NAME=$(echo ${HEAD_BRANCH} | cut -d'/' -f3)" >> $GITHUB_ENV 24 | 25 | - uses: actions/checkout@v3 26 | with: 27 | ref: ${{env.FEATURE_BRANCH}} 28 | 29 | - name: Reset promotion branch 30 | run: | 31 | git fetch origin ${HEAD_BRANCH}:${HEAD_BRANCH} 32 | git reset --hard ${HEAD_BRANCH} 33 | 34 | - name: Render template 35 | id: template 36 | uses: chuhlomin/render-template@v1.4 37 | with: 38 | template: .github/template/create-pull-request.md 39 | vars: | 40 | fromBranch: ${{env.HEAD_BRANCH}} 41 | toBranch: ${{ env.FEATURE_BRANCH }} 42 | 43 | - name: Create Pull Request 44 | uses: peter-evans/create-pull-request@v6.0.1 45 | with: 46 | branch: ${{ env.HEAD_BRANCH }} 47 | base: ${{env.FEATURE_BRANCH}} 48 | labels: automated PR 49 | title: "feat(${{env.FEATURE_NAME}}): implement `${{env.IMPLEMENT_NAME}}`" 50 | body: ${{ steps.template.outputs.result }} 51 | -------------------------------------------------------------------------------- /.github/workflows/create-PR-release-to-network.yml: -------------------------------------------------------------------------------- 1 | name: Create PR from release to network 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - release/* 7 | types: 8 | - closed 9 | 10 | permissions: 11 | contents: write 12 | pull-requests: write 13 | 14 | env: 15 | HEAD_BRANCH: ${{ github.head_ref || github.ref_name }} 16 | RELEASE_BRANCH: ${{ github.event.pull_request.base.ref}} 17 | 18 | jobs: 19 | merge-release-to-network: 20 | runs-on: ubuntu-latest 21 | if: ${{ (github.event.pull_request.merged == true) && (contains(github.head_ref, 'deploy') || contains(github.ref_name, 'deploy')) }} 22 | steps: 23 | - name: Set Env 24 | run: | 25 | echo "PR_BRANCH=merge/${HEAD_BRANCH}" >> $GITHUB_ENV 26 | echo "VERSION=$(echo -n ${{ env.HEAD_BRANCH }} | sed 's/.*deploy\///' | cut -d'-' -f1)" >> $GITHUB_ENV 27 | echo "NETWORK=$(echo -n ${{ env.HEAD_BRANCH }} | sed 's/.*deploy\/v[0-9\.]*-\(.*\)/\1/')" >> $GITHUB_ENV 28 | 29 | - name: Checkout code 30 | uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 31 | with: 32 | ref: ${{ env.NETWORK }} 33 | 34 | - name: Reset promotion branch 35 | run: | 36 | git fetch origin ${RELEASE_BRANCH}:${RELEASE_BRANCH} 37 | git reset --hard ${RELEASE_BRANCH} 38 | 39 | - name: Create Pull Request 40 | id: cpr 41 | uses: peter-evans/create-pull-request@v6.0.1 42 | with: 43 | labels: automated PR 44 | delete-branch: true 45 | title: "chore(`${{ env.NETWORK }}`): merge from `${{ env.HEAD_BRANCH}}`" 46 | body: ${{ steps.template.outputs.result }} 47 | branch: ${{env.PR_BRANCH}} 48 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - mainnet 7 | - testnet 8 | - "release/*" 9 | - "feature/*" 10 | - "features/*" 11 | pull_request: 12 | branches: 13 | - mainnet 14 | - testnet 15 | - "release/*" 16 | - "feature/*" 17 | - "features/*" 18 | 19 | env: 20 | FOUNDRY_PROFILE: ci 21 | 22 | jobs: 23 | check: 24 | strategy: 25 | fail-fast: true 26 | 27 | name: Foundry project 28 | runs-on: [self-hosted, dockerize] 29 | steps: 30 | - uses: actions/checkout@v3 31 | with: 32 | submodules: recursive 33 | 34 | - name: Install Foundry 35 | uses: foundry-rs/foundry-toolchain@v1 36 | with: 37 | version: nightly 38 | 39 | - name: Run Forge build 40 | run: | 41 | forge --version 42 | forge build 43 | id: build 44 | 45 | - name: Run Forge tests 46 | run: | 47 | forge test --no-match-path '*forking/*' -vvv 48 | id: test 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | artifacts/ 2 | cache/ 3 | node_modules/ 4 | src/types/ 5 | src/web3-types/ 6 | dist/ 7 | yarn-error.log 8 | .env 9 | .idea 10 | 11 | refs/ 12 | .vscode 13 | remix-compiler.config.js 14 | .npmrc 15 | .yarn 16 | .yarnrc.yml 17 | logs/storage_layout_table.log 18 | cache_foundry 19 | out 20 | .DS_Store 21 | 22 | dry-run/ 23 | script/data/* 24 | *.env -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/forge-std"] 2 | path = lib/forge-std 3 | url = https://github.com/foundry-rs/forge-std 4 | [submodule "lib/prb-test"] 5 | branch = release-v0 6 | path = lib/prb-test 7 | url = https://github.com/PaulRBerg/prb-test 8 | [submodule "lib/prb-math"] 9 | path = lib/prb-math 10 | url = https://github.com/PaulRBerg/prb-math 11 | branch = release-v4 12 | [submodule "lib/contract-libs"] 13 | path = lib/contract-libs 14 | url = https://github.com/axieinfinity/contract-libs 15 | [submodule "lib/openzeppelin-contracts"] 16 | path = lib/openzeppelin-contracts 17 | url = https://github.com/OpenZeppelin/openzeppelin-contracts 18 | [submodule "lib/foundry-deployment-kit"] 19 | path = lib/foundry-deployment-kit 20 | url = https://github.com/axieinfinity/foundry-deployment-kit 21 | branch = v0.2.0 22 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.husky/generate-layout.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | rm -rf logs/storage/* 4 | dirOutputs=$(ls out | grep '^[^.]*\.sol$') # assuming the out dir is at 'out' 5 | while IFS= read -r contractDir; do 6 | innerdirOutputs=$(ls out/$contractDir) 7 | 8 | while IFS= read -r jsonFile; do 9 | fileIn=out/$contractDir/$jsonFile 10 | fileOut=logs/storage/$contractDir:${jsonFile%.json}.log 11 | node .husky/storage-logger.js $fileIn $fileOut & 12 | done <<< "$innerdirOutputs" 13 | done <<< "$dirOutputs" 14 | 15 | # Wait for all background jobs to finish 16 | wait -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | forge build 5 | npx lint-staged 6 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | set -ex 5 | 6 | # Workaround: git stash no changes doesn't cause failure but git stash pop cause 7 | output=$(git stash) 8 | stashed=true 9 | if [[ $output == *"No local changes to save"* ]]; then 10 | stashed=false 11 | fi 12 | 13 | forge build --sizes 2>&1 | sed -n '/Contract/,$p' > logs/contract-code-sizes.log 14 | .husky/generate-layout.sh 15 | 16 | git add logs 17 | 18 | output=$(git status -s) 19 | word_count=$(echo "$output" | wc -w) 20 | if [ "$word_count" -gt 0 ]; then 21 | git commit -m "chore: storage layout" 22 | fi 23 | 24 | if $stashed; then 25 | git stash pop 26 | fi -------------------------------------------------------------------------------- /.husky/storage-logger.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const fileIn = process.argv[2]; 3 | const fileOut = process.argv[3]; 4 | 5 | if (!fileIn) { 6 | console.error('Invalid input'); 7 | } 8 | 9 | fs.readFile(fileIn, 'utf8', (err, data) => { 10 | if (err) { 11 | console.error('Error reading file:', err); 12 | return; 13 | } 14 | 15 | try { 16 | const jsonData = JSON.parse(data); 17 | if (typeof jsonData.storageLayout == 'undefined' || jsonData.ast.absolutePath == 'undefined') { 18 | return; 19 | } 20 | 21 | if (jsonData.storageLayout.storage.length == 0) { 22 | return; 23 | } 24 | 25 | // Skip generating storage layout for files locate in the directory "src" 26 | if (!jsonData.ast.absolutePath.startsWith('src')) { 27 | return; 28 | } 29 | 30 | const outputData = jsonData.storageLayout.storage 31 | .map(({ contract, label, offset, slot, type: typeId }) => { 32 | const typeObj = jsonData.storageLayout.types[typeId]; 33 | const typeLabel = typeObj.label; 34 | const numberOfBytes = typeObj.numberOfBytes; 35 | return `${contract}:${label} (storage_slot: ${slot}) (offset: ${offset}) (type: ${typeLabel}) (numberOfBytes: ${numberOfBytes})`; 36 | }) 37 | .join('\n'); 38 | if (!fileOut) { 39 | console.log(outputData); 40 | } else { 41 | fs.writeFile(fileOut, outputData, 'utf-8', err => { 42 | if (err) { 43 | console.error('Error writing file:', err); 44 | return; 45 | } 46 | }); 47 | } 48 | } catch (err) { 49 | console.error('Error parsing JSON:', err); 50 | } 51 | }); -------------------------------------------------------------------------------- /.npmrc.example: -------------------------------------------------------------------------------- 1 | //npm.pkg.github.com/:_authToken={YOUR_TOKEN} 2 | @axieinfinity:registry=https://npm.pkg.github.com/ 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "bracketSpacing": true, 6 | "explicitTypes": "preserve", 7 | "overrides": [ 8 | { 9 | "files": "*.sol", 10 | "options": { 11 | "singleQuote": false 12 | } 13 | }, 14 | { 15 | "files": "*.{js,ts}", 16 | "options": { 17 | "printWidth": 200, 18 | "singleQuote": true 19 | } 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /broadcast.sh: -------------------------------------------------------------------------------- 1 | source lib/foundry-deployment-kit/broadcast.sh -------------------------------------------------------------------------------- /contracts/extensions/TransparentUpgradeableProxyV2.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; 5 | 6 | contract TransparentUpgradeableProxyV2 is TransparentUpgradeableProxy { 7 | constructor( 8 | address _logic, 9 | address admin_, 10 | bytes memory _data 11 | ) payable TransparentUpgradeableProxy(_logic, admin_, _data) { } 12 | 13 | /** 14 | * @dev Calls a function from the current implementation as specified by `_data`, which should be an encoded function call. 15 | * 16 | * Requirements: 17 | * - Only the admin can call this function. 18 | * 19 | * Note: The proxy admin is not allowed to interact with the proxy logic through the fallback function to avoid 20 | * triggering some unexpected logic. This is to allow the administrator to explicitly call the proxy, please consider 21 | * reviewing the encoded data `_data` and the method which is called before using this. 22 | * 23 | */ 24 | function functionDelegateCall(bytes memory _data) public payable ifAdmin { 25 | address _addr = _implementation(); 26 | assembly { 27 | let _result := delegatecall(gas(), _addr, add(_data, 32), mload(_data), 0, 0) 28 | returndatacopy(0, 0, returndatasize()) 29 | switch _result 30 | case 0 { revert(0, returndatasize()) } 31 | default { return(0, returndatasize()) } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /contracts/extensions/bridge-operator-governance/BridgeTrackingHelper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | abstract contract BridgeTrackingHelper { 5 | /// @dev Event emited when the bridge tracking contract tracks the invalid data, cause malform in sharing bridge reward. 6 | event BridgeTrackingIncorrectlyResponded(); 7 | 8 | /** 9 | * @dev Internal function to validate the bridge tracking response for a given set of ballots. 10 | * @param totalBallot The total number of ballots available for the tracking response. 11 | * @param totalVote The total number of votes recorded in the tracking response. 12 | * @param ballots An array containing the individual ballot counts in the tracking response. 13 | * @return valid A boolean indicating whether the bridge tracking response is valid or not. 14 | * @notice The function checks if each individual ballot count is not greater than the total votes recorded. 15 | * @notice It also verifies that the sum of all individual ballot counts does not exceed the total available ballots. 16 | */ 17 | function _isValidBridgeTrackingResponse( 18 | uint256 totalBallot, 19 | uint256 totalVote, 20 | uint256[] memory ballots 21 | ) internal pure returns (bool valid) { 22 | valid = true; 23 | uint256 sumBallot; 24 | uint256 length = ballots.length; 25 | 26 | unchecked { 27 | for (uint256 i; i < length; ++i) { 28 | if (ballots[i] > totalVote) { 29 | valid = false; 30 | break; 31 | } 32 | 33 | sumBallot += ballots[i]; 34 | } 35 | } 36 | 37 | valid = valid && (sumBallot <= totalBallot); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /contracts/extensions/collections/HasProxyAdmin.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/utils/StorageSlot.sol"; 5 | import "../../utils/CommonErrors.sol"; 6 | 7 | abstract contract HasProxyAdmin { 8 | // bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); 9 | bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; 10 | 11 | modifier onlyAdmin() { 12 | _requireAdmin(); 13 | _; 14 | } 15 | 16 | /** 17 | * @dev Returns proxy admin. 18 | */ 19 | function _getAdmin() internal view virtual returns (address) { 20 | return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; 21 | } 22 | 23 | function _requireAdmin() internal view { 24 | if (msg.sender != _getAdmin()) revert ErrUnauthorized(msg.sig, RoleAccess.ADMIN); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /contracts/extensions/consumers/GlobalConfigConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | abstract contract GlobalConfigConsumer { 6 | /// @dev The addition amount of gas sending along in external calls. Total gas stipend is added with default 2300 gas. 7 | uint256 public constant DEFAULT_ADDITION_GAS = 1200; 8 | /// @dev The length of a period in second. 9 | uint256 public constant PERIOD_DURATION = 1 days; 10 | } 11 | -------------------------------------------------------------------------------- /contracts/extensions/consumers/PercentageConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | abstract contract PercentageConsumer { 5 | uint256 internal constant _MAX_PERCENTAGE = 100_00; 6 | } 7 | -------------------------------------------------------------------------------- /contracts/extensions/sequential-governance/governance-relay/GlobalGovernanceRelay.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../GlobalCoreGovernance.sol"; 5 | import "./CommonGovernanceRelay.sol"; 6 | 7 | abstract contract GlobalGovernanceRelay is CommonGovernanceRelay, GlobalCoreGovernance { 8 | using GlobalProposal for GlobalProposal.GlobalProposalDetail; 9 | 10 | /** 11 | * @dev Returns whether the voter `_voter` casted vote for the proposal. 12 | */ 13 | function globalProposalRelayed(uint256 _round) external view returns (bool) { 14 | return vote[0][_round].status != VoteStatus.Pending; 15 | } 16 | 17 | /** 18 | * @dev Relays voted global proposal. 19 | * 20 | * Requirements: 21 | * - The relay proposal is finalized. 22 | * 23 | */ 24 | function _relayGlobalProposal( 25 | GlobalProposal.GlobalProposalDetail calldata globalProposal, 26 | Ballot.VoteType[] calldata supports_, 27 | Signature[] calldata signatures, 28 | bytes32 domainSeparator, 29 | address creator 30 | ) internal { 31 | Proposal.ProposalDetail memory _proposal = _proposeGlobalStruct(globalProposal, creator); 32 | bytes32 globalProposalHash = globalProposal.hash(); 33 | _relayVotesBySignatures( 34 | _proposal, 35 | supports_, 36 | signatures, 37 | ECDSA.toTypedDataHash(domainSeparator, Ballot.hash(globalProposalHash, Ballot.VoteType.For)), 38 | ECDSA.toTypedDataHash(domainSeparator, Ballot.hash(globalProposalHash, Ballot.VoteType.Against)) 39 | ); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /contracts/extensions/sequential-governance/governance-relay/GovernanceRelay.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../CoreGovernance.sol"; 5 | import "./CommonGovernanceRelay.sol"; 6 | 7 | abstract contract GovernanceRelay is CoreGovernance, CommonGovernanceRelay { 8 | using Proposal for Proposal.ProposalDetail; 9 | using GlobalProposal for GlobalProposal.GlobalProposalDetail; 10 | 11 | /** 12 | * @dev Relays voted proposal. 13 | * 14 | * Requirements: 15 | * - The relay proposal is finalized. 16 | * 17 | */ 18 | function _relayProposal( 19 | Proposal.ProposalDetail calldata _proposal, 20 | Ballot.VoteType[] calldata _supports, 21 | Signature[] calldata _signatures, 22 | bytes32 _domainSeparator, 23 | address _creator 24 | ) internal { 25 | _proposeProposalStruct(_proposal, _creator); 26 | bytes32 _proposalHash = _proposal.hash(); 27 | _relayVotesBySignatures( 28 | _proposal, 29 | _supports, 30 | _signatures, 31 | ECDSA.toTypedDataHash(_domainSeparator, Ballot.hash(_proposalHash, Ballot.VoteType.For)), 32 | ECDSA.toTypedDataHash(_domainSeparator, Ballot.hash(_proposalHash, Ballot.VoteType.Against)) 33 | ); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /contracts/interfaces/IBridge.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IBridge { 5 | /** 6 | * @dev Replaces the old bridge operator list by the new one. 7 | * 8 | * Requirements: 9 | * - The method caller is admin. 10 | * 11 | * Emitted the event `BridgeOperatorsReplaced`. 12 | * 13 | */ 14 | function replaceBridgeOperators(address[] calldata) external; 15 | 16 | /** 17 | * @dev Returns the bridge operator list. 18 | */ 19 | function getBridgeOperators() external view returns (address[] memory); 20 | } 21 | -------------------------------------------------------------------------------- /contracts/interfaces/IBridgeAdminProposal.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { BridgeOperatorsBallot } from "../libraries/BridgeOperatorsBallot.sol"; 5 | 6 | interface IBridgeAdminProposal { 7 | /// @dev Emitted when the bridge operators are approved. 8 | event BridgeOperatorsApproved(uint256 period, uint256 epoch, address[] operators); 9 | 10 | /** 11 | * @dev Returns the last voted block of the bridge voter. 12 | */ 13 | function lastVotedBlock(address bridgeVoter) external view returns (uint256); 14 | 15 | /** 16 | * @dev Returns the synced bridge operator set info. 17 | */ 18 | function lastSyncedBridgeOperatorSetInfo() 19 | external 20 | view 21 | returns (BridgeOperatorsBallot.BridgeOperatorSet memory bridgeOperatorSetInfo); 22 | } 23 | -------------------------------------------------------------------------------- /contracts/interfaces/IERC20Mintable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.2; 3 | 4 | interface IERC20Mintable { 5 | function mint(address _to, uint256 _value) external returns (bool _success); 6 | } 7 | -------------------------------------------------------------------------------- /contracts/interfaces/IERC721Mintable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IERC721Mintable { 5 | function mint(address _to, uint256 _tokenId) external returns (bool); 6 | } 7 | -------------------------------------------------------------------------------- /contracts/interfaces/IFastFinalityTracking.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import { TConsensus } from "../udvts/Types.sol"; 6 | 7 | interface IFastFinalityTracking { 8 | /** 9 | * @dev Submit list of `voters` who vote for fast finality in the current block. 10 | * 11 | * Requirements: 12 | * - Only called once per block 13 | * - Only coinbase can call this method 14 | */ 15 | function recordFinality(TConsensus[] calldata voters) external; 16 | 17 | /** 18 | * @dev Returns vote count of `addrs` in the `period`. 19 | */ 20 | function getManyFinalityVoteCounts( 21 | uint256 period, 22 | TConsensus[] calldata addrs 23 | ) external view returns (uint256[] memory voteCounts); 24 | 25 | /** 26 | * @dev Returns vote count of `cids` in the `period`. 27 | */ 28 | function getManyFinalityVoteCountsById( 29 | uint256 period, 30 | address[] calldata cids 31 | ) external view returns (uint256[] memory voteCounts); 32 | } 33 | -------------------------------------------------------------------------------- /contracts/interfaces/IPauseTarget.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IPauseTarget { 5 | function pause() external; 6 | 7 | function unpause() external; 8 | 9 | function paused() external returns (bool); 10 | } 11 | -------------------------------------------------------------------------------- /contracts/interfaces/IQuorum.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IQuorum { 5 | /// @dev Emitted when the threshold is updated 6 | event ThresholdUpdated( 7 | uint256 indexed nonce, 8 | uint256 indexed numerator, 9 | uint256 indexed denominator, 10 | uint256 previousNumerator, 11 | uint256 previousDenominator 12 | ); 13 | 14 | /** 15 | * @dev Returns the threshold. 16 | */ 17 | function getThreshold() external view returns (uint256 _num, uint256 _denom); 18 | 19 | /** 20 | * @dev Checks whether the `_voteWeight` passes the threshold. 21 | */ 22 | function checkThreshold(uint256 _voteWeight) external view returns (bool); 23 | 24 | /** 25 | * @dev Returns the minimum vote weight to pass the threshold. 26 | */ 27 | function minimumVoteWeight() external view returns (uint256); 28 | 29 | /** 30 | * @dev Sets the threshold. 31 | * 32 | * Requirements: 33 | * - The method caller is admin. 34 | * 35 | * Emits the `ThresholdUpdated` event. 36 | * 37 | */ 38 | function setThreshold( 39 | uint256 _numerator, 40 | uint256 _denominator 41 | ) external returns (uint256 _previousNum, uint256 _previousDenom); 42 | } 43 | -------------------------------------------------------------------------------- /contracts/interfaces/IRoninGovernanceAdmin.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../utils/CommonErrors.sol"; 5 | 6 | interface IRoninGovernanceAdmin { 7 | /// @dev Emitted when an emergency exit poll is created. 8 | event EmergencyExitPollCreated( 9 | bytes32 voteHash, address validatorId, address recipientAfterUnlockedFund, uint256 requestedAt, uint256 expiredAt 10 | ); 11 | /// @dev Emitted when an emergency exit poll is approved. 12 | event EmergencyExitPollApproved(bytes32 voteHash); 13 | /// @dev Emitted when an emergency exit poll is expired. 14 | event EmergencyExitPollExpired(bytes32 voteHash); 15 | /// @dev Emitted when an emergency exit poll is voted. 16 | event EmergencyExitPollVoted(bytes32 indexed voteHash, address indexed voter); 17 | 18 | /** 19 | * @dev Create a vote to agree that an emergency exit is valid and should return the locked funds back.a 20 | * 21 | * Requirements: 22 | * - The method caller is validator contract. 23 | * 24 | */ 25 | function createEmergencyExitPoll( 26 | address validatorId, 27 | address recipientAfterUnlockedFund, 28 | uint256 requestedAt, 29 | uint256 expiredAt 30 | ) external; 31 | } 32 | -------------------------------------------------------------------------------- /contracts/interfaces/IWETH.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IWETH { 5 | function deposit() external payable; 6 | 7 | function withdraw(uint256 _wad) external; 8 | 9 | function balanceOf(address) external view returns (uint256); 10 | } 11 | -------------------------------------------------------------------------------- /contracts/interfaces/bridge/IBridgeManagerCallback.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; 5 | 6 | /** 7 | * @title IBridgeManagerCallback 8 | * @dev Interface for the callback functions to be implemented by the Bridge Manager contract. 9 | */ 10 | interface IBridgeManagerCallback is IERC165 { 11 | /** 12 | * @dev Handles the event when bridge operators are added. 13 | * @param bridgeOperators The addresses of the bridge operators. 14 | * @param addeds The corresponding boolean values indicating whether the operators were added or not. 15 | * @return selector The selector of the function being called. 16 | */ 17 | function onBridgeOperatorsAdded( 18 | address[] memory bridgeOperators, 19 | bool[] memory addeds 20 | ) external returns (bytes4 selector); 21 | 22 | /** 23 | * @dev Handles the event when bridge operators are removed. 24 | * @param bridgeOperators The addresses of the bridge operators. 25 | * @param removeds The corresponding boolean values indicating whether the operators were removed or not. 26 | * @return selector The selector of the function being called. 27 | */ 28 | function onBridgeOperatorsRemoved( 29 | address[] memory bridgeOperators, 30 | bool[] memory removeds 31 | ) external returns (bytes4 selector); 32 | 33 | /** 34 | * @dev Handles the event when a bridge operator is updated. 35 | * @param currentBridgeOperator The address of the current bridge operator. 36 | * @param newbridgeOperator The new address of the bridge operator. 37 | * @return selector The selector of the function being called. 38 | */ 39 | function onBridgeOperatorUpdated( 40 | address currentBridgeOperator, 41 | address newbridgeOperator 42 | ) external returns (bytes4 selector); 43 | } 44 | -------------------------------------------------------------------------------- /contracts/interfaces/bridge/IBridgeManagerCallbackRegister.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IBridgeManagerCallbackRegister { 5 | /** 6 | * @dev Emitted when the contract notifies multiple registers with statuses and return data. 7 | */ 8 | event Notified(bytes callData, address[] registers, bool[] statuses, bytes[] returnDatas); 9 | 10 | /** 11 | * @dev Retrieves the addresses of registered callbacks. 12 | * @return registers An array containing the addresses of registered callbacks. 13 | */ 14 | function getCallbackRegisters() external view returns (address[] memory registers); 15 | 16 | /** 17 | * @dev Registers multiple callbacks with the bridge. 18 | * @param registers The array of callback addresses to register. 19 | * @return registereds An array indicating the success status of each registration. 20 | */ 21 | function registerCallbacks(address[] calldata registers) external returns (bool[] memory registereds); 22 | 23 | /** 24 | * @dev Unregisters multiple callbacks from the bridge. 25 | * @param registers The array of callback addresses to unregister. 26 | * @return unregistereds An array indicating the success status of each unregistration. 27 | */ 28 | function unregisterCallbacks(address[] calldata registers) external returns (bool[] memory unregistereds); 29 | } 30 | -------------------------------------------------------------------------------- /contracts/interfaces/bridge/events/IBridgeRewardEvents.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IBridgeRewardEvents { 5 | /** 6 | * @dev Reward-related information for a bridge operator. 7 | * @param claimed The amount of rewards claimed by the bridge operator. 8 | * @param slashed The amount of rewards that have been slashed from the bridge operator. 9 | */ 10 | struct BridgeRewardInfo { 11 | uint256 claimed; 12 | uint256 slashed; 13 | } 14 | 15 | /** 16 | * @dev Emitted when RON are safely received as rewards in the contract. 17 | * @param from The address of the sender who transferred RON tokens as rewards. 18 | * @param balanceBefore The balance of the contract before receiving the RON tokens. 19 | * @param amount The amount of RON received. 20 | */ 21 | event SafeReceived(address indexed from, uint256 balanceBefore, uint256 amount); 22 | /// @dev Event emitted when the reward per period config is updated. 23 | event UpdatedRewardPerPeriod(uint256 newRewardPerPeriod); 24 | /// @dev Event emitted when the reward of the `operator` is scattered with `amount`. 25 | event BridgeRewardScattered(uint256 indexed period, address operator, uint256 amount); 26 | /// @dev Event emitted when the reward of the `operator` is slashed with `amount`. 27 | event BridgeRewardSlashed(uint256 indexed period, address operator, uint256 amount); 28 | /// @dev Event emitted when the reward of the `operator` is scattered with `amount` but failed to transfer. 29 | event BridgeRewardScatterFailed(uint256 indexed period, address operator, uint256 amount); 30 | /// @dev Event emitted when the requesting period to sync is too far. 31 | event BridgeRewardSyncTooFarPeriod(uint256 requestingPeriod, uint256 latestPeriod); 32 | } 33 | -------------------------------------------------------------------------------- /contracts/interfaces/bridge/events/IBridgeSlashEvents.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IBridgeSlashEvents { 5 | /** 6 | * @dev Enumeration representing the slashing tiers for bridge operators. 7 | */ 8 | enum Tier { 9 | Tier0, 10 | Tier1, 11 | Tier2 12 | } 13 | 14 | /** 15 | * @dev Struct representing the status of a bridge operator. 16 | */ 17 | struct BridgeSlashInfo { 18 | uint128 slashUntilPeriod; 19 | uint128 newlyAddedAtPeriod; 20 | } 21 | 22 | /** 23 | * @dev Event emitted when a bridge operator is slashed. 24 | * @param tier The slash tier of the operator. 25 | * @param bridgeOperator The address of the slashed bridge operator. 26 | * @param period The period in which the operator is slashed. 27 | * @param slashUntilPeriod The period until which the operator is penalized. 28 | */ 29 | event Slashed(Tier indexed tier, address indexed bridgeOperator, uint256 indexed period, uint256 slashUntilPeriod); 30 | 31 | /** 32 | * @dev Emitted when a removal request is made for a bridge operator. 33 | * @param period The period for which the removal request is made. 34 | * @param bridgeOperator The address of the bridge operator being requested for removal. 35 | */ 36 | event RemovalRequested(uint256 indexed period, address indexed bridgeOperator); 37 | } 38 | -------------------------------------------------------------------------------- /contracts/interfaces/collections/IHasContracts.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import { ContractType } from "../../utils/ContractType.sol"; 6 | 7 | interface IHasContracts { 8 | /// @dev Error of invalid role. 9 | error ErrContractTypeNotFound(ContractType contractType); 10 | 11 | /// @dev Emitted when a contract is updated. 12 | event ContractUpdated(ContractType indexed contractType, address indexed addr); 13 | 14 | /** 15 | * @dev Returns the address of a contract with a specific role. 16 | * Throws an error if no contract is set for the specified role. 17 | * 18 | * @param contractType The role of the contract to retrieve. 19 | * @return contract_ The address of the contract with the specified role. 20 | */ 21 | function getContract(ContractType contractType) external view returns (address contract_); 22 | 23 | /** 24 | * @dev Sets the address of a contract with a specific role. 25 | * Emits the event {ContractUpdated}. 26 | * @param contractType The role of the contract to set. 27 | * @param addr The address of the contract to set. 28 | */ 29 | function setContract(ContractType contractType, address addr) external; 30 | } 31 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/ChainTypeConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface ChainTypeConsumer { 5 | enum ChainType { 6 | RoninChain, 7 | Mainchain 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/MappedTokenConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../../libraries/Token.sol"; 5 | 6 | interface MappedTokenConsumer { 7 | struct MappedToken { 8 | Token.Standard erc; 9 | address tokenAddr; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/PeriodWrapperConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface PeriodWrapperConsumer { 5 | struct PeriodWrapper { 6 | // Inner value. 7 | uint256 inner; 8 | // Last period number that the info updated. 9 | uint256 lastPeriod; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/SignatureConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface SignatureConsumer { 5 | struct Signature { 6 | uint8 v; 7 | bytes32 r; 8 | bytes32 s; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/VoteStatusConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface VoteStatusConsumer { 5 | enum VoteStatus { 6 | Pending, 7 | Approved, 8 | Executed, 9 | Rejected, 10 | Expired 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /contracts/interfaces/consumers/WeightedAddressConsumer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface WeightedAddressConsumer { 5 | struct WeightedAddress { 6 | address addr; 7 | uint256 weight; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /contracts/interfaces/slash-indicator/IBaseSlash.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | interface IBaseSlash { 6 | enum SlashType { 7 | UNKNOWN, 8 | UNAVAILABILITY_TIER_1, 9 | UNAVAILABILITY_TIER_2, 10 | DOUBLE_SIGNING, 11 | BRIDGE_VOTING, 12 | BRIDGE_OPERATOR_MISSING_VOTE_TIER_1, 13 | BRIDGE_OPERATOR_MISSING_VOTE_TIER_2, 14 | UNAVAILABILITY_TIER_3, 15 | FAST_FINALITY 16 | } 17 | 18 | /// @dev Error thrown when evidence has already been submitted. 19 | error ErrEvidenceAlreadySubmitted(); 20 | 21 | /// @dev Error thrown when public key in evidence is not registered. 22 | error ErrUnregisteredPublicKey(); 23 | 24 | /// @dev Emitted when the validator is slashed. 25 | event Slashed(address indexed cid, SlashType slashType, uint256 period); 26 | } 27 | -------------------------------------------------------------------------------- /contracts/interfaces/slash-indicator/ISlashIndicator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./ISlashDoubleSign.sol"; 6 | import "./ISlashUnavailability.sol"; 7 | import "./ICreditScore.sol"; 8 | 9 | interface ISlashIndicator is ISlashDoubleSign, ISlashUnavailability, ICreditScore { } 10 | -------------------------------------------------------------------------------- /contracts/interfaces/staking/IStaking.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./IBaseStaking.sol"; 6 | import "./IStakingCallback.sol"; 7 | import "./ICandidateStaking.sol"; 8 | import "./IDelegatorStaking.sol"; 9 | 10 | interface IStaking is IRewardPool, IBaseStaking, ICandidateStaking, IDelegatorStaking, IStakingCallback { 11 | /// @dev Event emitted when the `wasAdmin` is finished to migrate. 12 | event MigrateWasAdminFinished(); 13 | /// @dev Event emitted when the `migrateWasAdmin` method is disabled. 14 | event MigrateWasAdminDisabled(); 15 | 16 | /// @dev Error indicating that the REP-4 migration is already done. 17 | error ErrMigrateWasAdminAlreadyDone(); 18 | 19 | /** 20 | * @dev Records the amount of rewards `_rewards` for the pools `_consensusAddrs`. 21 | * 22 | * Requirements: 23 | * - The method caller must be validator contract. 24 | * 25 | * Emits the event `PoolsUpdated` once the contract recorded the rewards successfully. 26 | * Emits the event `PoolsUpdateFailed` once the input array lengths are not equal. 27 | * Emits the event `PoolsUpdateConflicted` when there are some pools which already updated in the period. 28 | * 29 | * Note: This method should be called once at the period ending. 30 | * 31 | */ 32 | function execRecordRewards(address[] calldata poolIds, uint256[] calldata rewards, uint256 period) external payable; 33 | 34 | /** 35 | * @dev Deducts from staking amount of the validator `_consensusAddr` for `_amount`. 36 | * 37 | * Requirements: 38 | * - The method caller must be validator contract. 39 | * 40 | * Emits the event `Unstaked`. 41 | * 42 | */ 43 | function execDeductStakingAmount(address poolId, uint256 amount) external returns (uint256 actualDeductingAmount); 44 | } 45 | -------------------------------------------------------------------------------- /contracts/interfaces/staking/IStakingCallback.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import { TPoolId } from "../../udvts/Types.sol"; 6 | 7 | interface IStakingCallback { 8 | /** 9 | * @dev Requirements: 10 | * - Only Profile contract can call this method. 11 | */ 12 | function execChangeAdminAddr(address poolId, address currAdminAddr, address newAdminAddr) external; 13 | } 14 | -------------------------------------------------------------------------------- /contracts/interfaces/validator/IRoninValidatorSet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./ICandidateManager.sol"; 6 | import "./ICandidateManagerCallback.sol"; 7 | import "./info-fragments/ICommonInfo.sol"; 8 | import "./ICoinbaseExecution.sol"; 9 | import "./ISlashingExecution.sol"; 10 | import "./IEmergencyExit.sol"; 11 | 12 | interface IRoninValidatorSet is 13 | ICandidateManagerCallback, 14 | ICandidateManager, 15 | ICommonInfo, 16 | ISlashingExecution, 17 | ICoinbaseExecution, 18 | IEmergencyExit 19 | { } 20 | -------------------------------------------------------------------------------- /contracts/interfaces/validator/ISlashingExecution.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | interface ISlashingExecution { 6 | /// @dev Emitted when the validator is punished. 7 | event ValidatorPunished( 8 | address indexed cid, 9 | uint256 indexed period, 10 | uint256 jailedUntil, 11 | uint256 deductedStakingAmount, 12 | bool blockProducerRewardDeprecated, 13 | bool bridgeOperatorRewardDeprecated 14 | ); 15 | /// @dev Emitted when the validator get out of jail by bailout. 16 | event ValidatorUnjailed(address indexed cid, uint256 period); 17 | 18 | /// @dev Error of cannot bailout due to high tier slash. 19 | error ErrCannotBailout(address validator); 20 | 21 | /** 22 | * @dev Finalize the slash request from slash indicator contract. 23 | * 24 | * Requirements: 25 | * - The method caller is slash indicator contract. 26 | * 27 | * Emits the event `ValidatorPunished`. 28 | * 29 | */ 30 | function execSlash(address cid, uint256 newJailedUntil, uint256 slashAmount, bool cannotBailout) external; 31 | 32 | /** 33 | * @dev Finalize the bailout request from slash indicator contract. 34 | * 35 | * Requirements: 36 | * - The method caller is slash indicator contract. 37 | * 38 | * Emits the event `ValidatorUnjailed`. 39 | * 40 | */ 41 | function execBailOut(address cid, uint256 period) external; 42 | } 43 | -------------------------------------------------------------------------------- /contracts/interfaces/validator/info-fragments/ICommonInfo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./IJailingInfo.sol"; 6 | import "./ITimingInfo.sol"; 7 | import "./IValidatorInfoV2.sol"; 8 | 9 | interface ICommonInfo is ITimingInfo, IJailingInfo, IValidatorInfoV2 { 10 | struct EmergencyExitInfo { 11 | uint256 lockedAmount; 12 | // The timestamp that this locked amount will be recycled to staking vesting contract 13 | uint256 recyclingAt; 14 | } 15 | 16 | /// @dev Emitted when the deprecated reward is withdrawn. 17 | event DeprecatedRewardRecycled(address indexed recipientAddr, uint256 amount); 18 | /// @dev Emitted when the deprecated reward withdrawal is failed 19 | event DeprecatedRewardRecycleFailed(address indexed recipientAddr, uint256 amount, uint256 balance); 20 | 21 | /// @dev Error thrown when receives RON from neither staking vesting contract nor staking contract 22 | error ErrUnauthorizedReceiveRON(); 23 | /// @dev Error thrown when queries for a non existent info. 24 | error NonExistentRecyclingInfo(); 25 | 26 | /** 27 | * @dev Returns the total deprecated reward, which includes reward that is not sent for slashed validators and unsastified bridge operators 28 | */ 29 | function totalDeprecatedReward() external view returns (uint256); 30 | 31 | /** 32 | * @dev Returns the emergency exit request. 33 | */ 34 | function getEmergencyExitInfo(TConsensus consensus) external view returns (EmergencyExitInfo memory); 35 | } 36 | -------------------------------------------------------------------------------- /contracts/interfaces/validator/info-fragments/ITimingInfo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | interface ITimingInfo { 6 | /** 7 | * @dev Returns the block that validator set was updated. 8 | */ 9 | function getLastUpdatedBlock() external view returns (uint256); 10 | 11 | /** 12 | * @dev Returns the number of blocks in a epoch. 13 | */ 14 | function numberOfBlocksInEpoch() external view returns (uint256 _numberOfBlocks); 15 | 16 | /** 17 | * @dev Returns the epoch index from the block number. 18 | */ 19 | function epochOf(uint256 _block) external view returns (uint256); 20 | 21 | /** 22 | * @dev Returns whether the epoch ending is at the block number `_block`. 23 | */ 24 | function epochEndingAt(uint256 _block) external view returns (bool); 25 | 26 | /** 27 | * @dev Tries to get the period index from the epoch number. 28 | */ 29 | function tryGetPeriodOfEpoch(uint256 _epoch) external view returns (bool _filled, uint256 _periodNumber); 30 | 31 | /** 32 | * @dev Returns whether the period ending at the current block number. 33 | */ 34 | function isPeriodEnding() external view returns (bool); 35 | 36 | /** 37 | * @dev Returns the period index from the current block. 38 | */ 39 | function currentPeriod() external view returns (uint256); 40 | 41 | /** 42 | * @dev Returns the block number that the current period starts at. 43 | */ 44 | function currentPeriodStartAtBlock() external view returns (uint256); 45 | } 46 | -------------------------------------------------------------------------------- /contracts/interfaces/version-control/IConditionalImplementControl.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface IConditionalImplementControl { 5 | /// @dev Error when contract which delegate to this contract is not compatible with ERC1967 6 | error ErrDelegateFromUnknownOrigin(address addr); 7 | 8 | /** 9 | * @dev Emitted when the implementation is upgraded. 10 | */ 11 | event Upgraded(address indexed implementation); 12 | 13 | /** 14 | * @dev Executes the selfUpgrade function, upgrading to the new contract implementation. 15 | */ 16 | function selfUpgrade() external; 17 | 18 | /** 19 | * @dev Set additional calldata to call when upgrading via `selfUpgrade`. 20 | */ 21 | function setCallDatas(bytes[] calldata args) external; 22 | } 23 | -------------------------------------------------------------------------------- /contracts/libraries/Ballot.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; 5 | 6 | library Ballot { 7 | using ECDSA for bytes32; 8 | 9 | enum VoteType { 10 | For, 11 | Against 12 | } 13 | 14 | // keccak256("Ballot(bytes32 proposalHash,uint8 support)"); 15 | bytes32 private constant BALLOT_TYPEHASH = 0xd900570327c4c0df8dd6bdd522b7da7e39145dd049d2fd4602276adcd511e3c2; 16 | 17 | function hash(bytes32 _proposalHash, VoteType _support) internal pure returns (bytes32 digest) { 18 | // return keccak256(abi.encode(BALLOT_TYPEHASH, _proposalHash, _support)); 19 | assembly { 20 | let ptr := mload(0x40) 21 | mstore(ptr, BALLOT_TYPEHASH) 22 | mstore(add(ptr, 0x20), _proposalHash) 23 | mstore(add(ptr, 0x40), _support) 24 | digest := keccak256(ptr, 0x60) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /contracts/libraries/EmergencyExitBallot.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; 5 | 6 | library EmergencyExitBallot { 7 | // NOTE: The "address consensusAddress" is not changed in order to preserve the type hash. Since the EmergencyExitBallot 8 | // is not a library and is hashed by param feeds, not change the type hash still assure the contract to works correctly. 9 | 10 | // keccak256("EmergencyExitBallot(address consensusAddress,address recipientAfterUnlockedFund,uint256 requestedAt,uint256 expiredAt)"); 11 | bytes32 private constant EMERGENCY_EXIT_BALLOT_TYPEHASH = 12 | 0x697acba4deaf1a718d8c2d93e42860488cb7812696f28ca10eed17bac41e7027; 13 | 14 | /** 15 | * @dev Returns hash of the ballot. 16 | */ 17 | function hash( 18 | address validatorId, 19 | address recipientAfterUnlockedFund, 20 | uint256 requestedAt, 21 | uint256 expiredAt 22 | ) internal pure returns (bytes32 digest) { 23 | /* 24 | * return 25 | * keccak256( 26 | * abi.encode( 27 | * EMERGENCY_EXIT_BALLOT_TYPEHASH, 28 | * validatorId, 29 | * recipientAfterUnlockedFund, 30 | * requestedAt, 31 | * expiredAt 32 | * ) 33 | * ); 34 | */ 35 | assembly { 36 | let ptr := mload(0x40) 37 | mstore(ptr, EMERGENCY_EXIT_BALLOT_TYPEHASH) 38 | mstore(add(ptr, 0x20), validatorId) 39 | mstore(add(ptr, 0x40), recipientAfterUnlockedFund) 40 | mstore(add(ptr, 0x60), requestedAt) 41 | mstore(add(ptr, 0x80), expiredAt) 42 | digest := keccak256(ptr, 0xa0) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /contracts/libraries/EnumFlags.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | 3 | pragma solidity ^0.8.0; 4 | 5 | /** 6 | * @dev This library implements checking flag of an enumerated value. 7 | * The originated idea is inherited from [Enum.HashFlag(Enum)](https://learn.microsoft.com/en-us/dotnet/api/system.enum.hasflag?view=net-6.0) method of C#. 8 | */ 9 | library EnumFlags { 10 | enum ValidatorFlag { 11 | None, // bit(00) 12 | BlockProducer, // bit(01) 13 | DeprecatedBridgeOperator, // bit(10) 14 | Both // bit(11) 15 | 16 | } 17 | 18 | function isNone(ValidatorFlag _value) internal pure returns (bool) { 19 | return uint8(_value) == 0; 20 | } 21 | 22 | /** 23 | * @dev Checks if `_value` has `_flag`. 24 | */ 25 | function hasFlag(ValidatorFlag _value, ValidatorFlag _flag) internal pure returns (bool) { 26 | return (uint8(_value) & uint8(_flag)) != 0; 27 | } 28 | 29 | /** 30 | * @dev Calculate new value of `_value` after adding `_flag`. 31 | */ 32 | function addFlag(ValidatorFlag _value, ValidatorFlag _flag) internal pure returns (ValidatorFlag) { 33 | return ValidatorFlag(uint8(_value) | uint8(_flag)); 34 | } 35 | 36 | /** 37 | * @dev Calculate new value of `_value` after remove `_flag`. 38 | */ 39 | function removeFlag(ValidatorFlag _value, ValidatorFlag _flag) internal pure returns (ValidatorFlag) { 40 | return ValidatorFlag(uint8(_value) & ~uint8(_flag)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /contracts/libraries/ErrorHandler.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { ErrProxyCallFailed } from "../utils/CommonErrors.sol"; 5 | 6 | library ErrorHandler { 7 | /// @notice handle low level call revert if call failed, 8 | /// If extcall return empty bytes, reverts with custom error. 9 | /// @param status Status of external call 10 | /// @param callSig function signature of the calldata 11 | /// @param returnOrRevertData bytes result from external call 12 | function handleRevert(bool status, bytes4 callSig, bytes memory returnOrRevertData) internal pure { 13 | // Get the function signature of current context 14 | bytes4 msgSig = msg.sig; 15 | assembly { 16 | if iszero(status) { 17 | // Load the length of bytes array 18 | let revertLength := mload(returnOrRevertData) 19 | // Check if length != 0 => revert following reason from external call 20 | if iszero(iszero(revertLength)) { 21 | // Start of revert data bytes. The 0x20 offset is always the same. 22 | revert(add(returnOrRevertData, 0x20), revertLength) 23 | } 24 | 25 | // Load free memory pointer 26 | let ptr := mload(0x40) 27 | // Store 4 bytes the function selector of ErrProxyCallFailed(msg.sig, callSig) 28 | // Equivalent to revert ErrProxyCallFailed(bytes4,bytes4) 29 | mstore(ptr, 0x8e3eda2b) 30 | // Store 4 bytes of msgSig parameter in the next slot 31 | mstore(add(ptr, 0x20), msgSig) 32 | // Store 4 bytes of callSig parameter in the next slot 33 | mstore(add(ptr, 0x40), callSig) 34 | // Revert 68 bytes of error starting from 0x1c 35 | revert(add(ptr, 0x1c), 0x44) 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /contracts/libraries/Math.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | 3 | pragma solidity ^0.8.0; 4 | 5 | library Math { 6 | /** 7 | * @dev Returns the largest of two numbers. 8 | */ 9 | function max(uint256 a, uint256 b) internal pure returns (uint256) { 10 | return a >= b ? a : b; 11 | } 12 | 13 | /** 14 | * @dev Returns the smallest of two numbers. 15 | */ 16 | function min(uint256 a, uint256 b) internal pure returns (uint256) { 17 | return a < b ? a : b; 18 | } 19 | 20 | /** 21 | * @dev Returns whether the number `c` is in range of [a; b]. 22 | */ 23 | function inRange(uint256 c, uint256 a, uint256 b) internal pure returns (bool) { 24 | return a <= c && c <= b; 25 | } 26 | 27 | /** 28 | * @dev Returns whether two inclusive ranges [x1;x2] and [y1;y2] overlap. 29 | */ 30 | function twoRangeOverlap(uint256 x1, uint256 x2, uint256 y1, uint256 y2) internal pure returns (bool) { 31 | return x1 <= y2 && y1 <= x2; 32 | } 33 | 34 | /** 35 | * @dev Returns value of a + b; in case result is larger than upperbound, upperbound is returned. 36 | */ 37 | function addWithUpperbound(uint256 a, uint256 b, uint256 upperbound) internal pure returns (uint256) { 38 | return min(a + b, upperbound); 39 | } 40 | 41 | /** 42 | * @dev Returns value of a - b; in case of negative result, 0 is returned. 43 | */ 44 | function subNonNegative(uint256 a, uint256 b) internal pure returns (uint256) { 45 | return a > b ? a - b : 0; 46 | } 47 | 48 | /** 49 | * @dev Returns value of `a + zeroable` if zerobale is not 0; otherwise, return 0. 50 | */ 51 | function addIfNonZero(uint256 a, uint256 zeroable) internal pure returns (uint256) { 52 | return zeroable != 0 ? a + zeroable : 0; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /contracts/mocks/MockBridge.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "@openzeppelin/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol"; 6 | import "../interfaces/IBridge.sol"; 7 | 8 | contract MockBridge is IBridge { 9 | /// @dev Mapping from validator address => last block that the bridge operator is added 10 | mapping(address => uint256) public bridgeOperatorAddedBlock; 11 | /// @dev Bridge operators array 12 | address[] public bridgeOperators; 13 | 14 | function replaceBridgeOperators(address[] calldata _list) external { 15 | address _addr; 16 | for (uint256 _i = 0; _i < _list.length; _i++) { 17 | _addr = _list[_i]; 18 | if (bridgeOperatorAddedBlock[_addr] == 0) { 19 | bridgeOperators.push(_addr); 20 | } 21 | bridgeOperatorAddedBlock[_addr] = block.number; 22 | } 23 | 24 | { 25 | uint256 _i; 26 | while (_i < bridgeOperators.length) { 27 | _addr = bridgeOperators[_i]; 28 | if (bridgeOperatorAddedBlock[_addr] < block.number) { 29 | delete bridgeOperatorAddedBlock[_addr]; 30 | bridgeOperators[_i] = bridgeOperators[bridgeOperators.length - 1]; 31 | bridgeOperators.pop(); 32 | continue; 33 | } 34 | _i++; 35 | } 36 | } 37 | } 38 | 39 | function getBridgeOperators() external view override returns (address[] memory) { 40 | return bridgeOperators; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /contracts/mocks/MockGatewayForTracking.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../interfaces/bridge/IBridgeTracking.sol"; 6 | import "../extensions/collections/HasContracts.sol"; 7 | import { HasBridgeTrackingDeprecated } from "../utils/DeprecatedSlots.sol"; 8 | 9 | contract MockGatewayForTracking is HasContracts, HasBridgeTrackingDeprecated { 10 | constructor(address bridgeTrackingContract) { 11 | _setContract(ContractType.BRIDGE_TRACKING, bridgeTrackingContract); 12 | } 13 | 14 | function sendBallot(IBridgeTracking.VoteKind kind, uint256 id, address[] memory voters) external { 15 | IBridgeTracking bridgeTrackingContract = IBridgeTracking(getContract(ContractType.BRIDGE_TRACKING)); 16 | for (uint256 i; i < voters.length; i++) { 17 | bridgeTrackingContract.recordVote(kind, id, voters[i]); 18 | } 19 | } 20 | 21 | function sendApprovedVote(IBridgeTracking.VoteKind kind, uint256 id) external { 22 | IBridgeTracking(getContract(ContractType.BRIDGE_TRACKING)).handleVoteApproved(kind, id); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /contracts/mocks/MockProfile.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./MockPrecompile.sol"; 6 | import "../ronin/slash-indicator/SlashIndicator.sol"; 7 | import "../interfaces/validator/IRoninValidatorSet.sol"; 8 | import "../ronin/profile/Profile.sol"; 9 | 10 | contract MockProfile is Profile { 11 | bool internal _verificationFailed; 12 | 13 | function addNewProfile(CandidateProfile memory profile) external onlyAdmin { 14 | CandidateProfile storage _profile = _id2Profile[profile.id]; 15 | if (_profile.id != address(0)) revert ErrExistentProfile(); 16 | _addNewProfile(_profile, profile); 17 | } 18 | 19 | function setVerificationFailed(bool _failed) external { 20 | _verificationFailed = _failed; 21 | } 22 | 23 | function _pcVerifyBLSPublicKey( 24 | bytes calldata, /*publicKey*/ 25 | bytes calldata /*proofOfPossession*/ 26 | ) internal view override returns (bool) { 27 | return !_verificationFailed; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /contracts/mocks/MockSlashIndicatorExtended.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./MockPrecompile.sol"; 6 | import "../ronin/slash-indicator/SlashIndicator.sol"; 7 | import "../interfaces/validator/IRoninValidatorSet.sol"; 8 | 9 | contract MockSlashIndicatorExtended is SlashIndicator, MockPrecompile { 10 | function slashFelony(address _validatorAddr) external { 11 | IRoninValidatorSet(getContract(ContractType.VALIDATOR)).execSlash(_validatorAddr, 0, 0, false); 12 | } 13 | 14 | function slashMisdemeanor(address _validatorAddr) external { 15 | IRoninValidatorSet(getContract(ContractType.VALIDATOR)).execSlash(_validatorAddr, 0, 0, false); 16 | } 17 | 18 | function _pcValidateEvidence( 19 | address _consensusAddr, 20 | bytes calldata _header1, 21 | bytes calldata _header2 22 | ) internal pure override returns (bool _validEvidence) { 23 | return validatingDoubleSignProof(_consensusAddr, _header1, _header2); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /contracts/mocks/MockTransferFallback.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import "../extensions/RONTransferHelper.sol"; 5 | 6 | contract MockPaymentFallback { 7 | event SafeReceived(address indexed sender, uint256 value); 8 | 9 | /// @dev Fallback function accepts ether transactions. 10 | receive() external payable { 11 | emit SafeReceived(msg.sender, msg.value); 12 | } 13 | } 14 | 15 | contract MockPaymentFallbackExpensive { 16 | uint[] public array; 17 | 18 | event SafeReceived(address indexed sender, uint256 value); 19 | 20 | constructor() { 21 | array.push(0); 22 | } 23 | 24 | /// @dev Fallback function accepts ether transactions and set non-zero value to a zero value slot. 25 | receive() external payable { 26 | array.push(block.number); 27 | emit SafeReceived(msg.sender, msg.value); 28 | } 29 | } 30 | 31 | contract MockTransfer is RONTransferHelper { 32 | uint256 public track; 33 | 34 | constructor() payable { } 35 | 36 | function fooTransfer(address payable _recipient, uint256 _amount, uint256 _gas) external { 37 | if (_unsafeSendRONLimitGas(_recipient, _amount, _gas)) { 38 | track++; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /contracts/mocks/precompile-usages/MockPCUPickValidatorSet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../../precompile-usages/PCUPickValidatorSet.sol"; 6 | 7 | contract MockPCUPickValidatorSet is PCUPickValidatorSet { 8 | address internal _precompileSortValidatorAddress; 9 | 10 | constructor(address _precompile) { 11 | setPrecompileSortValidatorAddress(_precompile); 12 | } 13 | 14 | function setPrecompileSortValidatorAddress(address _addr) public { 15 | _precompileSortValidatorAddress = _addr; 16 | } 17 | 18 | function precompilePickValidatorSetAddress() public view override returns (address) { 19 | return _precompileSortValidatorAddress; 20 | } 21 | 22 | function callPrecompile( 23 | address[] memory _candidates, 24 | uint256[] memory _weights, 25 | uint256[] memory _trustedWeights, 26 | uint256 _maxValidatorNumber, 27 | uint256 _maxPrioritizedValidatorNumber 28 | ) public view returns (address[] memory _result) { 29 | (_result,) = 30 | _pcPickValidatorSet(_candidates, _weights, _trustedWeights, _maxValidatorNumber, _maxPrioritizedValidatorNumber); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contracts/mocks/precompile-usages/MockPCUSortValidators.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../../precompile-usages/PCUSortValidators.sol"; 6 | 7 | contract MockPCUSortValidators is PCUSortValidators { 8 | address internal _precompileSortValidatorAddress; 9 | 10 | constructor(address _precompile) { 11 | setPrecompileSortValidatorAddress(_precompile); 12 | } 13 | 14 | function setPrecompileSortValidatorAddress(address _addr) public { 15 | _precompileSortValidatorAddress = _addr; 16 | } 17 | 18 | function precompileSortValidatorsAddress() public view override returns (address) { 19 | return _precompileSortValidatorAddress; 20 | } 21 | 22 | function callPrecompile( 23 | address[] calldata _validators, 24 | uint256[] calldata _weights 25 | ) public view returns (address[] memory _result) { 26 | return _pcSortCandidates(_validators, _weights); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /contracts/mocks/precompile-usages/MockPCUValidateDoubleSign.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../../precompile-usages/PCUValidateDoubleSign.sol"; 6 | 7 | contract MockPCUValidateDoubleSign is PCUValidateDoubleSign { 8 | address internal _precompileValidateDoubleSignAddress; 9 | 10 | constructor(address _precompile) { 11 | setPrecompileValidateDoubleSignAddress(_precompile); 12 | } 13 | 14 | function setPrecompileValidateDoubleSignAddress(address _addr) public { 15 | _precompileValidateDoubleSignAddress = _addr; 16 | } 17 | 18 | function precompileValidateDoubleSignAddress() public view override returns (address) { 19 | return _precompileValidateDoubleSignAddress; 20 | } 21 | 22 | function callPrecompile( 23 | address _consensusAddr, 24 | bytes calldata _header1, 25 | bytes calldata _header2 26 | ) public view returns (bool) { 27 | return _pcValidateEvidence(_consensusAddr, _header1, _header2); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /contracts/mocks/precompile-usages/MockPCUValidateFastFinality.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../../precompile-usages/PCUValidateFastFinality.sol"; 6 | 7 | contract MockPCUValidateFastFinality is PCUValidateFastFinality { 8 | address internal _precompileValidateFastFinalityAddress; 9 | 10 | constructor(address _precompile) { 11 | setPrecompileValidateFastFinalityAddress(_precompile); 12 | } 13 | 14 | function setPrecompileValidateFastFinalityAddress(address _addr) public { 15 | _precompileValidateFastFinalityAddress = _addr; 16 | } 17 | 18 | function precompileValidateFastFinalityAddress() public view override returns (address) { 19 | return _precompileValidateFastFinalityAddress; 20 | } 21 | 22 | function callPrecompile( 23 | bytes memory voterPublicKey, 24 | uint256 targetBlockNumber, 25 | bytes32[2] memory targetBlockHash, 26 | bytes[][2] memory listOfPublicKey, 27 | bytes[2] memory aggregatedSignature 28 | ) public view returns (bool) { 29 | return _pcValidateFastFinalityEvidence( 30 | voterPublicKey, targetBlockNumber, targetBlockHash, listOfPublicKey, aggregatedSignature 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockBridgeManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { 5 | RoleAccess, 6 | ContractType, 7 | AddressArrayUtils, 8 | IBridgeManager, 9 | BridgeManager 10 | } from "../../extensions/bridge-operator-governance/BridgeManager.sol"; 11 | 12 | contract MockBridgeManager is BridgeManager { 13 | constructor( 14 | address[] memory bridgeOperators, 15 | address[] memory governors, 16 | uint96[] memory voteWeights 17 | ) payable BridgeManager(0, 0, 0, address(0), _getEmptyAddressArray(), bridgeOperators, governors, voteWeights) { } 18 | 19 | function _getEmptyAddressArray() internal pure returns (address[] memory arr) { } 20 | } 21 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockBridgeReward.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { IBridgeReward, BridgeReward } from "../../ronin/gateway/BridgeReward.sol"; 5 | 6 | contract MockBridgeReward is BridgeReward { 7 | function calcRewardAndCheckSlashedStatus( 8 | bool isValidTrackingResponse, 9 | uint256 numBridgeOperators, 10 | uint256 rewardPerPeriod, 11 | uint256 ballot, 12 | uint256 totalBallot, 13 | uint256 period, 14 | uint256 slashUntilPeriod 15 | ) external pure returns (uint256 reward, bool isSlashed) { 16 | return _calcRewardAndCheckSlashedStatus( 17 | isValidTrackingResponse, numBridgeOperators, rewardPerPeriod, ballot, totalBallot, period, slashUntilPeriod 18 | ); 19 | } 20 | 21 | function calcReward( 22 | bool isValidTrackingResponse, 23 | uint256 numBridgeOperators, 24 | uint256 rewardPerPeriod, 25 | uint256 ballot, 26 | uint256 totalBallot 27 | ) external pure returns (uint256 reward) { 28 | reward = _calcReward(isValidTrackingResponse, numBridgeOperators, rewardPerPeriod, ballot, totalBallot); 29 | } 30 | 31 | function isValidBridgeTrackingResponse( 32 | uint256 totalBallot, 33 | uint256 totalVote, 34 | uint256[] memory ballots 35 | ) external pure returns (bool valid) { 36 | return _isValidBridgeTrackingResponse(totalBallot, totalVote, ballots); 37 | } 38 | 39 | function shouldShareEqually( 40 | uint256 totalBallot, 41 | uint256 totalVote, 42 | uint256[] memory ballots 43 | ) external returns (bool shareEqually) { 44 | return _shouldShareEqually(totalBallot, totalVote, ballots); 45 | } 46 | 47 | function shouldSlashedThisPeriod(uint256 period, uint256 slashUntilDuration) external pure returns (bool) { 48 | return _shouldSlashedThisPeriod(period, slashUntilDuration); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockBridgeSlash.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { IBridgeSlash, BridgeSlash } from "../../ronin/gateway/BridgeSlash.sol"; 5 | 6 | contract MockBridgeSlash is BridgeSlash { 7 | function calcSlashUntilPeriod( 8 | Tier tier, 9 | uint256 period, 10 | uint256 slashUntilPeriod 11 | ) external pure returns (uint256 newSlashUntilPeriod) { 12 | newSlashUntilPeriod = _calcSlashUntilPeriod(tier, period, slashUntilPeriod, _getPenaltyDurations()); 13 | } 14 | 15 | function isSlashDurationMetRemovalThreshold(uint256 slashUntilPeriod, uint256 period) external pure returns (bool) { 16 | return _isSlashDurationMetRemovalThreshold(slashUntilPeriod, period); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockBridgeTracking.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockRoninBridgeManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { RoninBridgeManager } from "../../ronin/gateway/RoninBridgeManager.sol"; 5 | import { GlobalProposal } from "../../extensions/sequential-governance/governance-proposal/GovernanceProposal.sol"; 6 | 7 | contract MockRoninBridgeManager is RoninBridgeManager { 8 | constructor( 9 | uint256 num, 10 | uint256 denom, 11 | uint256 roninChainId, 12 | uint256 expiryDuration, 13 | address bridgeContract, 14 | address[] memory callbackRegisters, 15 | address[] memory bridgeOperators, 16 | address[] memory governors, 17 | uint96[] memory voteWeights, 18 | GlobalProposal.TargetOption[] memory targetOptions, 19 | address[] memory targets 20 | ) 21 | RoninBridgeManager( 22 | num, 23 | denom, 24 | roninChainId, 25 | expiryDuration, 26 | bridgeContract, 27 | callbackRegisters, 28 | bridgeOperators, 29 | governors, 30 | voteWeights, 31 | targetOptions, 32 | targets 33 | ) 34 | { } 35 | } 36 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockRoninGatewayV3Extended.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../../ronin/gateway/RoninGatewayV3.sol"; 5 | 6 | contract MockRoninGatewayV3Extended is RoninGatewayV3 { 7 | /* 8 | * @dev Returns the vote weight for a deposit based on its corressponding hash. 9 | */ 10 | function getDepositVoteWeight( 11 | uint256 _chainId, 12 | uint256 _depositId, 13 | bytes32 _hash 14 | ) external view returns (uint256 totalWeight) { 15 | totalWeight = _getVoteWeight(depositVote[_chainId][_depositId], _hash); 16 | } 17 | 18 | /** 19 | * @dev Returns the vote weight for a mainchain withdrew acknowledgement based on its corressponding hash. 20 | */ 21 | function getMainchainWithdrewVoteWeight( 22 | uint256 _withdrawalId, 23 | bytes32 _hash 24 | ) external view returns (uint256 totalWeight) { 25 | totalWeight = _getVoteWeight(mainchainWithdrewVote[_withdrawalId], _hash); 26 | } 27 | 28 | /** 29 | * @dev Returns the vote weight for a withdraw stats based on its corressponding hash. 30 | */ 31 | function getWithdrawalStatVoteWeight( 32 | uint256 _withdrawalId, 33 | bytes32 _hash 34 | ) external view returns (uint256 totalWeight) { 35 | totalWeight = _getVoteWeight(withdrawalStatVote[_withdrawalId], _hash); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /contracts/mocks/ronin/MockValidatorContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract MockValidatorContract { 5 | uint256 private _currentPeriod; 6 | 7 | function currentPeriod() external view returns (uint256) { 8 | return _currentPeriod; 9 | } 10 | 11 | function setCurrentPeriod(uint256 period) external { 12 | _currentPeriod = period; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /contracts/mocks/sorting/MockSorting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; 6 | import "../libraries/Sorting.sol"; 7 | 8 | contract MockSorting { 9 | uint256[] public data; 10 | 11 | function addData(uint256[] memory _data) public { 12 | for (uint256 i; i < _data.length; i++) { 13 | data.push(_data[i]); 14 | } 15 | } 16 | 17 | function sort(uint256[] memory _data) public pure returns (uint256[] memory) { 18 | return Sorting.sort(_data); 19 | } 20 | 21 | function sortOnStorage() public returns (uint256[] memory, uint256) { 22 | uint256[] memory _tmpData = data; 23 | data = Sorting.sort(_tmpData); 24 | 25 | return (data, data.length); 26 | } 27 | 28 | function sortAddressesAndValues( 29 | address[] calldata _addrs, 30 | uint256[] calldata _values 31 | ) public pure returns (address[] memory) { 32 | return Sorting.sort(_addrs, _values); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /contracts/mocks/utils/version-control/MockActor.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { ErrorHandler } from "../../../libraries/ErrorHandler.sol"; 5 | 6 | contract MockActor { 7 | using ErrorHandler for bool; 8 | 9 | address private _target; 10 | 11 | constructor(address target) { 12 | _target = target; 13 | } 14 | 15 | fallback() external payable { 16 | (bool success, bytes memory returnOrRevertData) = _target.call{ value: msg.value }(msg.data); 17 | success.handleRevert(msg.sig, returnOrRevertData); 18 | assembly { 19 | return(add(returnOrRevertData, 0x20), mload(returnOrRevertData)) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /contracts/mocks/utils/version-control/MockConditionalImplementControl.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { ConditionalImplementControl } from "../../../extensions/version-control/ConditionalImplementControl.sol"; 5 | 6 | contract MockConditionalImplementControl is ConditionalImplementControl { 7 | uint256 public immutable UPGRADED_AT_BLOCK; 8 | 9 | constructor( 10 | address proxyStorage, 11 | address prevImpl, 12 | address newImpl, 13 | uint256 upgradedAtBlock 14 | ) ConditionalImplementControl(proxyStorage, prevImpl, newImpl) { 15 | UPGRADED_AT_BLOCK = upgradedAtBlock; 16 | } 17 | 18 | function _isConditionMet() internal view override returns (bool) { 19 | return block.number >= UPGRADED_AT_BLOCK; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /contracts/mocks/utils/version-control/MockLogic.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface ILogic { 5 | event Received(uint256 version); 6 | 7 | function name() external pure returns (string memory); 8 | 9 | function magicNumber() external view returns (uint256); 10 | 11 | function get() external view returns (uint256); 12 | 13 | function set() external; 14 | 15 | function setAndGet() external returns (uint256); 16 | } 17 | 18 | abstract contract MockLogicBase is ILogic { 19 | uint256 internal _value; 20 | 21 | function magicNumber() public view virtual override returns (uint256) { } 22 | 23 | receive() external payable virtual { 24 | emit Received(0); 25 | } 26 | 27 | function get() public view returns (uint256) { 28 | return _value; 29 | } 30 | 31 | function set() public override { 32 | _value = magicNumber(); 33 | } 34 | 35 | function setAndGet() public returns (uint256) { 36 | set(); 37 | return get(); 38 | } 39 | } 40 | 41 | contract MockLogicV1 is MockLogicBase { 42 | receive() external payable override { 43 | emit Received(1); 44 | } 45 | 46 | function name() external pure returns (string memory) { 47 | return "LogicV1"; 48 | } 49 | 50 | function magicNumber() public pure override returns (uint256) { 51 | return 1; 52 | } 53 | } 54 | 55 | contract MockLogicV2 is MockLogicBase { 56 | receive() external payable override { 57 | emit Received(2); 58 | } 59 | 60 | function name() external pure returns (string memory) { 61 | return "LogicV2"; 62 | } 63 | 64 | function magicNumber() public pure override returns (uint256) { 65 | return 2; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /contracts/mocks/utils/version-control/MockLogicValidatorSet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | interface ILogicValidatorSet { 5 | event Received(string version); 6 | 7 | function wrapUpEpoch() external payable; 8 | 9 | function version() external view returns (string memory); 10 | 11 | function currentPeriod() external view returns (uint256); 12 | } 13 | 14 | abstract contract MockLogicValidatorSetCore is ILogicValidatorSet { 15 | uint256 private _lastUpdatedPeriod; 16 | 17 | receive() external payable virtual { 18 | emit Received("0"); 19 | } 20 | 21 | function wrapUpEpoch() external payable { 22 | if (block.number % 100 == 0) { 23 | _lastUpdatedPeriod += 1; 24 | } 25 | } 26 | 27 | function currentPeriod() external view returns (uint256) { 28 | return _lastUpdatedPeriod; 29 | } 30 | } 31 | 32 | contract MockLogicValidatorSetV1 is MockLogicValidatorSetCore { 33 | receive() external payable override { 34 | emit Received(version()); 35 | } 36 | 37 | function version() public pure returns (string memory) { 38 | return "V1"; 39 | } 40 | } 41 | 42 | contract MockLogicValidatorSetV2 is MockLogicValidatorSetCore { 43 | receive() external payable override { 44 | emit Received(version()); 45 | } 46 | 47 | function version() public pure returns (string memory) { 48 | return "V2"; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /contracts/mocks/validator/MockRoninValidatorSetExtended.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./MockRoninValidatorSetOverridePrecompile.sol"; 6 | import "../../libraries/EnumFlags.sol"; 7 | 8 | contract MockRoninValidatorSetExtended is MockRoninValidatorSetOverridePrecompile { 9 | bool private _initialized; 10 | uint256[] internal _epochs; 11 | 12 | constructor() { } 13 | 14 | function initEpoch() public { 15 | if (!_initialized) { 16 | _epochs.push(0); 17 | _initialized = true; 18 | } 19 | } 20 | 21 | function endEpoch() external { 22 | _epochs.push(block.number); 23 | } 24 | 25 | function epochOf(uint256 _block) public view override returns (uint256 _epoch) { 26 | for (uint256 _i = _epochs.length; _i > 0; _i--) { 27 | if (_block > _epochs[_i - 1]) { 28 | return _i; 29 | } 30 | } 31 | } 32 | 33 | function epochEndingAt(uint256 _block) public view override(ITimingInfo, TimingStorage) returns (bool) { 34 | for (uint _i = 0; _i < _epochs.length; _i++) { 35 | if (_block == _epochs[_i]) { 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | function getJailUntils(address[] calldata _addrs) public view returns (uint256[] memory jailUntils_) { 43 | jailUntils_ = new uint256[](_addrs.length); 44 | for (uint _i = 0; _i < _addrs.length; _i++) { 45 | jailUntils_[_i] = _blockProducerJailedBlock[_addrs[_i]]; 46 | } 47 | } 48 | 49 | function addValidators(address[] calldata _addrs) public { 50 | for (uint _i = 0; _i < _addrs.length; _i++) { 51 | address _cAddr = _addrs[_i]; 52 | _validatorIds[_i] = _cAddr; 53 | _validatorMap[_cAddr] = EnumFlags.ValidatorFlag.Both; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /contracts/mocks/validator/MockRoninValidatorSetOverridePrecompile.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../MockPrecompile.sol"; 6 | import "../../ronin/validator/RoninValidatorSet.sol"; 7 | 8 | contract MockRoninValidatorSetOverridePrecompile is RoninValidatorSet, MockPrecompile { 9 | constructor() { } 10 | 11 | function arrangeValidatorCandidates( 12 | address[] memory _candidates, 13 | uint256[] memory _trustedWeights, 14 | uint _newValidatorCount, 15 | uint _maxPrioritizedValidatorNumber 16 | ) external pure returns (address[] memory) { 17 | _arrangeValidatorCandidates(_candidates, _trustedWeights, _newValidatorCount, _maxPrioritizedValidatorNumber); 18 | return _candidates; 19 | } 20 | 21 | function _pcSortCandidates( 22 | address[] memory _candidates, 23 | uint256[] memory _weights 24 | ) internal pure override returns (address[] memory _result) { 25 | return sortValidators(_candidates, _weights); 26 | } 27 | 28 | function _pcPickValidatorSet( 29 | address[] memory _candidates, 30 | uint256[] memory _weights, 31 | uint256[] memory _trustedWeights, 32 | uint256 _maxValidatorNumber, 33 | uint256 _maxPrioritizedValidatorNumber 34 | ) internal pure override returns (address[] memory _result, uint256 _newValidatorCount) { 35 | _result = 36 | pickValidatorSet(_candidates, _weights, _trustedWeights, _maxValidatorNumber, _maxPrioritizedValidatorNumber); 37 | 38 | _newValidatorCount = _result.length; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /contracts/precompile-usages/PCUSortValidators.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./PrecompiledUsage.sol"; 6 | 7 | abstract contract PCUSortValidators is PrecompiledUsage { 8 | /// @dev Gets the address of the precompile of sorting validators 9 | function precompileSortValidatorsAddress() public view virtual returns (address) { 10 | return address(0x66); 11 | } 12 | 13 | /** 14 | * @dev Sorts candidates descending by their weights by calling precompile contract. 15 | * 16 | * Note: This function is marked as virtual for being wrapping in mock contract for testing purpose. 17 | */ 18 | function _pcSortCandidates( 19 | address[] memory _candidates, 20 | uint256[] memory _weights 21 | ) internal view virtual returns (address[] memory _result) { 22 | address _smc = precompileSortValidatorsAddress(); 23 | bool _success = true; 24 | 25 | bytes memory _payload = abi.encodeWithSignature("sortValidators(address[],uint256[])", _candidates, _weights); 26 | uint256 _payloadLength = _payload.length; 27 | uint256 _resultLength = 0x20 * _candidates.length + 0x40; 28 | 29 | assembly { 30 | let _payloadStart := add(_payload, 0x20) 31 | 32 | if iszero(staticcall(gas(), _smc, _payloadStart, _payloadLength, _result, _resultLength)) { _success := 0 } 33 | 34 | if iszero(returndatasize()) { _success := 0 } 35 | 36 | _result := add(_result, 0x20) 37 | } 38 | 39 | if (!_success) revert ErrCallPrecompiled(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /contracts/precompile-usages/PCUValidateDoubleSign.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./PrecompiledUsage.sol"; 6 | 7 | abstract contract PCUValidateDoubleSign is PrecompiledUsage { 8 | /// @dev Gets the address of the precompile of validating double sign evidence 9 | function precompileValidateDoubleSignAddress() public view virtual returns (address) { 10 | return address(0x67); 11 | } 12 | 13 | /** 14 | * @dev Validates the two submitted block header if they are produced by the same address 15 | * 16 | * Note: The recover process is done by pre-compiled contract. This function is marked as 17 | * virtual for implementing mocking contract for testing purpose. 18 | */ 19 | function _pcValidateEvidence( 20 | address _consensusAddr, 21 | bytes calldata _header1, 22 | bytes calldata _header2 23 | ) internal view virtual returns (bool _validEvidence) { 24 | address _smc = precompileValidateDoubleSignAddress(); 25 | bool _success = true; 26 | 27 | bytes memory _payload = 28 | abi.encodeWithSignature("validatingDoubleSignProof(address,bytes,bytes)", _consensusAddr, _header1, _header2); 29 | uint _payloadLength = _payload.length; 30 | uint[1] memory _output; 31 | 32 | assembly { 33 | let _payloadStart := add(_payload, 0x20) 34 | if iszero(staticcall(gas(), _smc, _payloadStart, _payloadLength, _output, 0x20)) { _success := 0 } 35 | 36 | if iszero(returndatasize()) { _success := 0 } 37 | } 38 | 39 | if (!_success) revert ErrCallPrecompiled(); 40 | return (_output[0] != 0); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /contracts/precompile-usages/PCUValidateFastFinality.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./PrecompiledUsage.sol"; 6 | 7 | abstract contract PCUValidateFastFinality is PrecompiledUsage { 8 | /// @dev Gets the address of the precompile of validating double sign evidence 9 | function precompileValidateFastFinalityAddress() public view virtual returns (address) { 10 | return address(0x69); 11 | } 12 | 13 | /** 14 | * @dev Validates the proof of malicious voting on fast finality 15 | * 16 | * Note: The recover process is done by pre-compiled contract. This function is marked as 17 | * virtual for implementing mocking contract for testing purpose. 18 | */ 19 | function _pcValidateFastFinalityEvidence( 20 | bytes memory voterPublicKey, 21 | uint256 targetBlockNumber, 22 | bytes32[2] memory targetBlockHash, 23 | bytes[][2] memory listOfPublicKey, 24 | bytes[2] memory aggregatedSignature 25 | ) internal view virtual returns (bool validEvidence) { 26 | address smc = precompileValidateFastFinalityAddress(); 27 | bool success = true; 28 | 29 | bytes memory payload = abi.encodeWithSignature( 30 | "validateFinalityVoteProof(bytes,uint256,bytes32[2],bytes[][2],bytes[2])", 31 | voterPublicKey, 32 | targetBlockNumber, 33 | targetBlockHash, 34 | listOfPublicKey, 35 | aggregatedSignature 36 | ); 37 | uint payloadLength = payload.length; 38 | uint[1] memory output; 39 | 40 | assembly { 41 | let payloadStart := add(payload, 0x20) 42 | if iszero(staticcall(gas(), smc, payloadStart, payloadLength, output, 0x20)) { success := 0 } 43 | if iszero(returndatasize()) { success := 0 } 44 | } 45 | 46 | if (!success) revert ErrCallPrecompiled(); 47 | return (output[0] != 0); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /contracts/precompile-usages/PCUVerifyBLSPublicKey.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./PrecompiledUsage.sol"; 6 | 7 | abstract contract PCUVerifyBLSPublicKey is PrecompiledUsage { 8 | /// @dev Gets the address of the precompile of validating double sign evidence 9 | function precompileVerifyBLSPublicKeyAddress() public view virtual returns (address) { 10 | return address(0x6a); 11 | } 12 | 13 | /** 14 | * @dev Validates the proof of possession of BLS public key 15 | * 16 | * Note: The verify process is done by pre-compiled contract. This function is marked as 17 | * virtual for implementing mocking contract for testing purpose. 18 | */ 19 | function _pcVerifyBLSPublicKey( 20 | bytes calldata publicKey, 21 | bytes calldata proofOfPossession 22 | ) internal view virtual returns (bool validPublicKey) { 23 | address smc = precompileVerifyBLSPublicKeyAddress(); 24 | bool success = true; 25 | 26 | bytes memory payload = 27 | abi.encodeWithSignature("validateProofOfPossession(bytes,bytes)", publicKey, proofOfPossession); 28 | uint payloadLength = payload.length; 29 | uint[1] memory output; 30 | 31 | assembly { 32 | let payloadStart := add(payload, 0x20) 33 | if iszero(staticcall(gas(), smc, payloadStart, payloadLength, output, 0x20)) { success := 0 } 34 | 35 | if iszero(returndatasize()) { success := 0 } 36 | } 37 | 38 | if (!success) revert ErrCallPrecompiled(); 39 | return (output[0] != 0); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /contracts/precompile-usages/PrecompiledUsage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "./PrecompiledUsage.sol"; 6 | 7 | abstract contract PrecompiledUsage { 8 | /// @dev Error of call to precompile fails. 9 | error ErrCallPrecompiled(); 10 | } 11 | -------------------------------------------------------------------------------- /contracts/ronin/VaultForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../extensions/forwarder/Forwarder.sol"; 6 | import "../extensions/RONTransferHelper.sol"; 7 | 8 | /** 9 | * @title A vault contract that keeps RON, and behaves as an EOA account to interact with a target contract. 10 | * @dev There are three roles of interaction: 11 | * - Admin: top-up and withdraw RON to the vault, cannot forward call to the target. 12 | * - Moderator: forward all calls to the target, can top-up RON, cannot withdraw RON. 13 | * - Others: can top-up RON, cannot execute any other actions. 14 | */ 15 | contract VaultForwarder is Forwarder, RONTransferHelper { 16 | /// @dev Emitted when the admin withdraws all RON from the forwarder contract. 17 | event ForwarderRONWithdrawn(address indexed recipient, uint256 value); 18 | 19 | constructor(address[] memory targets, address admin, address mod) Forwarder(targets, admin, mod) { } 20 | 21 | /** 22 | * @dev Withdraws all balance from the transfer to the admin. 23 | * 24 | * Requirements: 25 | * - Only the admin can call this method. 26 | */ 27 | function withdrawAll() external onlyRole(DEFAULT_ADMIN_ROLE) { 28 | uint256 value = address(this).balance; 29 | emit ForwarderRONWithdrawn(msg.sender, value); 30 | _transferRON(payable(msg.sender), value); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contracts/ronin/profile/Profile_Mainnet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | import "./Profile.sol"; 4 | 5 | pragma solidity ^0.8.9; 6 | 7 | contract Profile_Mainnet is Profile { 8 | modifier hookChangeConsensus() override { 9 | revert("Not supported"); 10 | _; 11 | } 12 | 13 | function migrateOmissionREP4() external onlyAdmin { 14 | if (block.chainid != 2020) return; 15 | address[] memory omittedCssList = new address[](3); 16 | 17 | omittedCssList[0] = 0x454f6C34F0cfAdF1733044Fdf8B06516BD1E9529; 18 | omittedCssList[1] = 0xD7fEf73d95ccEdb26483fd3C6C48393e50708159; 19 | omittedCssList[2] = 0xbD4bf317Da1928CC2f9f4DA9006401f3944A0Ab5; 20 | 21 | CandidateProfile storage _profile; 22 | for (uint i; i < omittedCssList.length; ++i) { 23 | address id = omittedCssList[i]; 24 | TConsensus css = TConsensus.wrap(id); 25 | 26 | _profile = _id2Profile[id]; 27 | _profile.oldConsensus = css; 28 | _consensus2Id[css] = id; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /contracts/ronin/slash-indicator/DeprecatedSlashBridgeOperator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import "../../extensions/consumers/PercentageConsumer.sol"; 6 | import "../../extensions/collections/HasProxyAdmin.sol"; 7 | import "../../extensions/collections/HasContracts.sol"; 8 | import { HasValidatorDeprecated } from "../../utils/DeprecatedSlots.sol"; 9 | 10 | abstract contract DeprecatedSlashBridgeOperator is 11 | HasProxyAdmin, 12 | HasContracts, 13 | HasValidatorDeprecated, 14 | PercentageConsumer 15 | { 16 | /** 17 | * @dev The bridge operators will be deprecated reward if (s)he missed more than the ratio. 18 | * Values 0-10,000 map to 0%-100%. 19 | */ 20 | uint256 private ____deprecatedMissingVotesRatioTier1; 21 | /** 22 | * @dev The bridge operators will be deprecated all rewards including bridge reward and mining reward if (s)he missed 23 | * more than the ratio. Values 0-10,000 map to 0%-100%. 24 | */ 25 | uint256 private ____deprecatedMissingVotesRatioTier2; 26 | /// @dev The number of blocks to jail the corresponding block producer when its bridge operator is slashed tier-2. 27 | uint256 private ____deprecatedJailDurationForMissingVotesRatioTier2; 28 | /// @dev The threshold to skip slashing the bridge operator in case the total number of votes in the bridge is too small. 29 | uint256 private ____deprecatedSkipBridgeOperatorSlashingThreshold; 30 | 31 | /** 32 | * @dev This empty reserved space is put in place to allow future versions to add new 33 | * variables without shifting down storage in the inheritance chain. 34 | */ 35 | uint256[50] private ______gap; 36 | } 37 | -------------------------------------------------------------------------------- /contracts/ronin/slash-indicator/DeprecatedSlashBridgeVoting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | import { 6 | HasValidatorDeprecated, 7 | HasTrustedOrgDeprecated, 8 | HasGovernanceAdminDeprecated 9 | } from "../../utils/DeprecatedSlots.sol"; 10 | import "../../extensions/collections/HasContracts.sol"; 11 | 12 | // TODO: remove this from slashing logic of consensus contract 13 | abstract contract DeprecatedSlashBridgeVoting is 14 | HasContracts, 15 | HasValidatorDeprecated, 16 | HasTrustedOrgDeprecated, 17 | HasGovernanceAdminDeprecated 18 | { 19 | /// @dev Mapping from validator address => period index => bridge voting slashed 20 | mapping(address => mapping(uint256 => bool)) private __deprecatedBridgeVotingSlashed; 21 | /// @dev The threshold to slash when a trusted organization does not vote for bridge operators. 22 | uint256 private __deprecatedBridgeVotingThreshold; 23 | /// @dev The amount of RON to slash bridge voting. 24 | uint256 private __deprecatedBridgeVotingSlashAmount; 25 | 26 | /** 27 | * @dev This empty reserved space is put in place to allow future versions to add new 28 | * variables without shifting down storage in the inheritance chain. 29 | */ 30 | uint256[50] private ______gap; 31 | } 32 | -------------------------------------------------------------------------------- /contracts/ronin/staking/StakingCallback.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import "../../interfaces/IProfile.sol"; 5 | import "../../interfaces/staking/IStakingCallback.sol"; 6 | import "./CandidateStaking.sol"; 7 | import "./DelegatorStaking.sol"; 8 | 9 | abstract contract StakingCallback is CandidateStaking, DelegatorStaking, IStakingCallback { 10 | /** 11 | * @dev Requirements: 12 | * - Only Profile contract can call this method. 13 | */ 14 | function execChangeAdminAddr( 15 | address poolId, 16 | address currAdminAddr, 17 | address newAdminAddr 18 | ) external override onlyContract(ContractType.PROFILE) { 19 | PoolDetail storage _pool = _poolDetail[poolId]; 20 | 21 | _pool.wasAdmin[newAdminAddr] = true; 22 | _changeStakeholder({ _pool: _pool, requester: currAdminAddr, newStakeholder: newAdminAddr }); 23 | 24 | _adminOfActivePoolMapping[_pool.__shadowedPoolAdmin] = address(0); 25 | _pool.__shadowedPoolAdmin = newAdminAddr; 26 | 27 | _adminOfActivePoolMapping[newAdminAddr] = poolId; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /contracts/ronin/validator/migrations/NotifiedMigrator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { ConditionalImplementControl } from "../../../extensions/version-control/ConditionalImplementControl.sol"; 5 | import { ErrUnauthorizedCall } from "../../../utils/CommonErrors.sol"; 6 | 7 | contract NotifiedMigrator is ConditionalImplementControl { 8 | address public immutable NOTIFIER; 9 | 10 | constructor( 11 | address proxyStorage, 12 | address prevImpl, 13 | address newImpl, 14 | address notifier 15 | ) payable ConditionalImplementControl(proxyStorage, prevImpl, newImpl) { 16 | NOTIFIER = notifier; 17 | } 18 | 19 | /** 20 | * @dev See {IConditionalImplementControl-selfUpgrade}. 21 | */ 22 | function selfUpgrade() external override onlyDelegateFromProxyStorage { 23 | if (msg.sender != NOTIFIER) revert ErrUnauthorizedCall(msg.sig); 24 | _upgradeTo(NEW_IMPL); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /contracts/types/Types.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.17; 3 | 4 | import { LibTUint256Slot } from "./operations/LibTUint256Slot.sol"; 5 | 6 | type TUint256Slot is bytes32; 7 | 8 | using { 9 | LibTUint256Slot.add, 10 | LibTUint256Slot.sub, 11 | LibTUint256Slot.mul, 12 | LibTUint256Slot.div, 13 | LibTUint256Slot.load, 14 | LibTUint256Slot.store, 15 | LibTUint256Slot.addAssign, 16 | LibTUint256Slot.subAssign, 17 | LibTUint256Slot.preDecrement, 18 | LibTUint256Slot.postDecrement, 19 | LibTUint256Slot.preIncrement, 20 | LibTUint256Slot.postIncrement 21 | } for TUint256Slot global; 22 | -------------------------------------------------------------------------------- /contracts/udvts/Types.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | type TPoolId is address; 5 | 6 | type TConsensus is address; 7 | 8 | using { TPoolIdEq as == } for TPoolId global; 9 | using { TConsensusEq as == } for TConsensus global; 10 | 11 | function TPoolIdEq(TPoolId a, TPoolId b) pure returns (bool) { 12 | return TPoolId.unwrap(a) == TPoolId.unwrap(b); 13 | } 14 | 15 | function TConsensusEq(TConsensus a, TConsensus b) pure returns (bool) { 16 | return TConsensus.unwrap(a) == TConsensus.unwrap(b); 17 | } 18 | -------------------------------------------------------------------------------- /contracts/utils/ContractType.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | enum ContractType { 5 | /* 0 */ 6 | UNKNOWN, 7 | /* 1 */ 8 | PAUSE_ENFORCER, 9 | /* 2 */ 10 | BRIDGE, 11 | /* 3 */ 12 | BRIDGE_TRACKING, 13 | /* 4 */ 14 | GOVERNANCE_ADMIN, 15 | /* 5 */ 16 | MAINTENANCE, 17 | /* 6 */ 18 | SLASH_INDICATOR, 19 | /* 7 */ 20 | STAKING_VESTING, 21 | /* 8 */ 22 | VALIDATOR, 23 | /* 9 */ 24 | STAKING, 25 | /* 10 */ 26 | RONIN_TRUSTED_ORGANIZATION, 27 | /* 11 */ 28 | BRIDGE_MANAGER, 29 | /* 12 */ 30 | BRIDGE_SLASH, 31 | /* 13 */ 32 | BRIDGE_REWARD, 33 | /* 14 */ 34 | FAST_FINALITY_TRACKING, 35 | /* 15 */ 36 | PROFILE 37 | } 38 | -------------------------------------------------------------------------------- /contracts/utils/RoleAccess.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | enum RoleAccess { 5 | /* 0 */ 6 | UNKNOWN, 7 | /* 1 */ 8 | ADMIN, 9 | /* 2 */ 10 | COINBASE, 11 | /* 3 */ 12 | GOVERNOR, 13 | /* 4 */ 14 | CANDIDATE_ADMIN, 15 | /* 5 */ 16 | WITHDRAWAL_MIGRATOR, 17 | /* 6 */ 18 | __DEPRECATED_BRIDGE_OPERATOR, 19 | /* 7 */ 20 | BLOCK_PRODUCER, 21 | /* 8 */ 22 | VALIDATOR_CANDIDATE, 23 | /* 9 */ 24 | CONSENSUS, 25 | /* 10 */ 26 | TREASURY 27 | } 28 | -------------------------------------------------------------------------------- /debug.sh: -------------------------------------------------------------------------------- 1 | # Source (or "dot") the .env file to load environment variables 2 | if [ -f .env ]; then 3 | source .debug.env 4 | else 5 | echo "Error: .debug.env file not found." 6 | fi 7 | 8 | verify_arg="" 9 | extra_argument="" 10 | op_command="" 11 | 12 | for arg in "$@"; do 13 | case $arg in 14 | --trezor) 15 | op_command="" 16 | extra_argument+=trezor@ 17 | ;; 18 | --broadcast) 19 | op_command="op run --env-file="./.env" --" 20 | ;; 21 | --log) 22 | set -- "${@/#--log/}" 23 | extra_argument+=log@ 24 | ;; 25 | *) ;; 26 | esac 27 | done 28 | 29 | # Remove the @ character from the end of extra_argument 30 | extra_argument="${extra_argument%%@}" 31 | 32 | echo Debug Tx... 33 | echo From: ${FROM} 34 | echo To: ${TO} 35 | echo Value: ${VALUE} 36 | echo Calldata: 37 | cast pretty-calldata ${CALLDATA} 38 | calldata=$(cast calldata 'debug(uint256,address,address,uint256,bytes)' ${BLOCK} ${FROM} ${TO} ${VALUE} ${CALLDATA}) 39 | ${op_command} forge script ${verify_arg} --legacy ${@} script/Debug.s.sol --sig 'run(bytes,string)' ${calldata} "${extra_argument}" 40 | -------------------------------------------------------------------------------- /deployments/ethereum/.chainId: -------------------------------------------------------------------------------- 1 | 1 -------------------------------------------------------------------------------- /deployments/goerli-for-devnet/.chainId: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /deployments/goerli/.chainId: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /deployments/ronin-devnet/.chainId: -------------------------------------------------------------------------------- 1 | 2022 -------------------------------------------------------------------------------- /deployments/ronin-mainnet/.chainId: -------------------------------------------------------------------------------- 1 | 2020 -------------------------------------------------------------------------------- /deployments/ronin-testnet/.chainId: -------------------------------------------------------------------------------- 1 | 2021 -------------------------------------------------------------------------------- /docs/CHEATSHEET.md: -------------------------------------------------------------------------------- 1 | # Deployment cheatsheet 2 | 3 | ## Account dependency graph 4 | 5 | ## Gateway 6 | ### Ronin Gateway Proxy 7 | 8 | 1. Setup & Deploy 9 | 10 | - [ ] [`initialize`](https://github.com/axieinfinity/ronin-dpos-contracts/blob/5ef887dba49571c32b7e59e56d8ddde29d1a09c4/contracts/ronin/RoninGatewayV3.sol#L68-L80): this sets initializing data, without validator contract 11 | - [ ] Deploy proxy: Should deploy with private-key based account as admin, for easily setting up the next step 12 | - [ ] [`setValidatorContract`](https://github.com/axieinfinity/ronin-dpos-contracts/blob/5ef887dba49571c32b7e59e56d8ddde29d1a09c4/contracts/ronin/RoninGatewayV3.sol#L103) 13 | - [ ] [`setBridgeTrackingContract`](https://github.com/axieinfinity/ronin-dpos-contracts/blob/95d7e94dea2d33e1835c51aa104114c18ff8df4c/contracts/ronin/RoninGatewayV3.sol#L118) 14 | - [ ] Transfer admin to GA (optional) 15 | 16 | 2. Grant role of minter or top-up initial value for gateway -------------------------------------------------------------------------------- /docs/HACK.md: -------------------------------------------------------------------------------- 1 | # Code structure of the Ronin DPoS contracts repo 2 | 3 | The structure of the repo is as follows. 4 | 5 | ``` 6 | ├── contracts 7 | │ ├── extensions <-- helpers and shared contracts 8 | │ ├── interfaces <-- interfaces 9 | │ ├── libraries <-- libraries 10 | │ ├── mainchain <-- contracts should only deployed on mainchain 11 | │ ├── mocks <-- mock contracts used in tests 12 | │ ├── multi-chains <-- Ronin trusted orgs contracts 13 | │ ├── precompile-usages <-- wrapper for precompiled calls 14 | │ └── ronin <-- contracts should only deployed on Ronin chain 15 | │ ├── slash-indicator <-- slashing and credit score contracts 16 | │ ├── staking <-- pool and staking contracts 17 | │ ├── validator <-- validator set contracts 18 | | └── ... <-- other single file contracts 19 | ├── docs <-- documentation 20 | ├── src <-- deployment scripts 21 | │ ├── deploy <-- hardhat-deploy scripts 22 | │ └── script <-- helpers for deploy scripts 23 | └── test <-- tests 24 | ``` -------------------------------------------------------------------------------- /docs/assets/Deposit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zikc2023/dpos-contract/1f10bf04e805111d4b6648ab9283fe2c7dd270e8/docs/assets/Deposit.png -------------------------------------------------------------------------------- /docs/assets/Governance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zikc2023/dpos-contract/1f10bf04e805111d4b6648ab9283fe2c7dd270e8/docs/assets/Governance.png -------------------------------------------------------------------------------- /docs/assets/Validator Contract Overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zikc2023/dpos-contract/1f10bf04e805111d4b6648ab9283fe2c7dd270e8/docs/assets/Validator Contract Overview.png -------------------------------------------------------------------------------- /docs/assets/Withdrawal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zikc2023/dpos-contract/1f10bf04e805111d4b6648ab9283fe2c7dd270e8/docs/assets/Withdrawal.png -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = 'contracts' 3 | test = 'test/foundry/' 4 | script = 'script' 5 | out = 'out' 6 | optimizer = true 7 | optimizer_runs = 1_000 8 | ffi = true 9 | 10 | libs = ['lib', 'node_modules/@openzeppelin', 'node_modules/hardhat'] 11 | 12 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config 13 | 14 | solc = '0.8.25' 15 | use_literal_content = true 16 | extra_output = ["devdoc", "userdoc", "storagelayout"] 17 | evm_version = 'istanbul' 18 | cache_path = 'cache_foundry' 19 | fs_permissions = [{ access = "read-write", path = "./" }] 20 | 21 | [fmt] 22 | line_length = 120 23 | tab_width = 2 24 | multiline_func_header = 'params_first' 25 | bracket_spacing = true 26 | int_types = 'preserve' 27 | 28 | [profile.ci] 29 | verbosity = 4 30 | 31 | [profile.default.fuzz] 32 | runs = 256 33 | 34 | [profile.intense.fuzz] 35 | runs = 5_000 36 | 37 | [profile.via-ir.fuzz] 38 | runs = 1_000 39 | 40 | [profile.min-solc] 41 | solc_version = "0.8.4" 42 | 43 | [profile.min-solc.fuzz] 44 | runs = 1_000 45 | 46 | [profile.min-solc-via-ir.fuzz] 47 | runs = 1_000 48 | 49 | [rpc_endpoints] 50 | ethereum = "https://eth.llamarpc.com" 51 | goerli = "https://goerli.infura.io/v3/${INFURA_API_KEY}" 52 | ronin-mainnet = "https://api-archived.roninchain.com/rpc" 53 | ronin-testnet = "https://saigon-archive.roninchain.com/rpc" 54 | ronin-devnet = "https://hcm-rpc.skymavis.one/rpc" 55 | localhost = "http://localhost:8545" 56 | ronin-testnet-shadow = "http://34.27.172.168:8545" 57 | ronin-mainnet-shadow = "http://35.225.161.81:8545" 58 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | 3 | ### Contract changes 4 | 5 | The table below shows the following info: 6 | - **Logic**: the logic is changed. 7 | - **ABI**: the ABI is changed. 8 | - **Init data**: new storage field is declared and needs initializing. 9 | - **Dependent**: needs to be changed due to changes in other contracts. 10 | 11 | | **Contract name** | **Logic** | **ABI** | **Init data** | **Dependent** | 12 | |-------------------------|:---------:|:-------:|:-------------:|:-------------:| 13 | | FastFinalityTracking | | | | | 14 | | GovernanceAdmin | | | | | 15 | | Maintenance | | | | | 16 | | Profile | | | | | 17 | | SlashIndicator | | | | | 18 | | Staking | | | | | 19 | | StakingVesting | | | | | 20 | | ValidatorSet | | | | | 21 | 22 | ### Checklist 23 | - [ ] I have chosen the base of the PR to the `release/**` branch. 24 | - [ ] I have named the PR following the format of `[contract_name] what_is_changed`, where `contract_name` is the list of changed contracts, separated by `|`, or is `*` if there is changed in more than 3 contracts 25 | - [ ] I have ticked in the `Contract changes` table to guide the deployer which contracts to be upgraded. 26 | - [ ] I have clearly commented on all the main functions following the [NatSpec Format](https://docs.soliditylang.org/en/v0.8.0/natspec-format.html) 27 | - [ ] The box that allows repo maintainers to update this PR is checked 28 | - [ ] I tested locally to make sure this feature/fix works 29 | -------------------------------------------------------------------------------- /remappings.txt: -------------------------------------------------------------------------------- 1 | ds-test/=lib/forge-std/lib/ds-test/src/ 2 | forge-std/=lib/forge-std/src/ 3 | @openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/ 4 | hardhat/=./node_modules/hardhat/ 5 | @ronin/contracts/=./contracts/ 6 | @ronin/test/=./test/foundry/ 7 | @prb/test/=lib/prb-test/src/ 8 | @prb/math/=lib/prb-math/ 9 | solady/=lib/solady/src 10 | foundry-deployment-kit/=lib/foundry-deployment-kit/script 11 | contract-libs/=lib/contract-libs/src -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | source lib/foundry-deployment-kit/run.sh 2 | -------------------------------------------------------------------------------- /script/20231003-rep-002-rep-003/20231003_REP002AndREP003_ETH.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { MainchainBridgeManager } from "@ronin/contracts/mainchain/MainchainBridgeManager.sol"; 6 | import { MainchainGatewayV3 } from "@ronin/contracts/mainchain/MainchainGatewayV3.sol"; 7 | import { TransparentUpgradeableProxyV2 } from "@ronin/contracts/extensions/TransparentUpgradeableProxyV2.sol"; 8 | import { MappedTokenConsumer } from "@ronin/contracts/interfaces/consumers/MappedTokenConsumer.sol"; 9 | import { RoninMigration, DefaultNetwork } from "../RoninMigration.s.sol"; 10 | import { Contract } from "script/utils/Contract.sol"; 11 | 12 | contract Simulation__20231003_UpgradeREP002AndREP003_ETH is RoninMigration, MappedTokenConsumer { 13 | RoninGovernanceAdmin internal _mainchainGovernanceAdmin; 14 | MainchainGatewayV3 internal _mainchainGatewayV3; 15 | MainchainBridgeManager internal _mainchainBridgeManager; 16 | 17 | function run() public virtual { 18 | _mainchainGatewayV3 = MainchainGatewayV3(config.getAddressFromCurrentNetwork(Contract.MainchainGatewayV3.key())); 19 | _mainchainBridgeManager = 20 | MainchainBridgeManager(config.getAddressFromCurrentNetwork(Contract.MainchainBridgeManager.key())); 21 | _mainchainGovernanceAdmin = 22 | RoninGovernanceAdmin(config.getAddressFromCurrentNetwork(Contract.MainchainGovernanceAdmin.key())); 23 | 24 | _upgradeProxy( 25 | Contract.MainchainGatewayV3.key(), 26 | abi.encodeCall(MainchainGatewayV3.initializeV2, (address(_mainchainBridgeManager))) 27 | ); 28 | vm.startPrank(address(_mainchainGovernanceAdmin)); 29 | TransparentUpgradeableProxyV2(payable(address(_mainchainGatewayV3))).changeAdmin(address(_mainchainBridgeManager)); 30 | vm.stopPrank(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /script/20231003-rep-002-rep-003/20231003_REP002AndREP003_RON_NonConditional_Wrapup2Periods.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { TConsensus } from "@ronin/contracts/udvts/Types.sol"; 5 | import "./20231003_REP002AndREP003_RON_NonConditional.s.sol"; 6 | 7 | contract Simulation__20231003_UpgradeREP002AndREP003_RON_NonConditional_Wrapup2Periods is 8 | Simulation__20231003_UpgradeREP002AndREP003_RON_NonConditional 9 | { 10 | function run() public virtual override { 11 | super.run(); 12 | 13 | // submit block reward for one epoch 14 | vm.warp(block.timestamp + 3 seconds); 15 | vm.roll(block.number + 1); 16 | vm.prank(block.coinbase); 17 | _validatorSet.submitBlockReward{ value: 1_000_000 }(); 18 | 19 | TConsensus[] memory finalityList = new TConsensus[](1); 20 | finalityList[0] = TConsensus.wrap(block.coinbase); 21 | vm.prank(block.coinbase); 22 | _fastFinalityTracking.recordFinality(finalityList); 23 | 24 | // wrap up period for second day after upgrade 25 | _fastForwardToNextDay(); 26 | _wrapUpEpoch(); 27 | 28 | // // test `RoninValidatorSet` functionality 29 | // _fastForwardToNextDay(); 30 | // _wrapUpEpoch(); 31 | 32 | // // test `RoninGatewayV3` functionality 33 | // _depositFor("after-upgrade-user"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /script/20231019-recover-fund/contracts/BridgeTrackingRecoveryLogic.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { IBridgeReward } from "@ronin/contracts/interfaces/bridge/IBridgeReward.sol"; 5 | import { ContractType, BridgeTracking } from "@ronin/contracts/ronin/gateway/BridgeTracking.sol"; 6 | 7 | contract BridgeTrackingRecoveryLogic is BridgeTracking { 8 | event TotalInternalTxCount(uint indexed count); 9 | 10 | function recoverFund() external onlyAdmin { 11 | IBridgeReward bridgeRewardContract = IBridgeReward(0x1C952D6717eBFd2E92E5f43Ef7C1c3f7677F007D); 12 | address receiver = msg.sender; 13 | 14 | address[] memory operators = new address[](1); 15 | uint256[] memory ballots = new uint256[](1); 16 | operators[0] = receiver; 17 | ballots[0] = 1; 18 | uint256 period = bridgeRewardContract.getLatestRewardedPeriod() + 1; 19 | uint256 count; 20 | while (address(bridgeRewardContract).balance > 1 ether) { 21 | bridgeRewardContract.execSyncReward(operators, ballots, 1, 1, period); 22 | period++; 23 | ++count; 24 | } 25 | 26 | emit TotalInternalTxCount(count); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/FastFinalityTrackingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { FastFinalityTracking } from "@ronin/contracts/ronin/fast-finality/FastFinalityTracking.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract FastFinalityTrackingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (FastFinalityTracking instance) { 12 | instance = FastFinalityTracking(_deployProxy(Contract.FastFinalityTracking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/MaintenanceDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { Maintenance } from "@ronin/contracts/ronin/Maintenance.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract MaintenanceDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Maintenance instance) { 12 | instance = Maintenance(_deployProxy(Contract.Maintenance.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/ProfileDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Profile } from "@ronin/contracts/ronin/profile/Profile.sol"; 5 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 6 | import { Contract } from "script/utils/Contract.sol"; 7 | 8 | contract ProfileDeploy is DevnetMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { } 10 | 11 | function run() public returns (Profile instance) { 12 | instance = Profile(_deployProxy(Contract.Profile.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/RoninGovernanceAdminDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { ISharedArgument, DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninGovernanceAdminDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { 10 | ISharedArgument.SharedParameter memory param = devnetConfig.sharedArguments(); 11 | 12 | args = abi.encode( 13 | block.chainid, 14 | config.getAddressFromCurrentNetwork(Contract.RoninTrustedOrganization.key()), 15 | config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()), 16 | param.proposalExpiryDuration 17 | ); 18 | } 19 | 20 | function run() public virtual returns (RoninGovernanceAdmin instance) { 21 | instance = RoninGovernanceAdmin(_deployImmutable(Contract.RoninGovernanceAdmin.key())); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/RoninTrustedOrganizationDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { RoninTrustedOrganization } from "@ronin/contracts/multi-chains/RoninTrustedOrganization.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninTrustedOrganizationDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninTrustedOrganization instance) { 12 | instance = RoninTrustedOrganization(_deployProxy(Contract.RoninTrustedOrganization.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/RoninValidatorSetDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninValidatorSet } from "@ronin/contracts/ronin/validator/RoninValidatorSet.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninValidatorSetDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninValidatorSet instance) { 12 | instance = RoninValidatorSet(_deployProxy(Contract.RoninValidatorSet.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/SlashIndicatorDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { SlashIndicator } from "@ronin/contracts/ronin/slash-indicator/SlashIndicator.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract SlashIndicatorDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (SlashIndicator instance) { 12 | instance = SlashIndicator(_deployProxy(Contract.SlashIndicator.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/StakingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Staking } from "@ronin/contracts/ronin/staking/Staking.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract StakingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Staking instance) { 12 | instance = Staking(_deployProxy(Contract.Staking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231130-deploy-devnet/contracts/StakingVestingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { StakingVesting } from "@ronin/contracts/ronin/StakingVesting.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract StakingVestingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (StakingVesting instance) { 12 | instance = StakingVesting(_deployProxy(Contract.StakingVesting.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/FastFinalityTrackingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { FastFinalityTracking } from "@ronin/contracts/ronin/fast-finality/FastFinalityTracking.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract FastFinalityTrackingDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (FastFinalityTracking instance) { 12 | instance = FastFinalityTracking(_deployProxy(Contract.FastFinalityTracking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/MaintenanceDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { Maintenance } from "@ronin/contracts/ronin/Maintenance.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract MaintenanceDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Maintenance instance) { 12 | instance = Maintenance(_deployProxy(Contract.Maintenance.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/ProfileDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Profile } from "@ronin/contracts/ronin/profile/Profile.sol"; 5 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 6 | import { Contract } from "script/utils/Contract.sol"; 7 | 8 | contract ProfileDeploy is TestnetMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { } 10 | 11 | function run() public returns (Profile instance) { 12 | instance = Profile(_deployProxy(Contract.Profile.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/RoninGovernanceAdminDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { ISharedArgument, TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract RoninGovernanceAdminDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { 10 | ISharedArgument.SharedParameter memory param = testnetConfig.sharedArguments(); 11 | 12 | args = abi.encode( 13 | block.chainid, 14 | config.getAddressFromCurrentNetwork(Contract.RoninTrustedOrganization.key()), 15 | config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()), 16 | param.expiryDuration 17 | ); 18 | } 19 | 20 | function run() public virtual returns (RoninGovernanceAdmin instance) { 21 | instance = RoninGovernanceAdmin(_deployImmutable(Contract.RoninGovernanceAdmin.key())); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/RoninTrustedOrganizationDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { RoninTrustedOrganization } from "@ronin/contracts/multi-chains/RoninTrustedOrganization.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract RoninTrustedOrganizationDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninTrustedOrganization instance) { 12 | instance = RoninTrustedOrganization(_deployProxy(Contract.RoninTrustedOrganization.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/RoninValidatorSetDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninValidatorSet } from "@ronin/contracts/ronin/validator/RoninValidatorSet.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract RoninValidatorSetDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninValidatorSet instance) { 12 | instance = RoninValidatorSet(_deployProxy(Contract.RoninValidatorSet.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/SlashIndicatorDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { SlashIndicator } from "@ronin/contracts/ronin/slash-indicator/SlashIndicator.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract SlashIndicatorDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (SlashIndicator instance) { 12 | instance = SlashIndicator(_deployProxy(Contract.SlashIndicator.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/StakingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Staking } from "@ronin/contracts/ronin/staking/Staking.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract StakingDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Staking instance) { 12 | instance = Staking(_deployProxy(Contract.Staking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20231212-deploy-testnet/contracts/StakingVestingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { StakingVesting } from "@ronin/contracts/ronin/StakingVesting.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { TestnetMigration } from "../TestnetMigration.s.sol"; 7 | 8 | contract StakingVestingDeploy is TestnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (StakingVesting instance) { 12 | instance = StakingVesting(_deployProxy(Contract.StakingVesting.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/FastFinalityTrackingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { FastFinalityTracking } from "@ronin/contracts/ronin/fast-finality/FastFinalityTracking.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract FastFinalityTrackingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (FastFinalityTracking instance) { 12 | instance = FastFinalityTracking(_deployProxy(Contract.FastFinalityTracking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/MaintenanceDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { Maintenance } from "@ronin/contracts/ronin/Maintenance.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract MaintenanceDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Maintenance instance) { 12 | instance = Maintenance(_deployProxy(Contract.Maintenance.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/ProfileDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Profile } from "@ronin/contracts/ronin/profile/Profile.sol"; 5 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 6 | import { Contract } from "script/utils/Contract.sol"; 7 | 8 | contract ProfileDeploy is DevnetMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { } 10 | 11 | function run() public returns (Profile instance) { 12 | instance = Profile(_deployProxy(Contract.Profile.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/RoninGovernanceAdminDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { ISharedArgument, DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninGovernanceAdminDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { 10 | ISharedArgument.SharedParameter memory param = devnetConfig.sharedArguments(); 11 | 12 | args = abi.encode( 13 | block.chainid, 14 | config.getAddressFromCurrentNetwork(Contract.RoninTrustedOrganization.key()), 15 | config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()), 16 | param.proposalExpiryDuration 17 | ); 18 | } 19 | 20 | function run() public virtual returns (RoninGovernanceAdmin instance) { 21 | instance = RoninGovernanceAdmin(_deployImmutable(Contract.RoninGovernanceAdmin.key())); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/RoninTrustedOrganizationDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { RoninTrustedOrganization } from "@ronin/contracts/multi-chains/RoninTrustedOrganization.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninTrustedOrganizationDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninTrustedOrganization instance) { 12 | instance = RoninTrustedOrganization(_deployProxy(Contract.RoninTrustedOrganization.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/RoninValidatorSetDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninValidatorSet } from "@ronin/contracts/ronin/validator/RoninValidatorSet.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract RoninValidatorSetDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninValidatorSet instance) { 12 | instance = RoninValidatorSet(_deployProxy(Contract.RoninValidatorSet.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/SlashIndicatorDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { SlashIndicator } from "@ronin/contracts/ronin/slash-indicator/SlashIndicator.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract SlashIndicatorDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (SlashIndicator instance) { 12 | instance = SlashIndicator(_deployProxy(Contract.SlashIndicator.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/StakingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Staking } from "@ronin/contracts/ronin/staking/Staking.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract StakingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Staking instance) { 12 | instance = Staking(_deployProxy(Contract.Staking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20233011-deploy-devnet/contracts/StakingVestingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { StakingVesting } from "@ronin/contracts/ronin/StakingVesting.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DevnetMigration } from "../DevnetMigration.s.sol"; 7 | 8 | contract StakingVestingDeploy is DevnetMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (StakingVesting instance) { 12 | instance = StakingVesting(_deployProxy(Contract.StakingVesting.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/20240220-miko-hardfork/20240220_p2A_mainnet_Miko_propose_proposal.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import "./20240220_p2_Miko_build_proposal.s.sol"; 5 | 6 | contract Proposal__20240220_MikoHardfork_ProposeProposal is Proposal__20240220_MikoHardfork_BuildProposal { 7 | using LibProxy for *; 8 | using StdStyle for *; 9 | using ArrayReplaceLib for *; 10 | 11 | /** 12 | * See `README.md` 13 | */ 14 | function run() public virtual override onlyOn(DefaultNetwork.RoninMainnet.key()) { 15 | Proposal__Base_20240220_MikoHardfork.run(); 16 | 17 | _run_unchained(); 18 | } 19 | 20 | function _run_unchained() internal virtual { 21 | Proposal.ProposalDetail memory proposal = _buildFinalProposal(); 22 | _proposeProposal(roninGovernanceAdmin, trustedOrgContract, proposal, SKY_MAVIS_GOVERNOR); 23 | 24 | CONFIG.setPostCheckingStatus(true); 25 | _voteProposalUntilSuccess(roninGovernanceAdmin, trustedOrgContract, proposal); 26 | CONFIG.setPostCheckingStatus(false); 27 | 28 | CONFIG.setAddress(network(), Contract.RoninGovernanceAdmin.key(), address(_newGA)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /script/20240220-miko-hardfork/20240220_p2B_shadow_Miko_propose_proposal.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import "./20240220_p2_Miko_build_proposal.s.sol"; 5 | 6 | contract Proposal__20240220_MikoHardfork_ProposeProposal is Proposal__20240220_MikoHardfork_BuildProposal { 7 | using LibProxy for *; 8 | using StdStyle for *; 9 | using ArrayReplaceLib for *; 10 | 11 | /** 12 | * See `README.md` 13 | */ 14 | function run() public virtual override onlyOn(DefaultNetwork.RoninMainnet.key()) { 15 | Proposal__Base_20240220_MikoHardfork.run(); 16 | 17 | _run_unchained(); 18 | } 19 | 20 | function _run_unchained() internal virtual { 21 | Proposal.ProposalDetail memory proposal = _buildFinalProposal(); 22 | _proposeProposal(roninGovernanceAdmin, trustedOrgContract, proposal, address(0)); 23 | _voteProposalUntilSuccess(roninGovernanceAdmin, trustedOrgContract, proposal); 24 | 25 | CONFIG.setAddress(network(), Contract.RoninGovernanceAdmin.key(), address(_newGA)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /script/20240220-miko-hardfork/ArrayReplaceLib.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import "forge-std/console2.sol"; 5 | 6 | library ArrayReplaceLib { 7 | function replace(uint[] memory src, uint[] memory dst, uint where) internal pure returns (uint256[] memory out) { 8 | require(dst.length + where <= src.length, "ArrayReplaceLib: invalid input"); 9 | out = new uint[](src.length); 10 | for (uint i; i < where; i++) { 11 | out[i] = src[i]; 12 | } 13 | 14 | for (uint i = 0; i < dst.length; i++) { 15 | out[where++] = dst[i]; 16 | } 17 | } 18 | 19 | function replace(bytes[] memory src, bytes[] memory dst, uint where) internal pure returns (bytes[] memory out) { 20 | require(dst.length + where <= src.length, "ArrayReplaceLib: invalid input"); 21 | out = new bytes[](src.length); 22 | for (uint i; i < where; i++) { 23 | out[i] = src[i]; 24 | } 25 | 26 | for (uint i = 0; i < dst.length; i++) { 27 | out[where++] = dst[i]; 28 | } 29 | } 30 | 31 | function replace(address[] memory src, address[] memory dst, uint where) internal pure returns (address[] memory out) { 32 | require(dst.length + where <= src.length, "ArrayReplaceLib: invalid input"); 33 | 34 | out = new address[](src.length); 35 | for (uint i; i < where; i++) { 36 | out[i] = src[i]; 37 | } 38 | 39 | for (uint i = 0; i < dst.length; i++) { 40 | out[where++] = dst[i]; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /script/20240220-miko-hardfork/README.md: -------------------------------------------------------------------------------- 1 | Miko Hardfork Proposal 2 | ================== 3 | 4 | # Description 5 | 6 | Before the proposal, the following items will be prepared: 7 | - A1. An address called `doctor`, which is the temporary admin of BridgeTracking 8 | - A2. A new Governance Admin (GANew) will be deployed 9 | - A3. Snapshot list for `migrateWasAdmin()` 10 | 11 | The proposal will do the following tasks: 12 | - B1. Change admin of BridgeTracking to `doctor` (See the After part) 13 | - B2. Deploy all DPoS contracts and upgrade all DPoS contracts 14 | - B3. Reinitialize all DPoS contracts 15 | - C1. The `MIGRATOR_ROLE` in the Staking will migrate the list of `wasAdmin`. 16 | - B4. Replace StableNode's governor address 17 | - B5. Change governance admin of all contracts to (GANew) 18 | 19 | After the proposal is executed, the following scripts will be run: 20 | - C2. The `doctor` will withdraw the locked fund. 21 | - C3. The `doctor` will upgrade the Bridge Tracking contract to remove the recovery method. 22 | - C4. The `doctor` will transfer admin to BridgeManager. 23 | - C5. The `doctor` will transfer all fund to Andy's trezor. 24 | - C6. The `migrator` disable the migration method in Staking contract. 25 | 26 | # TODO and To-fill config 27 | 28 | - See file [MikoConfig.s.sol](./MikoConfig.s.sol) and fill the `TODO` marks. 29 | - Uncomment [StableNode change](./20240220-miko-hardfork/20240220_p2_Miko_build_proposal.s.sol). 30 | - Set `setBroadcastDisableStatus(true)` to only activating part in the [final script](./20240220_Full_mainnet_Miko_Hardfork.s.sol). 31 | 32 | # Commands 33 | 34 | ## Full-flow simulation 35 | ``` 36 | # Mainnet 37 | ./run.sh -f ronin-mainnet script/20240220-miko-hardfork/20240220_Full_shadow_Miko_Hardfork.s.sol -vvvv --legacy 38 | ``` -------------------------------------------------------------------------------- /script/contracts/BridgeRewardDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { BridgeReward } from "@ronin/contracts/ronin/gateway/BridgeReward.sol"; 5 | import { RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract BridgeRewardDeploy is RoninMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory) { } 10 | 11 | function run() public returns (BridgeReward) { 12 | return BridgeReward(_deployProxy(Contract.BridgeReward.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/contracts/BridgeSlashDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { BridgeSlash } from "@ronin/contracts/ronin/gateway/BridgeSlash.sol"; 5 | import { RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract BridgeSlashDeploy is RoninMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory) { } 10 | 11 | function run() public returns (BridgeSlash) { 12 | return BridgeSlash(_deployProxy(Contract.BridgeSlash.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/contracts/FastFinalityTrackingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { FastFinalityTracking } from "@ronin/contracts/ronin/fast-finality/FastFinalityTracking.sol"; 5 | import { RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract FastFinalityTrackingDeploy is RoninMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { 10 | args = abi.encodeCall( 11 | FastFinalityTracking.initialize, config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()) 12 | ); 13 | } 14 | 15 | function run() public returns (FastFinalityTracking) { 16 | return FastFinalityTracking(_deployProxy(Contract.FastFinalityTracking.key())); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /script/contracts/HardForkRoninGovernanceAdminDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { ISharedArgument, RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract HardForkRoninGovernanceAdminDeploy is RoninMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { 10 | ISharedArgument.SharedParameter memory param = config.sharedArguments(); 11 | 12 | args = abi.encode( 13 | block.chainid, 14 | config.getAddressFromCurrentNetwork(Contract.RoninTrustedOrganization.key()), 15 | config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()), 16 | param.expiryDuration 17 | ); 18 | } 19 | 20 | function run() public returns (RoninGovernanceAdmin) { 21 | return RoninGovernanceAdmin(_deployImmutable(Contract.HardForkRoninGovernanceAdmin.key())); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /script/contracts/NotifiedMigratorUpgrade.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { LibProxy } from "foundry-deployment-kit/libraries/LibProxy.sol"; 5 | import { ConditionalImplementControl } from 6 | "@ronin/contracts/extensions/version-control/ConditionalImplementControl.sol"; 7 | import { RoninMigration } from "../RoninMigration.s.sol"; 8 | import { Contract } from "../utils/Contract.sol"; 9 | 10 | contract NotifiedMigratorUpgrade is RoninMigration { 11 | using LibProxy for address payable; 12 | 13 | function _defaultArguments() internal virtual override returns (bytes memory) { } 14 | 15 | function run(Contract contractType, bytes[] calldata callDatas) public virtual returns (address payable) { 16 | address payable proxy = config.getAddressFromCurrentNetwork(contractType.key()); 17 | address proxyAdmin = proxy.getProxyAdmin(); 18 | address prevImpl = proxy.getProxyImplementation(); 19 | address newImpl = _deployLogic(contractType.key()); 20 | address notifier = config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()); 21 | (address switcher,) = _deployRaw( 22 | config.getContractName(Contract.NotifiedMigrator.key()), abi.encode(proxy, prevImpl, newImpl, notifier) 23 | ); 24 | _upgradeRaw(proxyAdmin, proxy, switcher, abi.encodeCall(ConditionalImplementControl.setCallDatas, (callDatas))); 25 | return proxy; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /script/contracts/ProfileDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Profile } from "@ronin/contracts/ronin/profile/Profile.sol"; 5 | import { RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract ProfileDeploy is RoninMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { 10 | args = abi.encodeCall(Profile.initialize, config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key())); 11 | } 12 | 13 | function run() public returns (Profile) { 14 | return Profile(_deployProxy(Contract.Profile.key())); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /script/contracts/TemporalRoninTrustedOrganizationDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninTrustedOrganization } from "@ronin/contracts/multi-chains/RoninTrustedOrganization.sol"; 5 | import { ISharedArgument, RoninMigration } from "../RoninMigration.s.sol"; 6 | import { Contract } from "../utils/Contract.sol"; 7 | 8 | contract TemporalRoninTrustedOrganizationDeploy is RoninMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { 10 | ISharedArgument.SharedParameter memory param = config.sharedArguments(); 11 | args = abi.encodeCall(RoninTrustedOrganization.initialize, (param.trustedOrgs, param.num, param.denom)); 12 | } 13 | 14 | function run() public returns (RoninTrustedOrganization) { 15 | return RoninTrustedOrganization(_deployProxy(Contract.TemporalRoninTrustedOrganization.key())); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/FastFinalityTrackingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { FastFinalityTracking } from "@ronin/contracts/ronin/fast-finality/FastFinalityTracking.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract FastFinalityTrackingDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (FastFinalityTracking instance) { 12 | instance = FastFinalityTracking(_deployProxy(Contract.FastFinalityTracking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/MaintenanceDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { Maintenance } from "@ronin/contracts/ronin/Maintenance.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract MaintenanceDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Maintenance instance) { 12 | instance = Maintenance(_deployProxy(Contract.Maintenance.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/ProfileDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Profile } from "@ronin/contracts/ronin/profile/Profile.sol"; 5 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 6 | import { Contract } from "script/utils/Contract.sol"; 7 | 8 | contract ProfileDeploy is DPoSMigration { 9 | function _defaultArguments() internal view override returns (bytes memory args) { } 10 | 11 | function run() public returns (Profile instance) { 12 | instance = Profile(_deployProxy(Contract.Profile.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/RoninGovernanceAdminDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { ISharedArgument, DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract RoninGovernanceAdminDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { 10 | ISharedArgument.GovernanceAdminParam memory param = cfg.sharedArguments().governanceAdmin; 11 | 12 | args = abi.encode( 13 | block.chainid, 14 | config.getAddressFromCurrentNetwork(Contract.RoninTrustedOrganization.key()), 15 | config.getAddressFromCurrentNetwork(Contract.RoninValidatorSet.key()), 16 | param.proposalExpiryDuration 17 | ); 18 | } 19 | 20 | function run() public virtual returns (RoninGovernanceAdmin instance) { 21 | instance = RoninGovernanceAdmin(_deployImmutable(Contract.RoninGovernanceAdmin.key())); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/RoninTrustedOrganizationDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Contract } from "script/utils/Contract.sol"; 5 | import { RoninTrustedOrganization } from "@ronin/contracts/multi-chains/RoninTrustedOrganization.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract RoninTrustedOrganizationDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninTrustedOrganization instance) { 12 | instance = RoninTrustedOrganization(_deployProxy(Contract.RoninTrustedOrganization.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/RoninValidatorSetDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { RoninValidatorSet } from "@ronin/contracts/ronin/validator/RoninValidatorSet.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract RoninValidatorSetDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (RoninValidatorSet instance) { 12 | instance = RoninValidatorSet(_deployProxy(Contract.RoninValidatorSet.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/SlashIndicatorDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { SlashIndicator } from "@ronin/contracts/ronin/slash-indicator/SlashIndicator.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract SlashIndicatorDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (SlashIndicator instance) { 12 | instance = SlashIndicator(_deployProxy(Contract.SlashIndicator.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/StakingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { Staking } from "@ronin/contracts/ronin/staking/Staking.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract StakingDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (Staking instance) { 12 | instance = Staking(_deployProxy(Contract.Staking.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/deploy-dpos/contracts/StakingVestingDeploy.s.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { StakingVesting } from "@ronin/contracts/ronin/StakingVesting.sol"; 5 | import { Contract } from "script/utils/Contract.sol"; 6 | import { DPoSMigration } from "../DPoSMigration.s.sol"; 7 | 8 | contract StakingVestingDeploy is DPoSMigration { 9 | function _defaultArguments() internal virtual override returns (bytes memory args) { } 10 | 11 | function run() public virtual returns (StakingVesting instance) { 12 | instance = StakingVesting(_deployProxy(Contract.StakingVesting.key())); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /script/interfaces/ISharedArgument.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.19; 3 | 4 | import { IRoninTrustedOrganization } from "@ronin/contracts/interfaces/IRoninTrustedOrganization.sol"; 5 | import { IGeneralConfig } from "foundry-deployment-kit/interfaces/IGeneralConfig.sol"; 6 | 7 | interface ISharedArgument is IGeneralConfig { 8 | struct SharedParameter { 9 | // RoninTrustedOrganization 10 | IRoninTrustedOrganization.TrustedOrganization[] trustedOrgs; 11 | uint256 num; 12 | uint256 denom; 13 | // RoninGovernanceAdmin 14 | uint256 expiryDuration; 15 | } 16 | 17 | function sharedArguments() external view returns (SharedParameter memory param); 18 | } 19 | -------------------------------------------------------------------------------- /src/dashboard/dashboard-helper.ts: -------------------------------------------------------------------------------- 1 | import { Address, Deployment } from 'hardhat-deploy/dist/types'; 2 | import { DEFAULT_ADDRESS } from '../utils'; 3 | import { ethers } from 'hardhat'; 4 | 5 | export function isCorrectAdmin(admin: Address, expectedAdmin: Address): boolean { 6 | if (expectedAdmin == DEFAULT_ADDRESS) return false; 7 | return admin.toLocaleLowerCase() == expectedAdmin.toLocaleLowerCase(); 8 | } 9 | 10 | export const getAdminOfProxy = async (address: Address): Promise => { 11 | const ADMIN_SLOT = '0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103'; 12 | const slotValue = await ethers.provider.getStorageAt(address, ADMIN_SLOT); 13 | return ethers.utils.hexStripZeros(slotValue); 14 | }; 15 | 16 | export interface ProxyManagementInfo { 17 | deployment: Deployment | null; 18 | address?: Address; 19 | admin?: Address; 20 | expectedAdmin?: Address; 21 | isCorrect?: Boolean; 22 | } 23 | -------------------------------------------------------------------------------- /src/deploy/calculate-address/calculate-bridge.ts: -------------------------------------------------------------------------------- 1 | import { ethers, network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { generalRoninConf, roninchainNetworks, mainchainNetworks, generalMainchainConf } from '../../configs/config'; 5 | import { Network } from '../../utils'; 6 | import { calculateAddress } from './helper'; 7 | 8 | const deploy = async ({ getNamedAccounts }: HardhatRuntimeEnvironment) => { 9 | const { deployer } = await getNamedAccounts(); 10 | let nonce = await ethers.provider.getTransactionCount(deployer); 11 | 12 | if (roninchainNetworks.includes(network.name!)) { 13 | generalRoninConf[network.name] = { 14 | ...generalRoninConf[network.name], 15 | bridgeTrackingContract: calculateAddress(deployer, nonce++), 16 | bridgeSlashContract: calculateAddress(deployer, nonce++), 17 | bridgeRewardContract: calculateAddress(deployer, nonce++), 18 | bridgeManagerContract: calculateAddress(deployer, nonce++), 19 | }; 20 | } 21 | 22 | if (mainchainNetworks.includes(network.name!)) { 23 | generalMainchainConf[network.name] = { 24 | ...generalMainchainConf[network.name], 25 | bridgeManagerContract: calculateAddress(deployer, nonce++), 26 | }; 27 | } 28 | 29 | // Only for local 30 | if ([Network.Local.toString()].includes(network.name)) { 31 | generalMainchainConf[network.name].bridgeContract = calculateAddress(deployer, nonce++).address; 32 | } 33 | }; 34 | 35 | deploy.tags = ['_HelperBridgeCalculate']; 36 | deploy.dependencies = [ 37 | 'BridgeTrackingLogic', 38 | 'BridgeSlashLogic', 39 | 'BridgeRewardLogic', 40 | 'MainchainGatewayV3Logic', 41 | 'RoninGatewayV3Logic', 42 | ]; 43 | 44 | export default deploy; 45 | -------------------------------------------------------------------------------- /src/deploy/calculate-address/calculate-dpos.ts: -------------------------------------------------------------------------------- 1 | import { ethers, network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { generalRoninConf, roninchainNetworks } from '../../configs/config'; 5 | import { calculateAddress } from './helper'; 6 | 7 | const deploy = async ({ getNamedAccounts }: HardhatRuntimeEnvironment) => { 8 | const { deployer } = await getNamedAccounts(); 9 | let nonce = await ethers.provider.getTransactionCount(deployer); 10 | 11 | if (roninchainNetworks.includes(network.name!)) { 12 | generalRoninConf[network.name] = { 13 | ...generalRoninConf[network.name], 14 | governanceAdmin: calculateAddress(deployer, nonce++), 15 | fastFinalityTrackingContract: calculateAddress(deployer, nonce++), 16 | roninTrustedOrganizationContract: calculateAddress(deployer, nonce++), 17 | maintenanceContract: calculateAddress(deployer, nonce++), 18 | stakingVestingContract: calculateAddress(deployer, nonce++), 19 | slashIndicatorContract: calculateAddress(deployer, nonce++), 20 | stakingContract: calculateAddress(deployer, nonce++), 21 | validatorContract: calculateAddress(deployer, nonce++), 22 | profileContract: calculateAddress(deployer, nonce++), 23 | }; 24 | } 25 | 26 | // console.debug('Nonce calculation for deployments...'); 27 | // console.table(generalRoninConf[network.name]); 28 | }; 29 | 30 | deploy.tags = ['_HelperDposCalculate']; 31 | deploy.dependencies = [ 32 | 'FastFinalityTrackingLogic', 33 | 'MaintenanceLogic', 34 | 'StakingVestingLogic', 35 | 'SlashIndicatorLogic', 36 | 'StakingLogic', 37 | 'RoninValidatorSetLogic', 38 | 'RoninTrustedOrganizationLogic', 39 | 'ProfileLogic', 40 | ]; 41 | 42 | export default deploy; 43 | -------------------------------------------------------------------------------- /src/deploy/calculate-address/helper.ts: -------------------------------------------------------------------------------- 1 | import { ethers } from 'ethers'; 2 | 3 | export const calculateAddress = (from: string, nonce: number) => ({ 4 | nonce, 5 | address: ethers.utils.getContractAddress({ from, nonce }), 6 | }); 7 | -------------------------------------------------------------------------------- /src/deploy/logic/bridge-reward.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('BridgeRewardLogic', { 15 | contract: 'BridgeReward', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['BridgeRewardLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/bridge-slash.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('BridgeSlashLogic', { 15 | contract: 'BridgeSlash', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['BridgeSlashLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/bridge-tracking.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('BridgeTrackingLogic', { 15 | contract: 'BridgeTracking', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['BridgeTrackingLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/fast-finality-tracking.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('FastFinalityTrackingLogic', { 15 | contract: 'FastFinalityTracking', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['FastFinalityTrackingLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/mainchain-gateway-pause-enforcer-logic.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { mainchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!mainchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('MainchainGatewayPauseEnforcerLogic', { 15 | contract: 'PauseEnforcer', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['MainchainGatewayPauseEnforcerLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/mainchain-gateway-v3.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { mainchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!mainchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('MainchainGatewayV3Logic', { 15 | contract: 'MainchainGatewayV3', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['MainchainGatewayV3Logic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/maintenance.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('MaintenanceLogic', { 15 | contract: 'Maintenance', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['MaintenanceLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/profile.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | import { Network } from '../../utils'; 6 | 7 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 8 | if (!roninchainNetworks.includes(network.name!)) { 9 | return; 10 | } 11 | 12 | const { deploy } = deployments; 13 | const { deployer } = await getNamedAccounts(); 14 | 15 | let contractToDeploy; 16 | switch (network.name!) { 17 | case Network.Mainnet: 18 | contractToDeploy = 'Profile_Mainnet'; 19 | default: 20 | contractToDeploy = 'Profile'; 21 | } 22 | 23 | await deploy('ProfileLogic', { 24 | contract: contractToDeploy, 25 | from: deployer, 26 | log: true, 27 | }); 28 | }; 29 | 30 | deploy.tags = ['ProfileLogic']; 31 | 32 | export default deploy; 33 | -------------------------------------------------------------------------------- /src/deploy/logic/ronin-gateway-pause-enforcer-logic.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('RoninGatewayPauseEnforcerLogic', { 15 | contract: 'PauseEnforcer', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['RoninGatewayPauseEnforcerLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/ronin-gateway-v3.ts: -------------------------------------------------------------------------------- 1 | import { ethers, network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | let nonce = await ethers.provider.getTransactionCount(deployer); 15 | 16 | await deploy('RoninGatewayV3Logic', { 17 | contract: 'RoninGatewayV3', 18 | from: deployer, 19 | log: true, 20 | }); 21 | }; 22 | 23 | deploy.tags = ['RoninGatewayV3Logic']; 24 | 25 | export default deploy; 26 | -------------------------------------------------------------------------------- /src/deploy/logic/ronin-trusted-organization-temp.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { allNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!allNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('RoninTrustedOrganizationTempLogic', { 15 | contract: 'RoninTrustedOrganization', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['RoninTrustedOrganizationTempLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/ronin-trusted-organization.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { allNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!allNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('RoninTrustedOrganizationLogic', { 15 | contract: 'RoninTrustedOrganization', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['RoninTrustedOrganizationLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/slash-indicator.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('SlashIndicatorLogic', { 15 | contract: 'SlashIndicator', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['SlashIndicatorLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/staking-vesting.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('StakingVestingLogic', { 15 | contract: 'StakingVesting', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['StakingVestingLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/staking.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | 11 | const { deploy } = deployments; 12 | const { deployer } = await getNamedAccounts(); 13 | 14 | await deploy('StakingLogic', { 15 | contract: 'Staking', 16 | from: deployer, 17 | log: true, 18 | }); 19 | }; 20 | 21 | deploy.tags = ['StakingLogic']; 22 | 23 | export default deploy; 24 | -------------------------------------------------------------------------------- /src/deploy/logic/validator-set.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | 6 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 7 | if (!roninchainNetworks.includes(network.name!)) { 8 | return; 9 | } 10 | const { deploy } = deployments; 11 | const { deployer } = await getNamedAccounts(); 12 | 13 | await deploy('RoninValidatorSetLogic', { 14 | contract: 'RoninValidatorSet', 15 | from: deployer, 16 | log: true, 17 | }); 18 | }; 19 | 20 | deploy.tags = ['RoninValidatorSetLogic']; 21 | 22 | export default deploy; 23 | -------------------------------------------------------------------------------- /src/deploy/migrations/staking-notified-migrator.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | import { DEFAULT_ADDRESS, Network, getImplementOfProxy } from '../../utils'; 6 | 7 | const deploy = async ({ getNamedAccounts, deployments, ethers }: HardhatRuntimeEnvironment) => { 8 | if (!roninchainNetworks.includes(network.name!)) { 9 | return; 10 | } 11 | 12 | // No need to deploy on hardhat network, to not break fixture 13 | if (network.name === Network.Hardhat) { 14 | return; 15 | } 16 | 17 | const { deploy } = deployments; 18 | const { deployer } = await getNamedAccounts(); 19 | 20 | const proxyDepl = await deployments.get('StakingProxy'); 21 | const newImplDelp = await deployments.get('StakingLogic'); 22 | 23 | const prevImplAddr = await getImplementOfProxy(proxyDepl.address); 24 | const roninValidatorAddr = await deployments.get('RoninValidatorSetProxy'); 25 | 26 | console.info('Deploying StakingNotifiedMigrator...'); 27 | console.info(' proxy ', proxyDepl.address); 28 | console.info(' new impl ', newImplDelp.address); 29 | console.info(' prev impl', prevImplAddr); 30 | console.info(' ronin validator set', roninValidatorAddr.address); 31 | 32 | if (prevImplAddr == DEFAULT_ADDRESS) { 33 | console.error('Invalid prev impl'); 34 | return; 35 | } 36 | 37 | const deployment = await deploy('StakingNotifiedMigrator', { 38 | contract: 'NotifiedMigrator', 39 | from: deployer, 40 | log: true, 41 | args: [proxyDepl.address, prevImplAddr, newImplDelp.address, roninValidatorAddr.address], 42 | }); 43 | }; 44 | 45 | deploy.tags = ['StakingNotifiedMigrator', 'MigratorBridgeDetachV0_6']; 46 | deploy.dependencies = ['StakingProxy']; 47 | 48 | export default deploy; 49 | -------------------------------------------------------------------------------- /src/deploy/migrations/timed-migrator-ronin-validator-set.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks } from '../../configs/config'; 5 | import { DEFAULT_ADDRESS, Network } from '../../utils'; 6 | 7 | const deploy = async ({ getNamedAccounts, deployments, ethers }: HardhatRuntimeEnvironment) => { 8 | if (!roninchainNetworks.includes(network.name!)) { 9 | return; 10 | } 11 | 12 | // No need to deploy on hardhat network, to not break fixture 13 | if (network.name === Network.Hardhat) { 14 | return; 15 | } 16 | 17 | const { deploy } = deployments; 18 | const { deployer } = await getNamedAccounts(); 19 | 20 | const proxyDepl = await deployments.get('RoninValidatorSetProxy'); 21 | const newImplDelp = await deployments.get('RoninValidatorSetLogic'); 22 | 23 | const IMPLEMENTATION_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc'; 24 | const prevImplRawBytes32 = await ethers.provider.getStorageAt(proxyDepl.address, IMPLEMENTATION_SLOT); 25 | const prevImplAddr = '0x' + prevImplRawBytes32.slice(26); 26 | 27 | console.info('Deploying RoninValidatorSetTimedMigrator...'); 28 | console.info(' proxy ', proxyDepl.address); 29 | console.info(' new impl ', newImplDelp.address); 30 | console.info(' prev impl', prevImplAddr); 31 | 32 | if (prevImplAddr == DEFAULT_ADDRESS) { 33 | console.error('Invalid prev impl'); 34 | return; 35 | } 36 | 37 | await deploy('RoninValidatorSetTimedMigrator', { 38 | from: deployer, 39 | log: true, 40 | args: [proxyDepl.address, prevImplAddr, newImplDelp.address], 41 | }); 42 | }; 43 | 44 | deploy.tags = ['RoninValidatorSetTimedMigrator']; 45 | 46 | export default deploy; 47 | -------------------------------------------------------------------------------- /src/deploy/proxy/mainchain-gateway-pause-enforcer-proxy.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { generalMainchainConf, mainchainNetworks } from '../../configs/config'; 5 | import { gatewayPauseEnforcerConf } from '../../configs/gateway'; 6 | import { PauseEnforcer__factory } from '../../types'; 7 | 8 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 9 | if (!mainchainNetworks.includes(network.name!)) { 10 | return; 11 | } 12 | 13 | const { deploy } = deployments; 14 | const { deployer } = await getNamedAccounts(); 15 | 16 | const logicContract = await deployments.get('MainchainGatewayPauseEnforcerLogic'); 17 | const GAContract = await deployments.get('MainchainGovernanceAdmin'); 18 | 19 | const data = new PauseEnforcer__factory().interface.encodeFunctionData('initialize', [ 20 | generalMainchainConf[network.name].bridgeContract, 21 | gatewayPauseEnforcerConf[network.name]?.enforcerAdmin, 22 | gatewayPauseEnforcerConf[network.name]?.sentries, 23 | ]); 24 | 25 | await deploy('MainchainGatewayPauseEnforcerProxy', { 26 | contract: 'TransparentUpgradeableProxyV2', 27 | from: deployer, 28 | log: true, 29 | args: [logicContract.address, GAContract.address, data], 30 | }); 31 | }; 32 | 33 | deploy.tags = ['MainchainGatewayPauseEnforcerProxy']; 34 | deploy.dependencies = ['MainchainGatewayPauseEnforcerLogic']; 35 | 36 | export default deploy; 37 | -------------------------------------------------------------------------------- /src/deploy/proxy/mainchain-ronin-trusted-organization-proxy.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninTrustedOrganizationConf, mainchainNetworks, generalMainchainConf } from '../../configs/config'; 5 | import { verifyAddress } from '../../script/verify-address'; 6 | import { RoninTrustedOrganization__factory } from '../../types'; 7 | 8 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 9 | if (!mainchainNetworks.includes(network.name!)) { 10 | return; 11 | } 12 | 13 | const { deploy } = deployments; 14 | const { deployer } = await getNamedAccounts(); 15 | 16 | const logicContract = await deployments.get('RoninTrustedOrganizationLogic'); 17 | const data = new RoninTrustedOrganization__factory().interface.encodeFunctionData('initialize', [ 18 | roninTrustedOrganizationConf[network.name]!.trustedOrganizations, 19 | roninTrustedOrganizationConf[network.name]!.numerator, 20 | roninTrustedOrganizationConf[network.name]!.denominator, 21 | ]); 22 | 23 | const deployment = await deploy('MainchainRoninTrustedOrganizationProxy', { 24 | contract: 'TransparentUpgradeableProxyV2', 25 | from: deployer, 26 | log: true, 27 | args: [logicContract.address, generalMainchainConf[network.name].governanceAdmin?.address, data], 28 | nonce: generalMainchainConf[network.name].roninTrustedOrganizationContract?.nonce, 29 | }); 30 | verifyAddress(deployment.address, generalMainchainConf[network.name].roninTrustedOrganizationContract?.address); 31 | }; 32 | 33 | deploy.tags = ['MainchainRoninTrustedOrganizationProxy']; 34 | deploy.dependencies = ['RoninTrustedOrganizationLogic', '_HelperDposCalculate', 'MainchainGovernanceAdmin']; 35 | deploy.skip = true; 36 | 37 | export default deploy; 38 | -------------------------------------------------------------------------------- /src/deploy/proxy/ronin-gateway-pause-enforcer-proxy.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { generalRoninConf, roninchainNetworks } from '../../configs/config'; 5 | import { gatewayPauseEnforcerConf } from '../../configs/gateway'; 6 | import { PauseEnforcer__factory } from '../../types'; 7 | 8 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 9 | if (!roninchainNetworks.includes(network.name!)) { 10 | return; 11 | } 12 | 13 | const { deploy } = deployments; 14 | const { deployer } = await getNamedAccounts(); 15 | 16 | const logicContract = await deployments.get('RoninGatewayPauseEnforcerLogic'); 17 | const GAContract = await deployments.get('RoninGovernanceAdmin'); 18 | 19 | const data = new PauseEnforcer__factory().interface.encodeFunctionData('initialize', [ 20 | generalRoninConf[network.name].bridgeContract, 21 | gatewayPauseEnforcerConf[network.name]?.enforcerAdmin, 22 | gatewayPauseEnforcerConf[network.name]?.sentries, 23 | ]); 24 | 25 | await deploy('RoninGatewayPauseEnforcerProxy', { 26 | contract: 'TransparentUpgradeableProxyV2', 27 | from: deployer, 28 | log: true, 29 | args: [logicContract.address, GAContract.address, data], 30 | }); 31 | }; 32 | 33 | deploy.tags = ['RoninGatewayPauseEnforcerProxy']; 34 | deploy.dependencies = ['RoninGatewayPauseEnforcerLogic']; 35 | 36 | export default deploy; 37 | -------------------------------------------------------------------------------- /src/deploy/proxy/ronin-trusted-organization-proxy.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninTrustedOrganizationConf, generalRoninConf, roninchainNetworks } from '../../configs/config'; 5 | import { verifyAddress } from '../../script/verify-address'; 6 | import { RoninTrustedOrganization__factory } from '../../types'; 7 | 8 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 9 | if (!roninchainNetworks.includes(network.name!)) { 10 | return; 11 | } 12 | 13 | const { deploy } = deployments; 14 | const { deployer } = await getNamedAccounts(); 15 | 16 | const logicContract = await deployments.get('RoninTrustedOrganizationLogic'); 17 | const data = new RoninTrustedOrganization__factory().interface.encodeFunctionData('initialize', [ 18 | roninTrustedOrganizationConf[network.name]!.trustedOrganizations, 19 | roninTrustedOrganizationConf[network.name]!.numerator, 20 | roninTrustedOrganizationConf[network.name]!.denominator, 21 | ]); 22 | 23 | const nonce = undefined; 24 | // console.log(`Deploying RoninTrustedOrganizationProxy (nonce: ${nonce})...`); 25 | 26 | const deployment = await deploy('RoninTrustedOrganizationProxy', { 27 | contract: 'TransparentUpgradeableProxyV2', 28 | from: deployer, 29 | log: true, 30 | args: [logicContract.address, generalRoninConf[network.name].governanceAdmin?.address, data], 31 | }); 32 | verifyAddress(deployment.address, generalRoninConf[network.name].roninTrustedOrganizationContract?.address); 33 | }; 34 | 35 | deploy.tags = ['RoninTrustedOrganizationProxy']; 36 | deploy.dependencies = ['RoninTrustedOrganizationLogic', '_HelperDposCalculate', 'RoninGovernanceAdmin']; 37 | 38 | export default deploy; 39 | -------------------------------------------------------------------------------- /src/deploy/proxy/staking-proxy.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { stakingConfig, generalRoninConf, roninchainNetworks } from '../../configs/config'; 5 | import { verifyAddress } from '../../script/verify-address'; 6 | import { Staking__factory } from '../../types'; 7 | 8 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 9 | if (!roninchainNetworks.includes(network.name!)) { 10 | return; 11 | } 12 | 13 | const { deploy } = deployments; 14 | const { deployer } = await getNamedAccounts(); 15 | 16 | const logicContract = await deployments.get('StakingLogic'); 17 | 18 | const data = new Staking__factory().interface.encodeFunctionData('initialize', [ 19 | generalRoninConf[network.name]!.validatorContract?.address, 20 | stakingConfig[network.name]!.minValidatorStakingAmount, 21 | stakingConfig[network.name]!.maxCommissionRate, 22 | stakingConfig[network.name]!.cooldownSecsToUndelegate, 23 | stakingConfig[network.name]!.waitingSecsToRevoke, 24 | ]); 25 | 26 | const nonce = generalRoninConf[network.name].stakingContract?.nonce; 27 | // console.log(`Deploying StakingProxy (nonce: ${nonce})...`); 28 | 29 | const deployment = await deploy('StakingProxy', { 30 | contract: 'TransparentUpgradeableProxyV2', 31 | from: deployer, 32 | log: true, 33 | args: [logicContract.address, generalRoninConf[network.name]!.governanceAdmin?.address, data], 34 | nonce, 35 | }); 36 | verifyAddress(deployment.address, generalRoninConf[network.name].stakingContract?.address); 37 | }; 38 | 39 | deploy.tags = ['StakingProxy']; 40 | deploy.dependencies = ['StakingLogic', '_HelperDposCalculate', 'SlashIndicatorProxy']; 41 | 42 | export default deploy; 43 | -------------------------------------------------------------------------------- /src/deploy/ronin-governance-admin.ts: -------------------------------------------------------------------------------- 1 | import { ethers, network } from 'hardhat'; 2 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 3 | 4 | import { roninchainNetworks, generalRoninConf, roninGovernanceAdminConf } from '../configs/config'; 5 | import { verifyAddress } from '../script/verify-address'; 6 | 7 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 8 | if (!roninchainNetworks.includes(network.name!)) { 9 | return; 10 | } 11 | 12 | const { deploy } = deployments; 13 | const { deployer } = await getNamedAccounts(); 14 | 15 | const nonce = generalRoninConf[network.name].governanceAdmin?.nonce; 16 | // console.log(`Deploying RoninGovernanceAdmin (nonce: ${nonce})...`); 17 | 18 | const deployment = await deploy('RoninGovernanceAdmin', { 19 | from: deployer, 20 | log: true, 21 | args: [ 22 | generalRoninConf[network.name].roninChainId, 23 | generalRoninConf[network.name].roninTrustedOrganizationContract?.address, 24 | generalRoninConf[network.name].validatorContract?.address, 25 | roninGovernanceAdminConf[network.name]?.proposalExpiryDuration, 26 | ], 27 | nonce, 28 | }); 29 | 30 | verifyAddress(deployment.address, generalRoninConf[network.name].governanceAdmin?.address); 31 | }; 32 | 33 | deploy.tags = ['RoninGovernanceAdmin']; 34 | deploy.dependencies = ['_HelperDposCalculate']; 35 | 36 | export default deploy; 37 | -------------------------------------------------------------------------------- /src/deploy/vault-forwarder.ts: -------------------------------------------------------------------------------- 1 | import { network } from 'hardhat'; 2 | import { Address } from 'hardhat-deploy/dist/types'; 3 | import { HardhatRuntimeEnvironment } from 'hardhat/types'; 4 | 5 | import { roninchainNetworks, vaultForwarderConf } from '../configs/config'; 6 | 7 | const deploy = async ({ getNamedAccounts, deployments }: HardhatRuntimeEnvironment) => { 8 | if (!roninchainNetworks.includes(network.name!)) { 9 | return; 10 | } 11 | 12 | const { deploy } = deployments; 13 | const { deployer } = await getNamedAccounts(); 14 | const artifactName = 'VaultForwarder'; 15 | 16 | let vaultConfigs = vaultForwarderConf[network.name]!; 17 | let targets: Address[] = []; 18 | let admin: Address = deployer; 19 | let moderator: Address = deployer; 20 | 21 | for (let vaultConf of vaultConfigs) { 22 | let deploymentName = [artifactName, vaultConf.vaultId].join('-'); 23 | 24 | await deploy(deploymentName, { 25 | contract: artifactName, 26 | from: deployer, 27 | log: true, 28 | args: [ 29 | // target 30 | vaultConf.targets ?? targets, 31 | // admin 32 | vaultConf.admin ?? admin, 33 | // moderator 34 | vaultConf.moderator ?? moderator, 35 | ], 36 | }); 37 | } 38 | }; 39 | 40 | deploy.tags = ['VaultForwarder']; 41 | 42 | export default deploy; 43 | -------------------------------------------------------------------------------- /src/script/bridge.ts: -------------------------------------------------------------------------------- 1 | import { AbiCoder, keccak256, _TypedDataEncoder } from 'ethers/lib/utils'; 2 | 3 | import { InfoStruct, OwnerStruct, ReceiptStruct } from '../types/IMainchainGatewayV3'; 4 | 5 | // keccak256("TokenInfo(uint8 erc,uint256 id,uint256 quantity)"); 6 | const tokenInfoTypeHash = '0x1e2b74b2a792d5c0f0b6e59b037fa9d43d84fbb759337f0112fcc15ca414fc8d'; 7 | // keccak256("TokenOwner(address addr,address tokenAddr,uint256 chainId)"); 8 | const tokenOwnerTypeHash = '0x353bdd8d69b9e3185b3972e08b03845c0c14a21a390215302776a7a34b0e8764'; 9 | // keccak256("Receipt(uint256 id,uint8 kind,TokenOwner mainchain,TokenOwner ronin,TokenInfo info)TokenInfo(uint8 erc,uint256 id,uint256 quantity)TokenOwner(address addr,address tokenAddr,uint256 chainId)"); 10 | const receiptTypeHash = '0xb9d1fe7c9deeec5dc90a2f47ff1684239519f2545b2228d3d91fb27df3189eea'; 11 | 12 | export const tokenInfoParamTypes = ['bytes32', 'uint8', 'uint256', 'uint256']; 13 | export const tokenOwnerParamTypes = ['bytes32', 'address', 'address', 'uint256']; 14 | export const receiptParamTypes = ['bytes32', 'uint256', 'uint8', 'bytes32', 'bytes32', 'bytes32']; 15 | 16 | const getTokenInfoHash = (info: InfoStruct): string => 17 | keccak256(AbiCoder.prototype.encode(tokenInfoParamTypes, [tokenInfoTypeHash, info.erc, info.id, info.quantity])); 18 | 19 | const getTokenOwnerHash = (owner: OwnerStruct): string => 20 | keccak256( 21 | AbiCoder.prototype.encode(tokenOwnerParamTypes, [tokenOwnerTypeHash, owner.addr, owner.tokenAddr, owner.chainId]) 22 | ); 23 | 24 | export const getReceiptHash = (receipt: ReceiptStruct): string => 25 | keccak256( 26 | AbiCoder.prototype.encode(receiptParamTypes, [ 27 | receiptTypeHash, 28 | receipt.id, 29 | receipt.kind, 30 | getTokenOwnerHash(receipt.mainchain), 31 | getTokenOwnerHash(receipt.ronin), 32 | getTokenInfoHash(receipt.info), 33 | ]) 34 | ); 35 | -------------------------------------------------------------------------------- /src/script/ronin-validator-set.ts: -------------------------------------------------------------------------------- 1 | export enum BlockRewardDeprecatedType { 2 | UNKNOWN = 0, 3 | UNAVAILABILITY = 1, 4 | AFTER_BAILOUT = 2, 5 | } 6 | -------------------------------------------------------------------------------- /src/script/slash-indicator.ts: -------------------------------------------------------------------------------- 1 | export enum SlashType { 2 | UNKNOWN = 0, 3 | UNAVAILABILITY_TIER_1 = 1, 4 | UNAVAILABILITY_TIER_2 = 2, 5 | DOUBLE_SIGNING = 3, 6 | BRIDGE_VOTING = 4, 7 | BRIDGE_OPERATOR_MISSING_VOTE_TIER_1 = 5, 8 | BRIDGE_OPERATOR_MISSING_VOTE_TIER_2 = 6, 9 | UNAVAILABILITY_TIER_3 = 7, 10 | } 11 | -------------------------------------------------------------------------------- /src/script/verify-address.ts: -------------------------------------------------------------------------------- 1 | import { Address } from 'hardhat-deploy/dist/types'; 2 | 3 | export const verifyAddress = (actual: Address, expected?: Address) => { 4 | if (actual.toLowerCase() != (expected || '').toLowerCase()) { 5 | throw Error(`Invalid address, expected=${expected}, actual=${actual}`); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /src/upgrades/REP-002-REP-003--v0.6.4--mainnet/TODO: -------------------------------------------------------------------------------- 1 | // - [ ] Deploy MainchainGatewayV3Logic 2 | // - [ ] Config operators and governors for BridgeManager 3 | // - [ ] Top-up for BridgeReward 4 | // - [ ] Execute `20231013-proposal-on-roninchain.ts --network ronin-mainnet` 5 | // - [ ] Execute `20231013-proposal-on-mainchain.ts --network ronin-mainnet` -------------------------------------------------------------------------------- /src/upgrades/REP-003/TODO.ts: -------------------------------------------------------------------------------- 1 | // - [ ] Deploy simple version of Profile contract 2 | // - [ ] Deploy Fast Finality contract 3 | // - [ ] Upgrade Validator Set Contract 4 | // - [ ] Upgrade 5 | // - [ ] InitV3 6 | 7 | // - [ ] Upgrade Staking Vesting Contract 8 | // - [ ] Upgrade 9 | // - [ ] InitV3 10 | 11 | // - [ ] Upgrade Slash Indicator Contract 12 | // - [ ] Upgrade 13 | // - [ ] InitV3 14 | -------------------------------------------------------------------------------- /test/foundry/Base.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity >=0.8.17 <0.9.0; 3 | 4 | import { StdCheats } from "forge-std/StdCheats.sol"; 5 | 6 | import { Assertions } from "./utils/Assertions.sol"; 7 | import { Utils } from "./utils/Utils.sol"; 8 | 9 | import { IBridgeManagerEvents } from "@ronin/contracts/interfaces/bridge/events/IBridgeManagerEvents.sol"; 10 | 11 | abstract contract Base_Test is Assertions, Utils, StdCheats, IBridgeManagerEvents { } 12 | -------------------------------------------------------------------------------- /test/foundry/bridge/unit/concrete/bridge-manager/add/add.tree: -------------------------------------------------------------------------------- 1 | add.t.sol 2 | when not self-called 3 | it should revert 4 | when self-called 5 | when the three input arrays length mismatch 6 | it should revert 7 | when the vote weight or the address is zero 8 | it should revert 9 | when duplicated governor 10 | it should revert 11 | when duplicated bridge operator 12 | it should revert 13 | when the info is valid 14 | it should add gorvernor to the governor list 15 | it should add bridge operator to the operator list 16 | it should grant the governor the expected weight 17 | -------------------------------------------------------------------------------- /test/foundry/bridge/unit/concrete/bridge-manager/remove/remove.tree: -------------------------------------------------------------------------------- 1 | remove.t.sol 2 | ├── when not self-called 3 | │ └── it should revert 4 | └── when self-called 5 | ├── when the address contains one address 6 | │ ├── when the address is not operator 7 | │ │ └── it should revert 8 | │ └── when the address is operator 9 | │ ├── it should remove the gorvernor to the governor list 10 | │ ├── it should remove the bridge operator to the operator list 11 | │ ├── it should remove the governor the expected weight 12 | │ ├── it should reduce total weight 13 | │ ├── it should reduce total operator 14 | │ ├── it should notify registers 15 | │ ├── it should then return address zero when query by the removed governor 16 | │ └── it should then return address zero when query by the removed operator 17 | └── when the address contains two address 18 | ├── when the address duplicated 19 | └── when the address is not duplicated 20 | ├── it should remove the gorvernor to the governor list 21 | ├── it should remove the bridge operator to the operator list 22 | ├── it should remove the governor the expected weight 23 | ├── it should reduce total weight 24 | └── it should notify registers -------------------------------------------------------------------------------- /test/foundry/bridge/unit/concrete/bridge-manager/update/update.tree: -------------------------------------------------------------------------------- 1 | update.t.sol 2 | ├── when not call by the governor whose operator is being updated 3 | │ └── it should revert 4 | └── when call by the governor whose operator is being updated 5 | ├── when the new operator is zero address 6 | │ └── it should revert 7 | ├── when the new operator is already existed in the current list of operators 8 | │ └── it should revert 9 | ├── when the new operator is already existed in the current list of governors 10 | │ └── it should revert 11 | ├── when the new operator is the same as the previous operator 12 | │ └── it should revert 13 | └── when the new operator is valid 14 | ├── it should modify the current operators list 15 | ├── it should remove the old operator 16 | ├── it should notify the registers // TODO 17 | ├── it should emit {BridgeOperatorUpdated} event 18 | ├── it should then return new operator when query mapping by governor 19 | ├── it should then return governor when query mapping by the new operator 20 | └── it should then return address zero when query mapping by the old operator -------------------------------------------------------------------------------- /test/foundry/bridge/unit/concrete/bridge-reward/execSyncReward/execSyncReward.tree: -------------------------------------------------------------------------------- 1 | execSyncReward.t.sol 2 | ├── when not called by BridgeTracking 3 | │ └── it should revert 4 | └── when call by BridgeTracking 5 | ├── when operators length is zero 6 | │ └── it should revert 7 | ├── when operators and ballots length mismatchs 8 | │ └── it should revert 9 | ├── when period number is less than {latestRewardedPeriod + 1} 10 | │ └── it should revert 11 | ├── when period number is greater than {latestRewardedPeriod + 1} 12 | │ └── it should revert with too far period 13 | └── when input length valid 14 | ├── when data corrupts 15 | │ ├── when reward contract insufficient funds 16 | │ │ ├── should share reward equally 17 | │ │ └── should emit fail transfer event 18 | │ └── when reward contract have funds 19 | │ ├── should share reward equally 20 | │ └── should emit success transfer event 21 | ├── when there is no vote 22 | │ └── should share reward equally 23 | └── when data is normal 24 | ├── should share reward proportionally 25 | └── when call execSyncReward again 26 | └── should revert with already rewarded or invalid arguments -------------------------------------------------------------------------------- /test/foundry/forking/REP-002/DebugTestnetWrapupPeriod.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "../RoninTest.t.sol"; 5 | import { MockPrecompile } from "@ronin/contracts/mocks/MockPrecompile.sol"; 6 | import { ITimingInfo } from "@ronin/contracts/interfaces/validator/info-fragments/ITimingInfo.sol"; 7 | import { ICoinbaseExecution } from "@ronin/contracts/interfaces/validator/ICoinbaseExecution.sol"; 8 | 9 | contract DebugTx is RoninTest { 10 | uint256 internal _roninFork; 11 | uint256 internal constant FORK_HEIGHT = 0; 12 | bytes32 internal constant TX = 0x5210f0de49b8a8aa4e8197965c8d3bdaa86177f721b31937ed92b9c06f363299; 13 | 14 | function _createFork() internal override { 15 | _roninFork = vm.createSelectFork(RONIN_TEST_RPC); 16 | } 17 | 18 | function _setUp() internal override { 19 | address mockPrecompile = 20 | deployImmutable(type(MockPrecompile).name, type(MockPrecompile).creationCode, EMPTY_PARAM, ZERO_VALUE); 21 | vm.etch(address(0x68), mockPrecompile.code); 22 | } 23 | 24 | function test_Debug_SingleTransaction() external onWhichFork(_roninFork) { 25 | address coinbase = block.coinbase; 26 | uint256 numberOfBlocksInEpoch = ITimingInfo(address(RONIN_VALIDATOR_SET_CONTRACT)).numberOfBlocksInEpoch(); 27 | 28 | uint256 epochEndingBlockNumber = block.number + (numberOfBlocksInEpoch - 1) - (block.number % numberOfBlocksInEpoch); 29 | uint256 nextDayTimestamp = block.timestamp + 1 days; 30 | 31 | console.log(_getProxyImplementation(RONIN_VALIDATOR_SET_CONTRACT)); 32 | 33 | // fast forward to next day 34 | vm.warp(nextDayTimestamp); 35 | vm.roll(epochEndingBlockNumber); 36 | vm.prank(coinbase, coinbase); 37 | ICoinbaseExecution(address(RONIN_VALIDATOR_SET_CONTRACT)).wrapUpEpoch(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /test/foundry/forking/utils/Consts.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { RoninGovernanceAdmin } from "@ronin/contracts/ronin/RoninGovernanceAdmin.sol"; 5 | import { TransparentUpgradeableProxyV2 } from "@ronin/contracts/extensions/TransparentUpgradeableProxyV2.sol"; 6 | 7 | bytes constant EMPTY_PARAM = ""; 8 | uint256 constant ZERO_VALUE = 0; 9 | string constant GOERLI_RPC = "https://eth-goerli.public.blastapi.io"; 10 | string constant RONIN_TEST_RPC = "https://saigon-archive.roninchain.com/rpc"; 11 | 12 | bytes32 constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; 13 | 14 | bytes32 constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; 15 | 16 | // Saigon Testnet 17 | TransparentUpgradeableProxyV2 constant RONIN_VALIDATOR_SET_CONTRACT = 18 | TransparentUpgradeableProxyV2(payable(0x54B3AC74a90E64E8dDE60671b6fE8F8DDf18eC9d)); 19 | TransparentUpgradeableProxyV2 constant RONIN_BRIDGE_TRACKING_CONTRACT = 20 | TransparentUpgradeableProxyV2(payable(0x874ad3ACb2801733c3fbE31a555d430Ce3A138Ed)); 21 | RoninGovernanceAdmin constant RONIN_GOVERNANCE_ADMIN_CONTRACT = 22 | RoninGovernanceAdmin(payable(0x53Ea388CB72081A3a397114a43741e7987815896)); 23 | TransparentUpgradeableProxyV2 constant RONIN_GATEWAY_CONTRACT = 24 | TransparentUpgradeableProxyV2(payable(0xCee681C9108c42C710c6A8A949307D5F13C9F3ca)); 25 | 26 | // Goerli 27 | TransparentUpgradeableProxyV2 constant ETH_GATEWAY_CONTRACT = 28 | TransparentUpgradeableProxyV2(payable(0xFc4319Ae9e6134C708b88D5Ad5Da1A4a83372502)); 29 | -------------------------------------------------------------------------------- /test/foundry/helpers/LibArrayUtils.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | library LibArrayUtils { 5 | function sum(bool[] memory arr) internal pure returns (uint256 total) { 6 | uint256 length = arr.length; 7 | for (uint256 i; i < length;) { 8 | if (arr[i]) total++; 9 | unchecked { 10 | ++i; 11 | } 12 | } 13 | } 14 | 15 | function sum(uint256[] memory arr) internal pure returns (uint256 total) { 16 | uint256 length = arr.length; 17 | for (uint256 i; i < length;) { 18 | total += arr[i]; 19 | unchecked { 20 | ++i; 21 | } 22 | } 23 | } 24 | 25 | function sum(uint96[] memory arr) internal pure returns (uint256 total) { 26 | uint256[] memory arr256; 27 | assembly { 28 | arr256 := arr 29 | } 30 | 31 | return sum(arr256); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /test/foundry/helpers/Randomizer.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import { Base_Test } from "../Base.t.sol"; 5 | 6 | abstract contract Randomizer is Base_Test { 7 | function _randomize(uint256 seed, uint256 min, uint256 max) internal pure returns (uint256 r) { 8 | r = _bound(uint256(keccak256(abi.encode(seed))), min, max); 9 | } 10 | 11 | function _createRandomAddresses(uint256 seed, uint256 amount) internal returns (address[] memory addrs) { 12 | addrs = new address[](amount); 13 | 14 | for (uint256 i; i < amount;) { 15 | seed = uint256(keccak256(abi.encode(seed))); 16 | addrs[i] = vm.addr(seed); 17 | vm.etch(addrs[i], abi.encode()); 18 | vm.deal(addrs[i], 1 ether); 19 | 20 | unchecked { 21 | ++i; 22 | } 23 | } 24 | } 25 | 26 | function _createRandomNumbers( 27 | uint256 seed, 28 | uint256 amount, 29 | uint256 min, 30 | uint256 max 31 | ) internal pure returns (uint256[] memory nums) { 32 | uint256 r; 33 | nums = new uint256[](amount); 34 | 35 | for (uint256 i; i < amount;) { 36 | r = _randomize(seed, min, max); 37 | nums[i] = r; 38 | seed = r; 39 | 40 | unchecked { 41 | ++i; 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/foundry/mocks/MockBridgeSlash.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity >=0.8.17 <0.9.0; 3 | 4 | import { IBridgeSlash } from "@ronin/contracts/interfaces/bridge/IBridgeSlash.sol"; 5 | 6 | contract MockBridgeSlash is IBridgeSlash { 7 | mapping(address => uint256) internal _slashMap; 8 | 9 | function MINIMUM_VOTE_THRESHOLD() external view returns (uint256) { } 10 | 11 | function REMOVE_DURATION_THRESHOLD() external view returns (uint256) { } 12 | 13 | function TIER_1_PENALTY_DURATION() external view returns (uint256) { } 14 | 15 | function TIER_2_PENALTY_DURATION() external view returns (uint256) { } 16 | 17 | function execSlashBridgeOperators( 18 | address[] calldata operators, 19 | uint256[] calldata ballots, 20 | uint256 totalBallot, 21 | uint256 totalVote, 22 | uint256 period 23 | ) external { } 24 | 25 | function getAddedPeriodOf(address[] calldata bridgeOperators) external view returns (uint256[] memory addedPeriods) { } 26 | 27 | function getPenaltyDurations() external pure returns (uint256[] memory penaltyDurations) { } 28 | 29 | function getSlashTier(uint256 ballot, uint256 totalVote) external pure returns (Tier tier) { } 30 | 31 | function getSlashUntilPeriodOf(address[] calldata operators) external view returns (uint256[] memory untilPeriods) { 32 | untilPeriods = new uint256[](operators.length); 33 | for (uint i; i < operators.length; i++) { 34 | untilPeriods[i] = _slashMap[operators[i]]; 35 | } 36 | } 37 | 38 | function cheat_setSlash(address[] calldata operators, uint256[] calldata untilPeriods) external { 39 | require(operators.length != untilPeriods.length, "invalid length"); 40 | 41 | for (uint i; i < operators.length; i++) { 42 | _slashMap[operators[i]] = untilPeriods[i]; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/foundry/mocks/MockValidatorSet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity >=0.8.17 <0.9.0; 3 | 4 | import { TConsensus } from "@ronin/contracts/udvts/Types.sol"; 5 | 6 | contract MockValidatorSet { 7 | uint256 _period; 8 | 9 | function setPeriod(uint256 period) external { 10 | _period = period; 11 | } 12 | 13 | function currentPeriod() external view returns (uint256) { 14 | return _period; 15 | } 16 | 17 | function getValidatorCandidates() external pure returns (address[] memory) { 18 | return new address[](0); 19 | } 20 | 21 | function isCandidateAdmin(TConsensus, /*consensus*/ address /*admin*/ ) external pure returns (bool) { 22 | return true; 23 | } 24 | 25 | function isCandidateAdminById(address, /*cid*/ address /*admin*/ ) external pure returns (bool) { 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /test/foundry/mocks/README.md: -------------------------------------------------------------------------------- 1 | This folder includes mocks for unit tests. Do not use these mocks in the integration or forking test, instead using the production contracts. 2 | -------------------------------------------------------------------------------- /test/foundry/overview.tree: -------------------------------------------------------------------------------- 1 | test 2 | ├── mocks // mocks to set up unit test, DO NOT use in integration test 3 | ├── unit 4 | │ ├── concrete 5 | │ │ └── ... 6 | │ └── fuzz 7 | │ └── ... 8 | ├── integration 9 | │ ├── concrete 10 | │ │ └── ... 11 | │ └── fuzz 12 | │ └── ... 13 | ├── invariant 14 | ├── fork 15 | └── Base.t.sol -------------------------------------------------------------------------------- /test/foundry/utils/Assertions.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.8.21; 3 | 4 | import { PRBTest } from "@prb/test/PRBTest.sol"; 5 | import { PRBMathAssertions } from "@prb/math/src/test/Assertions.sol"; 6 | 7 | abstract contract Assertions is PRBTest, PRBMathAssertions { 8 | event LogNamedArray(string key, uint96[] value); 9 | 10 | /// @dev Tests that `a` and `b` are equal. If they are not, the test fails. 11 | /// Works by comparing the `keccak256` hashes of the arrays, which is faster than iterating over the elements. 12 | function assertEq(uint96[] memory a, uint96[] memory b) internal virtual { 13 | if (!(keccak256(abi.encode(a)) == keccak256(abi.encode(b)))) { 14 | emit PRBTest.Log("Error: a == b not satisfied [uint96[]]"); 15 | emit LogNamedArray(" Left", a); 16 | emit LogNamedArray(" Right", b); 17 | PRBTest.fail(); 18 | } 19 | } 20 | 21 | /// @dev Tests that `a` and `b` are equal. If they are not, the test fails with the error message `err`. 22 | /// Works by comparing the `keccak256` hashes of the arrays, which is faster than iterating over the elements. 23 | function assertEq(uint96[] memory a, uint96[] memory b, string memory err) internal virtual { 24 | if (!(keccak256(abi.encode(a)) == keccak256(abi.encode(b)))) { 25 | emit PRBTest.LogNamedString("Error", err); 26 | assertEq(a, b); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/foundry/utils/Types.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.8.19; 3 | 4 | struct Users { 5 | // Impartial user. 6 | address payable alice; 7 | } 8 | -------------------------------------------------------------------------------- /test/foundry/utils/Utils.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.8.19; 3 | 4 | import { StdUtils } from "forge-std/StdUtils.sol"; 5 | 6 | import { PRBMathUtils } from "@prb/math/src/test/Utils.sol"; 7 | 8 | abstract contract Utils is StdUtils, PRBMathUtils { 9 | function getEmptyAddressArray() internal pure returns (address[] memory arr) { } 10 | 11 | function wrapAddress(address val) internal pure returns (address[] memory arr) { 12 | arr = new address[](1); 13 | arr[0] = val; 14 | } 15 | 16 | function unwrapAddress(address[] memory arr) internal pure returns (address val) { 17 | val = arr[0]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/address-set-types/operator-tuple-type.ts: -------------------------------------------------------------------------------- 1 | import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'; 2 | import { expect } from 'chai'; 3 | import { checkArraysHaveSameSize } from '../utils'; 4 | 5 | export type OperatorTuple = { 6 | operator: SignerWithAddress; 7 | governor: SignerWithAddress; 8 | }; 9 | 10 | export function createOperatorTuple(addrs: SignerWithAddress[]): OperatorTuple | undefined { 11 | if (addrs.length != 2) { 12 | return; 13 | } 14 | 15 | return { 16 | operator: addrs[0], 17 | governor: addrs[1], 18 | }; 19 | } 20 | 21 | export function createManyOperatorTuples(signers: SignerWithAddress[]): OperatorTuple[]; 22 | 23 | export function createManyOperatorTuples( 24 | operators: SignerWithAddress[], 25 | governors: SignerWithAddress[] 26 | ): OperatorTuple[]; 27 | 28 | export function createManyOperatorTuples( 29 | signers: SignerWithAddress[], 30 | governors?: SignerWithAddress[] 31 | ): OperatorTuple[] { 32 | let operators: SignerWithAddress[] = []; 33 | 34 | if (!governors || !operators) { 35 | expect(signers.length % 2).eq(0, 'createManyOperatorTuples: signers length must be divisible by 2'); 36 | 37 | let _length = signers.length / 2; 38 | operators = signers.splice(0, _length); 39 | governors = signers.splice(0, _length); 40 | } else { 41 | operators = signers; 42 | } 43 | 44 | governors.sort((v1, v2) => v1.address.toLowerCase().localeCompare(v2.address.toLowerCase())); 45 | operators.sort((v1, v2) => v1.address.toLowerCase().localeCompare(v2.address.toLowerCase())); 46 | 47 | expect(checkArraysHaveSameSize([governors, operators])).eq( 48 | true, 49 | 'createManyOperatorTuples: input arrays of signers must have same length' 50 | ); 51 | 52 | return operators.map((v, i) => ({ 53 | operator: v, 54 | governor: governors![i], 55 | })); 56 | } 57 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/address-set-types/whitelisted-candidate-set-type.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import { TrustedOrganizationAddressSet } from './trusted-org-set-type'; 3 | import { ValidatorCandidateAddressSet } from './validator-candidate-set-type'; 4 | import { checkArraysHaveSameSize } from '../utils'; 5 | 6 | export type WhitelistedCandidateAddressSet = TrustedOrganizationAddressSet & ValidatorCandidateAddressSet; 7 | 8 | export function mergeToWhitelistedCandidateAddressSet( 9 | trustedOrg: TrustedOrganizationAddressSet, 10 | candidate: ValidatorCandidateAddressSet 11 | ): WhitelistedCandidateAddressSet { 12 | candidate.consensusAddr = trustedOrg.consensusAddr; 13 | candidate.cid = trustedOrg.consensusAddr; 14 | return { ...trustedOrg, ...candidate }; 15 | } 16 | 17 | export function mergeToManyWhitelistedCandidateAddressSets( 18 | trustedOrgs: TrustedOrganizationAddressSet[], 19 | candidates: ValidatorCandidateAddressSet[] 20 | ): WhitelistedCandidateAddressSet[] { 21 | expect(checkArraysHaveSameSize([trustedOrgs, candidates])).eq( 22 | true, 23 | 'mergeToManyWhitelistedCandidateAddressSets: input arrays of signers must have same length' 24 | ); 25 | 26 | return trustedOrgs.map((org, idx) => mergeToWhitelistedCandidateAddressSet(org, candidates[idx])); 27 | } 28 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/candidate-manager.ts: -------------------------------------------------------------------------------- 1 | import { ethers, network } from 'hardhat'; 2 | 3 | import { expect } from 'chai'; 4 | import { ContractTransaction } from 'ethers'; 5 | 6 | import { expectEvent } from './utils'; 7 | import { CandidateManager__factory } from '../../../src/types'; 8 | 9 | const contractInterface = CandidateManager__factory.createInterface(); 10 | 11 | export const expects = { 12 | emitCandidatesRevokedEvent: async function (tx: ContractTransaction, expectingRevokedCandidates: string[]) { 13 | await expectEvent( 14 | contractInterface, 15 | 'CandidatesRevoked', 16 | tx, 17 | (event) => { 18 | expect(event.args[0], 'invalid revoked candidates').deep.equal(expectingRevokedCandidates); 19 | }, 20 | 1 21 | ); 22 | }, 23 | 24 | emitCandidateGrantedEvent: async function ( 25 | tx: ContractTransaction, 26 | expectingConsensusAddr: string, 27 | expectingTreasuryAddr: string, 28 | expectingAdmin: string 29 | ) { 30 | await expectEvent( 31 | contractInterface, 32 | 'CandidateGranted', 33 | tx, 34 | (event) => { 35 | expect(event.args[0], 'invalid consensus address').deep.equal(expectingConsensusAddr); 36 | expect(event.args[1], 'invalid treasury address').deep.equal(expectingTreasuryAddr); 37 | expect(event.args[2], 'invalid admin address').deep.equal(expectingAdmin); 38 | }, 39 | 1 40 | ); 41 | }, 42 | }; 43 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/encoder.ts: -------------------------------------------------------------------------------- 1 | import { Interface } from '@ethersproject/abi'; 2 | import { ethers } from 'ethers'; 3 | 4 | export class Encoder { 5 | static readonly abi: string[] = ['function Error(string)']; 6 | static readonly iface: Interface = new ethers.utils.Interface(Encoder.abi); 7 | 8 | static encodeError(msg: string): string { 9 | return Encoder.iface.encodeFunctionData('Error', [msg]); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/governance-admin.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | 3 | import { expectEvent } from './utils'; 4 | import { GovernanceAdmin__factory, RoninValidatorSet__factory } from '../../../src/types'; 5 | import { ContractTransaction } from 'ethers'; 6 | 7 | const contractInterface = GovernanceAdmin__factory.createInterface(); 8 | 9 | export const expects = { 10 | emitProposalExecutedEvent: async function ( 11 | tx: ContractTransaction, 12 | expectingProposalHash: string, 13 | expectingSuccessCalls: boolean[], 14 | expectingReturnedDatas: string[] 15 | ) { 16 | await expectEvent( 17 | contractInterface, 18 | 'ProposalExecuted', 19 | tx, 20 | (event) => { 21 | expect(event.args[0], 'invalid proposal hash').eq(expectingProposalHash); 22 | expect(event.args[1], 'invalid success calls').deep.equal(expectingSuccessCalls); 23 | expect(event.args[2], 'invalid returned datas').deep.equal(expectingReturnedDatas); 24 | }, 25 | 1 26 | ); 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/slash.ts: -------------------------------------------------------------------------------- 1 | export class IndicatorController { 2 | private _indicators: number[]; 3 | 4 | constructor(_size: number) { 5 | this._indicators = new Array(_size).fill(0); 6 | } 7 | 8 | increaseAt(idx: number, value?: number) { 9 | value = value ?? 1; 10 | this._indicators[idx] += value; 11 | } 12 | 13 | setAt(idx: number, value: number) { 14 | this._indicators[idx] = value; 15 | } 16 | 17 | resetAt(idx: number) { 18 | this._indicators[idx] = 0; 19 | } 20 | 21 | getAt(idx: number): number { 22 | return this._indicators[idx]; 23 | } 24 | } 25 | 26 | export class ScoreController { 27 | private _scores: number[]; 28 | 29 | constructor(_size: number) { 30 | this._scores = new Array(_size).fill(0); 31 | } 32 | 33 | increaseAt(idx: number, value?: number) { 34 | value = value ?? 1; 35 | this._scores[idx] += value; 36 | } 37 | 38 | increaseAtWithUpperbound(idx: number, upperbound: number, value?: number) { 39 | value = value ?? 1; 40 | this._scores[idx] += value; 41 | 42 | if (this._scores[idx] > upperbound) { 43 | this._scores[idx] = upperbound; 44 | } 45 | } 46 | 47 | subAtNonNegative(idx: number, value: number) { 48 | this._scores[idx] -= value; 49 | 50 | if (this._scores[idx] < 0) { 51 | this._scores[idx] = 0; 52 | } 53 | } 54 | 55 | setAt(idx: number, value: number) { 56 | this._scores[idx] = value; 57 | } 58 | 59 | resetAt(idx: number) { 60 | this._scores[idx] = 0; 61 | } 62 | 63 | getAt(idx: number): number { 64 | return this._scores[idx]; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /test/hardhat_test/helpers/staking.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import { BigNumberish, ContractTransaction } from 'ethers'; 3 | 4 | import { expectEvent } from './utils'; 5 | import { Staking__factory } from '../../../src/types'; 6 | 7 | const contractInterface = Staking__factory.createInterface(); 8 | 9 | export const expects = { 10 | emitPoolsUpdatedEvent: async function ( 11 | tx: ContractTransaction, 12 | expectingPeriod?: BigNumberish, 13 | expectingPoolAddressList?: string[], 14 | expectingAccumulatedRpsList?: BigNumberish[] 15 | ) { 16 | await expectEvent( 17 | contractInterface, 18 | 'PoolsUpdated', 19 | tx, 20 | (event) => { 21 | if (!!expectingPeriod) { 22 | expect(event.args[0], 'invalid period').deep.equal(expectingPeriod); 23 | } 24 | if (!!expectingPoolAddressList) { 25 | expect(event.args[1], 'invalid pool address list').deep.equal(expectingPoolAddressList); 26 | } 27 | if (!!expectingAccumulatedRpsList) { 28 | expect(event.args[2], 'invalid accumulated rps list').deep.equal(expectingAccumulatedRpsList); 29 | } 30 | }, 31 | 1 32 | ); 33 | }, 34 | }; 35 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "downlevelIteration": true, 5 | "lib": ["dom", "es2015"], 6 | "module": "commonjs", 7 | "noImplicitReturns": true, 8 | "strict": true, 9 | "target": "es5", 10 | "outDir": "dist", 11 | "rootDir": ".", 12 | "composite": true, 13 | "declaration": true, 14 | "declarationMap": true, 15 | "sourceMap": true, 16 | "skipLibCheck": true 17 | }, 18 | "include": ["./src/types"], 19 | "files": [] 20 | } 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2018", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "outDir": "dist", 8 | "composite": true, 9 | "skipLibCheck": true 10 | }, 11 | "include": ["./src", "./test"], 12 | "files": ["./hardhat.config.ts"] 13 | } 14 | --------------------------------------------------------------------------------