Skip to content
Verified contractPartialUNLICENSED

PryaBuyback

Address0x33f0cd76c850a082a2dfba63c5a48e278d853cbb
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.27

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,325,120
Creation transaction
0x8b5edcc295…8b4f1d336e
Libraries
src/libraries/TreasuryCow.sol:TreasuryCow0x0735…a0a97csrc/libraries/TreasuryFold.sol:TreasuryFold0x0f4e…d64a21src/libraries/TreasurySales.sol:TreasurySales0x1780…949d2a

97 files

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

src/PryaBuyback.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.27;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {WarehouseTreasury} from "./WarehouseTreasury.sol";
import {Warehouse} from "./Warehouse.sol";
import {WarehouseRegistry} from "./registries/WarehouseRegistry.sol";
import {StableReserveVault} from "./StableReserveVault.sol";
import {StableReserveRegistry} from "./registries/StableReserveRegistry.sol";
import {IPoolSwapTest, PoolKey, SwapParams, TestSettings} from "./V4FloorExecutor.sol";
import {Roles} from "./libraries/Roles.sol";

/// @title PryaBuyback — buy back and burn the protocol token from Treasury free cash (task 0302)
/// @notice The keeper's buyback lane opens a round at most once per `minGap`: if the Treasury's free cash is above
///         `threshold`, `shareBps` of it becomes the round's allowance. The lane then buys in tranches at times it
///         chooses: each tranche withdraws exactly its PRUSD from the Treasury's free cash, swaps it on the hookless
///         PRUSD-token Uniswap V4 pool, and burns every token received, in one transaction. Nothing runs while any pool
///         has an open or held liquidation cycle or is owed TAB, any warehouse has an open cycle, or any stable reserve has a repair gap (Tim's
///         waterfall rule: nothing reaches the token while a creditor or an impaired reserve is waiting). Each tranche
///         must be filled whole and pay at most `maxPrice` PRUSD per token. The contract holds nothing between calls.
///         Settings are admin-settable for the mainnet test only (pre-audit list).
contract PryaBuyback is AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 private constant BPS = 10_000;
    uint160 private constant MIN_SQRT = 4_295_128_739;
    uint160 private constant MAX_SQRT =
        1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342;

    WarehouseTreasury public immutable treasury;
    WarehouseRegistry public immutable warehouses;
    IERC20 public immutable prusd;
    ERC20Burnable public immutable token;
    IPoolSwapTest public immutable router;
    uint24 public immutable fee;
    int24 public immutable tickSpacing;

    uint256 public threshold; // free cash a round needs, PRUSD (18 decimals)
    uint256 public shareBps; // share of free cash a round may spend
    uint256 public minGap; // seconds between round openings
    uint256 public maxPrice; // most PRUSD paid per token (18 decimals)

    uint256 public roundOpenedAt;
    uint256 public roundAllowance;
    uint256 public roundSpent;

    event TermsSet(uint256 threshold, uint256 shareBps, uint256 minGap, uint256 maxPrice);
    event RoundOpened(uint256 freeCash, uint256 allowance);
    event BoughtAndBurned(uint256 prusdPaid, uint256 tokensBurned, uint256 roundSpent);

    error InvalidTerms();
    error ZeroAmount();
    error RoundTooSoon(uint256 opensAt);
    error BelowThreshold(uint256 freeCash, uint256 threshold);
    error OverAllowance(uint256 requested, uint256 left);
    error WarehouseWaiting(address warehouse);
    error PoolWaiting(uint256 poolId);
    error ReserveWaiting(address asset);
    error PartialFill(uint256 offered, uint256 consumed);
    error PriceAboveCeiling(uint256 paid, uint256 received);
    error BelowMinimum(uint256 received, uint256 minimum);

    constructor(
        address admin,
        WarehouseTreasury treasury_,
        WarehouseRegistry warehouses_,
        IERC20 prusd_,
        ERC20Burnable token_,
        IPoolSwapTest router_,
        uint24 fee_,
        int24 tickSpacing_,
        uint256 threshold_,
        uint256 shareBps_,
        uint256 minGap_,
        uint256 maxPrice_
    ) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        treasury = treasury_;
        warehouses = warehouses_;
        prusd = prusd_;
        token = token_;
        router = router_;
        fee = fee_;
        tickSpacing = tickSpacing_;
        _setTerms(threshold_, shareBps_, minGap_, maxPrice_);
    }

    /// @notice Test-only mutability (mainnet test, pre-audit list): the admin can change the round terms.
    function setTerms(uint256 threshold_, uint256 shareBps_, uint256 minGap_, uint256 maxPrice_)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        _setTerms(threshold_, shareBps_, minGap_, maxPrice_);
    }

    function openRound() external nonReentrant onlyRole(Roles.BUYBACK_ROLE) {
        if (roundOpenedAt != 0 && block.timestamp < roundOpenedAt + minGap) {
            revert RoundTooSoon(roundOpenedAt + minGap);
        }
        _requireNothingWaiting();
        uint256 free = treasury.spendableCash();
        if (free <= threshold) revert BelowThreshold(free, threshold);
        roundOpenedAt = block.timestamp;
        roundAllowance = free * shareBps / BPS;
        roundSpent = 0; // whatever the last round did not spend lapses
        emit RoundOpened(free, roundAllowance);
    }

    /// @notice Buy `amount` PRUSD of tokens and burn them. `minTokensOut` comes from the lane's fresh quote, so a price
    ///         pushed up before the tranche is refused; `maxPrice` stays as the backstop the lane cannot loosen.
    ///         Returns the tokens burned, so the lane quotes a tranche by simulating it with `minTokensOut` 0.
    function buy(uint256 amount, uint256 minTokensOut)
        external
        nonReentrant
        onlyRole(Roles.BUYBACK_ROLE)
        returns (uint256 burned)
    {
        if (amount == 0) revert ZeroAmount();
        uint256 left = roundAllowance - roundSpent;
        if (amount > left) revert OverAllowance(amount, left);
        _requireNothingWaiting();
        roundSpent += amount;

        // Measured against what was here before, so a donation to this contract can never block a purchase.
        uint256 prusdBefore = prusd.balanceOf(address(this));
        treasury.fundBuyback(amount);
        uint256 tokensBefore = token.balanceOf(address(this));
        bool zeroForOne = address(prusd) < address(token);
        prusd.forceApprove(address(router), amount);
        router.swap(
            PoolKey({
                currency0: zeroForOne ? address(prusd) : address(token),
                currency1: zeroForOne ? address(token) : address(prusd),
                fee: fee,
                tickSpacing: tickSpacing,
                hooks: address(0)
            }),
            SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amount),
                sqrtPriceLimitX96: zeroForOne ? MIN_SQRT + 1 : MAX_SQRT - 1
            }),
            TestSettings({takeClaims: false, settleUsingBurn: false}),
            ""
        );
        prusd.forceApprove(address(router), 0);
        uint256 unspent = prusd.balanceOf(address(this)) - prusdBefore;
        if (unspent != 0) revert PartialFill(amount, amount - unspent);
        uint256 received = token.balanceOf(address(this)) - tokensBefore;
        // Price paid per token, rounded against the purchase: amount / received <= maxPrice.
        if (received == 0 || amount * 1e18 > received * maxPrice) {
            revert PriceAboveCeiling(amount, received);
        }
        if (received < minTokensOut) revert BelowMinimum(received, minTokensOut);
        token.burn(received);
        emit BoughtAndBurned(amount, received, roundSpent);
        return received;
    }

    /// @dev Every warehouse the registry created (a seizure opens its cycle before the Treasury hears of it), then the
    ///      lists the waterfall reads: every pool in the Treasury's ledger and every stable reserve.
    function _requireNothingWaiting() private view {
        uint256 count = warehouses.warehouseCount();
        for (uint256 i; i < count; ++i) {
            address w = warehouses.warehouses(i);
            if (Warehouse(w).liquidationCycleOpen()) revert WarehouseWaiting(w);
        }
        count = treasury.ledgerPoolCount();
        for (uint256 i; i < count; ++i) {
            uint256 pid = treasury.ledgerPoolAt(i);
            address pool = treasury.poolRegistry().getPool(pid).pool;
            if (
                treasury.outstanding(pool) != 0 || treasury.activeLiquidationCycle(pid) != 0
                    || treasury.heldLiquidationCycleCount(pid) != 0
            ) revert PoolWaiting(pid);
        }
        StableReserveRegistry reserves = treasury.reserveRegistry();
        if (address(reserves) == address(0)) return;
        count = reserves.assetCount();
        for (uint256 i; i < count; ++i) {
            address asset = reserves.assetAt(i);
            if (StableReserveVault(reserves.reserveForAsset(asset)).repairGap() != 0) {
                revert ReserveWaiting(asset);
            }
        }
    }

    function _setTerms(uint256 threshold_, uint256 shareBps_, uint256 minGap_, uint256 maxPrice_)
        private
    {
        if (shareBps_ == 0 || shareBps_ > BPS || maxPrice_ == 0) revert InvalidTerms();
        threshold = threshold_;
        shareBps = shareBps_;
        minGap = minGap_;
        maxPrice = maxPrice_;
        emit TermsSet(threshold_, shareBps_, minGap_, maxPrice_);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/libraries/TreasuryCow.sol": {
      "TreasuryCow": "0x073588108c7Ae8EF49C634f0F02FB45C40a0a97c"
    },
    "src/libraries/TreasuryFold.sol": {
      "TreasuryFold": "0x0f4E2cDA7DEBd197493721eed4f7a132a3d64A21"
    },
    "src/libraries/TreasurySales.sol": {
      "TreasurySales": "0x1780fB5873F0692108B06D14Ab5df853C1949d2a"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/community-contracts/=lib/openzeppelin-community-contracts/contracts/",
    "@openzeppelin7540/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "composable-cow/=lib/composable-cow/src/",
    "lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "cowprotocol/=lib/composable-cow/lib/cowprotocol/src/",
    "safe/=lib/composable-cow/lib/safe/contracts/",
    "@axelar-network/axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/",
    "@openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/",
    "@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "@zk-email/contracts/=lib/openzeppelin-community-contracts/lib/zk-email-verify/packages/contracts/",
    "@zk-email/email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/packages/contracts/",
    "ds-test/=lib/composable-cow/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "murky/=lib/composable-cow/lib/murky/src/",
    "openzeppelin-community-contracts/=lib/openzeppelin-community-contracts/contracts/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/composable-cow/lib/@openzeppelin/contracts/",
    "wormhole-solidity-sdk/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.