Skip to content
Verified contractPartialMIT

StabilityPool_v3_Upgrader

Address0x4b8b554faf412958ffae424aa4c5a46a908ab09a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

3 more contracts

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 700 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,398,483
Creation transaction
0xf05b362944…086d70dcd1
Libraries
src/minter/library/Config_v2.sol:Config_v20xae95…413ca7src/minter/library/RebalanceSizing_v1.sol:RebalanceSizing_v10x5a84…b841besrc/minter/library/MinterAdjustments_v1.sol:MinterAdjustments_v10x410d…39f0fc

62 files

The source code is large: one file is shown at a time. Choose a file in the list.

script/UpgradeStabilityPool_v2_v3/StabilityPool_v3_Upgrader.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import {HarborFixedOwnable} from "@bao/HarborFixedOwnable.sol";

import {IMultipleRewardAccumulator_v3} from "@harbor/interfaces/IMultipleRewardAccumulator_v3.sol";
import {LinearReward} from "@harbor/reward/distributor/LinearReward.sol";
import {LinearReward_v2} from "@harbor/reward/distributor/LinearReward_v2.sol";
import {LinearMultipleRewardDistributor_v3} from "@harbor/reward/distributor/LinearMultipleRewardDistributor_v3.sol";
import {MultipleRewardCompoundingAccumulator_v3} from "@harbor/reward/accumulator/MultipleRewardCompoundingAccumulator_v3.sol";
import {StabilityPool_v3} from "@harbor/minter/StabilityPool_v3.sol";

import {IStabilityPool_v3_Upgrader} from "@harbor-script/UpgradeStabilityPool_v2_v3/IStabilityPool_v3_Upgrader.sol";

/// @title StabilityPool_v3_Upgrader
/// @notice One-shot throwaway implementation for the StabilityPool_v2 -> StabilityPool_v3 upgrade, run atomically as a
///         TEMPORARY proxy implementation. `migrateAndUpgrade`, in one transaction:
///           1. widen-copies each active token's reward stream from the legacy `rewardDataUNUSED` (v1 layout) into the
///              widened `rewardData` - the v3 reward-field widen relocated it to a fresh slot, so a plain upgrade would
///              read the empty widened mapping and drop every mid-period reward. Historical tokens are skipped:
///              unregistering a token requires a fully-distributed stream, so their data reads identically from the
///              empty widened mapping;
///           2. writes the reward-divisor gap (`rewardDivisor = totalAssetSupply.amount - rewardDivisorGap`, the
///              denominator reward accrual divides by, which must track Sum(balanceOf)). The value is the exact
///              `supply - Sum(balanceOf)` computed off-chain from the complete frozen holder list under realistic
///              bounds - `0` when supply already equals the summed balances;
///           3. takes each deduction from what its account may claim and pays it to the owner: a reward a holder was
///              credited with by a fault, taken back before the pool resumes and anyone can claim. The account is
///              settled first through the new implementation's own `checkpoint`, delegatecalled on the migrated storage
///              as the upgrade delegatecalls an initializer, so what it may claim is counted by the arithmetic a claim
///              counts it by and none is restated here;
///           4. upgrades the proxy to the real StabilityPool_v3.
///         Before any of it, it refuses a pool where v2's loss-product exponent byte is not zero in the supply's record
///         or in a listed holder's: v3 reads a record as v2 wrote it only where that byte is zero.
///         All of it runs in one call because the gap does NOT self-heal - normal operation only rescales it on losses,
///         never re-derives it from balances - so it must be correct before any reward accrues; a separate later run
///         would leave the pool on v3 with an un-seeded divisor in between. The deductions ride the same call because
///         the pool's first claim after it must already see them. It leaves no migration code on the functional
///         contract.
/// @dev Owner-gated and single-shot by construction: it upgrades away from itself in the same transaction, so
///      `migrateAndUpgrade` can never run twice - no re-run guard is needed. Storage safety: it reaches each namespace
///      it touches (the pool's and the linear distributor's) through that contract's own canonical struct type
///      (compiler-enforced, cannot drift) at the namespace's ERC-7201 slot - which storage-successor auto-verifies each
///      slot constant against its canonical hash. The bao-upgrades-from below makes storage-successor byte-compare
///      those reached (v3) structs against StabilityPool_v2's same namespaces - a PARTIAL successor check: the
///      namespaces it does not touch are left to `StabilityPool_v3 <- StabilityPool_v2`. So this upgrader is verified
///      compatible with v2 and identical to v3, which double-checks that StabilityPool_v3 is a valid route from v2.
///      OZ sees only @custom:oz-upgrades and validates it in isolation.
/// @custom:oz-upgrades
/// @custom:bao-upgrades-from src/minter/StabilityPool_v2.sol:StabilityPool_v2
// solhint-disable-next-line contract-name-capwords
contract StabilityPool_v3_Upgrader is Initializable, UUPSUpgradeable, HarborFixedOwnable, IStabilityPool_v3_Upgrader {
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;

    /// @dev The linear distributor's ERC-7201 slot. Its storage LAYOUT is reached through the canonical
    ///      `LinearMultipleRewardDistributorStorage` type below, so only the slot is copied and it cannot drift; the
    ///      slot itself is verified against the namespace's canonical ERC-7201 hash by storage-successor (which
    ///      auto-detects the getter below), so a mistyped slot is caught.
    bytes32 private constant _LINEARMULTIPLEREWARDDISTRIBUTOR_STORAGE =
        0xe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d300;

    /// @dev The pool's ERC-7201 slot, reached through the canonical `StabilityPoolStorage` type below (same
    ///      auto-verified-slot guarantee as above).
    bytes32 private constant _STABILITYPOOL_STORAGE =
        0xcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e400;

    /// @dev The accumulator's ERC-7201 slot, reached through the canonical `MultipleRewardCompoundingAccumulatorStorage`
    ///      type below (same auto-verified-slot guarantee as above). Holds the per-holder reward snapshots.
    bytes32 private constant _MULTIPLEREWARDCOMPOUNDINGACCUMULATOR_STORAGE =
        0x47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7900;

    /// @param owner_ The account authorised to run the migration - the same account that owns the proxy (the Harbor
    ///        multisig in production).
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(address owner_) HarborFixedOwnable(address(0), owner_, 0) {
        _disableInitializers();
    }

    /// @inheritdoc IStabilityPool_v3_Upgrader
    function migrateAndUpgrade(
        int256 rewardDivisorGap,
        address[] calldata holders,
        Deduction[] calldata deductions,
        address stabilityPoolV3
    ) external onlyOwner {
        // v2 kept the loss product's exponent in byte 15 of a record's first slot, the top byte of what v3 reads as
        // the mantissa. v3 takes the exponent from bytes of the second slot v2 never wrote, so a record reads as v2
        // wrote it only where that byte is zero. A holder's record holds the supply's product as it was at the
        // holder's last checkpoint, and v2's exponent only rises until its eight bits wrap, so a supply's byte of zero
        // that never wrapped bounds every holder's, listed or not; the listed ones are checked all the same.
        StabilityPool_v3.StabilityPoolStorage storage $pool = _stabilityPoolStorage();
        uint8 supplyExponentByte = uint8($pool.totalAssetSupply.mantissa >> 120);
        if (supplyExponentByte != 0) {
            revert SupplyRecordExponentByteNotZero(supplyExponentByte);
        }
        for (uint256 h = 0; h < holders.length; ++h) {
            uint8 exponentByte = uint8($pool.assetBalances[holders[h]].mantissa >> 120);
            if (exponentByte != 0) {
                revert HolderRecordExponentByteNotZero(holders[h], exponentByte);
            }
        }

        LinearMultipleRewardDistributor_v3.LinearMultipleRewardDistributorStorage storage $reward = _rewardStorage();
        address[] memory tokens = $reward.activeRewardTokens.values();
        for (uint256 i = 0; i < tokens.length; ++i) {
            LinearReward.RewardData storage legacy = $reward.rewardDataUNUSED[tokens[i]];
            $reward.rewardData[tokens[i]] = LinearReward_v2.RewardData_v2({
                queued: legacy.queued,
                rate: legacy.rate,
                lastUpdate: legacy.lastUpdate,
                finishAt: legacy.finishAt
            });
        }

        // widen-copy each holder's per-token reward snapshot from the v2 (uint128 ClaimData) mapping into the v3
        // (uint256 ClaimData) mapping. The v3 claim-field widen relocated the snapshot to a fresh slot, so a plain
        // upgrade would read the empty v3 mapping and drop every holder's pending/claimed AND their checkpoint integral
        // (over-crediting future accrual from integral 0). `activeRewardTokens` is the COMPLETE token set here - the pool
        // has never unregistered a reward token - so no holder's pending is on a token this loop skips.
        MultipleRewardCompoundingAccumulator_v3.MultipleRewardCompoundingAccumulatorStorage
            storage $acc = _accumulatorStorage();
        for (uint256 h = 0; h < holders.length; ++h) {
            for (uint256 i = 0; i < tokens.length; ++i) {
                MultipleRewardCompoundingAccumulator_v3.UserRewardSnapshotV2 storage source = $acc
                    .userRewardSnapshotV2NOTUSED[holders[h]][tokens[i]];
                $acc.userRewardSnapshot[holders[h]][tokens[i]] = MultipleRewardCompoundingAccumulator_v3
                    .UserRewardSnapshotV3({
                        rewards: MultipleRewardCompoundingAccumulator_v3.ClaimDataV3({
                            pending: source.rewards.pending,
                            claimed: source.rewards.claimed
                        }),
                        timestamp: source.timestamp,
                        integral: source.integral
                    });
            }
        }

        // The gap before any checkpoint: the checkpoint folds the stream since the pool's last update into its
        // reward-per-share, dividing by the divisor the gap seeds.
        $pool.rewardDivisorGap = rewardDivisorGap;

        for (uint256 d = 0; d < deductions.length; ++d) {
            Deduction calldata deduction = deductions[d];
            // Settled by the new implementation's own checkpoint, on the storage just migrated: what the record then
            // holds as pending is exactly what the account may claim. A revert there is passed on unchanged.
            Address.functionDelegateCall(
                stabilityPoolV3,
                abi.encodeCall(IMultipleRewardAccumulator_v3.checkpoint, (deduction.account))
            );
            MultipleRewardCompoundingAccumulator_v3.ClaimDataV3 storage rewards = $acc
                .userRewardSnapshot[deduction.account][deduction.token]
                .rewards;
            uint256 claimable = rewards.pending;
            if (deduction.amount > claimable) {
                revert DeductionExceedsReward(deduction.account, deduction.token, deduction.amount, claimable);
            }
            rewards.pending = claimable - deduction.amount;
            emit RewardDeducted(deduction.account, deduction.token, deduction.amount);
            // The pool's own tokens, no longer owed to anyone, to the owner. The account's `claimed` is not touched:
            // it counts what the account received.
            IERC20(deduction.token).safeTransfer(owner(), deduction.amount);
        }

        upgradeToAndCall(stabilityPoolV3, "");
    }

    /// @inheritdoc UUPSUpgradeable
    function _authorizeUpgrade(address) internal override onlyOwner {} // solhint-disable-line no-empty-blocks

    /// @dev The distributor's namespaced storage, referenced through its canonical struct type at its fixed slot.
    function _rewardStorage()
        private
        pure
        returns (LinearMultipleRewardDistributor_v3.LinearMultipleRewardDistributorStorage storage $)
    {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            $.slot := _LINEARMULTIPLEREWARDDISTRIBUTOR_STORAGE
        }
    }

    /// @dev The accumulator's namespaced storage, referenced through its canonical struct type at its fixed slot.
    function _accumulatorStorage()
        private
        pure
        returns (MultipleRewardCompoundingAccumulator_v3.MultipleRewardCompoundingAccumulatorStorage storage $)
    {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            $.slot := _MULTIPLEREWARDCOMPOUNDINGACCUMULATOR_STORAGE
        }
    }

    /// @dev The pool's namespaced storage, referenced through its canonical struct type at its fixed slot.
    function _stabilityPoolStorage() private pure returns (StabilityPool_v3.StabilityPoolStorage storage $) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            $.slot := _STABILITYPOOL_STORAGE
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/minter/library/Config_v2.sol": {
      "Config_v2": "0xae95f3fe61Ffec38307Fb8361bCe2cE930413cA7"
    },
    "src/minter/library/RebalanceSizing_v1.sol": {
      "RebalanceSizing_v1": "0x5a84A236Df42adCe1044acEC91c27C3246B841BE"
    },
    "src/minter/library/MinterAdjustments_v1.sol": {
      "MinterAdjustments_v1": "0x410D41A753B634FfAfF33E27cEdE5ee22439F0fc"
    }
  },
  "optimizer": {
    "runs": 700,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "@solady/=lib/solady/src/",
    "@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts/src/v0.8/",
    "@bao/=lib/bao-base/src/",
    "@bao-test/=lib/bao-base/test/",
    "@bao-script/=lib/bao-base/script/",
    "@bao-factory/=lib/bao-base/lib/bao-factory/src/",
    "@bao-factory-test/=lib/bao-base/lib/bao-factory/test/",
    "@harbor/=src/",
    "@harbor-script/=script/",
    "@harbor-test/=test/",
    "src/=src/",
    "test/=test/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.