Verified contractPartialMIT
Machine
Address0x5a2cc6b2d8f443e5d2aacd87c555a34c52aeed25
- Balance
0 ETH
- Transactions
172
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,441,476
- Creation transaction
- 0x31843aac11…cfdf1d5f60
Machine.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.16 >=0.6.2 ^0.8.20 ^0.8.24 ^0.8.28;
// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// src/interfaces/IConfig.sol
/// @notice SPHToken 外部配置源(参数唯一权威)
interface IConfig {
struct TradeParams {
address keeper;
address stakingContractAddress;
address referralContract;
address lpRewardAddress;
address contributionRewardAddress;
address autoLpManagerAddress;
address fundWallet;
uint256 buyFeeBps;
uint256 sellFeeBps;
uint256 extraSellTaxBps;
uint16 buyTaxLpBps;
uint16 buyTaxLpRewardBps;
uint16 buyTaxContributionBps;
uint16 buyTaxFundBps;
uint16 buyTaxBurnBps;
uint16 sellTaxLpRewardBps;
uint16 sellTaxFundBps;
uint16 sellTaxBurnBps;
bool purchaseOpen;
/// @notice 历史字段;当前 Staking.claim 不读取
bool claimOpen;
bool burnEnabled;
uint16 maxTxBpsOfPool;
uint32 minBlocksBeforeSell;
bool stopAll;
bool enablePerBlockTradeLimit;
uint256 perBlockMaxTradeCount;
uint256 perBlockMaxTradeAmount;
bool enableTxPoolTradeLimit;
uint256 txPoolTradeLockSize;
uint256 txPoolTradeAmountSize;
bool enableMinBlocksBeforeSell;
address sphToken;
bool sellOpen;
bool enableBuyTax;
bool enableSellTax;
bool enableAddLiquidityTax;
bool enableRemoveLiquidityTax;
}
function tradeParams() external view returns (TradeParams memory);
/// @notice Ethereum mainnet USDT
function usdt() external view returns (address);
/// @notice Uniswap V2 Router02(Ethereum mainnet)
function uniswapV2RouterAddress() external view returns (address);
function keeper() external view returns (address);
function stakingContractAddress() external view returns (address);
function referralContract() external view returns (address);
function buyFeeBps() external view returns (uint256);
function sellFeeBps() external view returns (uint256);
function extraSellTaxBps() external view returns (uint256);
/// @notice UTC 自然日基准价(sphToUsdt(1e18) 口径);keeper 写入,跨日未写则沿用
function utcDayBaselinePrice() external view returns (uint256);
/// @notice 历史字段:线性免跌宽度;阶梯卖税模式下不参与同步
function extraTaxFreeBps() external view returns (uint256);
/// @notice 仅 Security:按跌幅覆盖写入 extraSellTaxBps
function syncExtraSellTaxBps(uint256 bps) external;
function lpRewardAddress() external view returns (address);
function contributionRewardAddress() external view returns (address);
function autoLpManagerAddress() external view returns (address);
function fundWallet() external view returns (address);
function purchaseOpen() external view returns (bool);
function claimOpen() external view returns (bool);
function burnEnabled() external view returns (bool);
function maxTxBpsOfPool() external view returns (uint16);
/// @notice 买入 U 限额:本笔付出 U ≤ 底池 USDT reserve × bps/10000;0=关闭(Security 钩子)
function maxTxBpsOfPoolBuy() external view returns (uint16);
/// @notice 卖出 U 限额:本笔 SPH 税后估值 U ≤ 底池 USDT reserve × bps/10000;0=关闭(Security 钩子)
function maxTxBpsOfPoolSell() external view returns (uint16);
function minBlocksBeforeSell() external view returns (uint32);
function isExcludedFromFees(address account) external view returns (bool);
function isBlacklisted(address account) external view returns (bool);
function isRecycleToAddressPermission(
address to
) external view returns (bool);
function securityContractAddress() external view returns (address);
/// @notice 卖税沉淀合约;非 0 时 SPHToken 卖税整笔打入该地址
function taxContractAddress() external view returns (address);
/// @notice 静态/动态出局倍数(默认 1)
function exitMultiple() external view returns (uint256);
/// @notice 出局计量模式:0=币数 1=U(默认 0=币本位)
function exitMetricMode() external view returns (uint256);
/// @notice 静态阶段累计产出阈值(index 0..2)
function phaseThresholds(uint256 index) external view returns (uint256);
/// @notice 静态阶段小时利率 bps(index 0..2;20 => 0.02%/h)
function hourlyBps(uint256 index) external view returns (uint256);
/// @notice 建单最低 USDT(18 位)
function minOrderUsdt() external view returns (uint256);
/// @notice 有效账户最低持币价值 USDT(18 位)
function minHoldingUsdt() external view returns (uint256);
/// @notice 单次 claim 实发上限(SPH,18 位)
function maxClaimSph() external view returns (uint256);
/// @notice 两次 claim 最小间隔(秒);0=不限制
function minClaimInterval() external view returns (uint256);
/// @notice 静态产出总开关(false 则 Staking 不计息)
function productionEnabled() external view returns (bool);
function enablePerBlockTradeLimit() external view returns (bool);
function perBlockMaxTradeCount() external view returns (uint256);
function perBlockMaxTradeAmount() external view returns (uint256);
function enableTxPoolTradeLimit() external view returns (bool);
function txPoolTradeLockSize() external view returns (uint256);
function txPoolTradeAmountSize() external view returns (uint256);
function enableMinBlocksBeforeSell() external view returns (bool);
function sphToken() external view returns (address);
function sellOpen() external view returns (bool);
function enableBuyTax() external view returns (bool);
function enableSellTax() external view returns (bool);
function enableAddLiquidityTax() external view returns (bool);
function enableRemoveLiquidityTax() external view returns (bool);
/// @notice 系统日长度(秒)。上线一般为 86400,测试可压缩
function dayLength() external view returns (uint256);
/// @notice 系统起始时间戳,用于计算日期 index
function systemStartTimestamp() external view returns (uint256);
/// @notice 指定时间戳对应的系统日 index
function getDayIndex(uint256 timestamp) external view returns (uint256);
/// @notice 排队通道硬闸:false 时 join 与 pull / join 尾带匹配均不可执行(默认 false,首期启动时置 true)
function enableQueue() external view returns (bool);
/// @notice 暂停标志:true 时禁止一切匹配与自动开下一期;仍允许入队与判定
function queuePaused() external view returns (bool);
/// @notice 是否在 managePermission 名单内(owner 不必在名单内)
function hasManagePermission(address account) external view returns (bool);
/// @notice owner / managePermission / Queue 合约可调
function setEnableQueue(bool enabled) external;
/// @notice owner / managePermission / Queue 合约可调
function setQueuePaused(bool paused) external;
/// @notice 配置基准目标;owner / managePermission / Queue 合约可调
function setQueueTargetAmount(uint256 amount) external;
/// @notice 递增倍数;owner / managePermission / Queue 合约可调
function setQueueTargetIncreaseRatio(uint256 ratio) external;
/// @notice 排单周期,单位是 dayLength 的个数
function queuePeriod() external view returns (uint256);
/// @notice 配置基准目标(整枚 USDT);每次正式开期把该期实际目标写回,下一期 = 基准 × 倍数
function queueTargetAmount() external view returns (uint256);
/// @notice 排单额度乘数,分母 10000。13000 表示每期目标 × 1.3
function queueTargetIncreaseRatio() external view returns (uint256);
/// @notice 单地址最低入金,单位是整枚 USDT
function queueMinEntryAmount() external view returns (uint256);
/// @notice 单地址每个排单周期最高入金,单位是整枚 USDT
function queueMaxEntryAmount() external view returns (uint256);
/// @notice 排单静态收益比例,分母 10000
function queueStaticRewardRatio() external view returns (uint256);
/// @notice 排单静态收益提现手续费比例,分母 10000
function queueFeeRatio() external view returns (uint256);
/// @notice 排单收益分配:回购,分母 10000
function specifiedAddress() external view returns (uint256);
/// @notice 排单收益分配:保险池,分母 10000
function insurancePoolAddress() external view returns (uint256);
/// @notice 排单收益分配:生态,分母 10000
function ecosystemAddress() external view returns (uint256);
/// @notice 排单收益分配:风险池,分母 10000
function riskPoolAddress() external view returns (uint256);
/// @notice 强制复投时间,单位是 dayLength 的个数
function queueForceRecycleTime() external view returns (uint256);
/// @notice 排队合约地址(鉴权 pull→staking / machine sync)
function queueContract() external view returns (address);
/// @notice 提现手续费分配钱包
function queueFeeBuybackWallet() external view returns (address);
function queueFeeInsuranceWallet() external view returns (address);
function queueFeeEcosystemWallet() external view returns (address);
function queueFeeRiskWallet() external view returns (address);
/// @notice 每满多少 USDT 一台矿机
function machineSlotUsdt() external view returns (uint256);
/// @notice 矿机管理费周期,单位 dayLength 个数
function machineFeeDays() external view returns (uint256);
/// @notice 默认单台算力(1e18=1.0)
function machineDefaultPower() external view returns (uint256);
/// @notice 全网未销毁矿机数(owner 维护,用于管理费档位)
function machineAliveCount() external view returns (uint256);
/// @notice 管理费档位数量(固定)
function machineFeeTierCount() external pure returns (uint256);
/// @notice 第 index 档上限(含):aliveCount <= 该值则命中此档;最后一档为 type(uint256).max
function machineFeeTierMaxAlive(uint256 index) external view returns (uint256);
/// @notice 第 index 档每台管理费(整枚 USDT)
function machineFeeTierPrice(uint256 index) external view returns (uint256);
/// @notice 按全网 alive 数量取当前档位单价(整枚 USDT)
function machineFeePriceByAlive(uint256 alive) external view returns (uint256);
/// @notice 日产上限(SPH wei),默认 5000e18
function machineDailyOutputCap() external view returns (uint256);
/// @notice 减产周期,单位 dayLength 个数,默认 90
function machineReduceDays() external view returns (uint256);
/// @notice 每次减产比例,分母 10000,默认 1000=10%
function machineReduceRatio() external view returns (uint256);
/// @notice 单地址名下矿机软上限(热列表),默认 50;超额不新建
function machinePerUserSoftCap() external view returns (uint256);
/// @notice true=结算/sync 不扫已销毁(归档)机,默认 true
function machineSkipDestroyedInSettle() external view returns (bool);
/// @notice claim 单次最多处理机台数,默认 50
function machineClaimBatchSize() external view returns (uint256);
/// @notice claim/pending 单次最多回溯系统日,默认 30;0=不限制
function machinePendingLookbackDays() external view returns (uint256);
/// @notice 结算全网算力地板:peak × 该 bps / 10000;默认 9000=90%;0=关闭
function machinePowerFloorBps() external view returns (uint256);
/// @notice 单次 pull 最多处理订单数,默认 10
function queuePullMaxOrders() external view returns (uint256);
/// @notice 单次从游标起最多扫描订单数,默认 32
function queuePullScanLimit() external view returns (uint256);
/// @notice true=匹配后延后 sync 矿机,默认 false(当场 sync)
function queueDeferMachineSync() external view returns (bool);
function enableCredentialPurchase() external view returns (bool);
function onlyAllowWhiteListPurchase() external view returns (bool);
/// @notice 凭证单价,单位是整枚 USDT
function credentialPrice() external view returns (uint256);
/// @notice 入队扣凭证百分比:扣量 = amount * 本值 / 100(整枚);取值 1–100,默认 100
function queueCredentialBurnPercent() external view returns (uint256);
/// @notice 白名单折扣比例,分母 10000
function whiteListDiscountRatio() external view returns (uint256);
function addsCouldCallCredentialBurn(
address account
) external view returns (bool);
/// @notice 购买凭证的 USDT 收款地址
function credentialDepositAddress() external view returns (address);
/// @notice 团队/级差奖励无法发放时的沉淀地址
function teamRewardSinkAddress() external view returns (address);
/// @notice 直推奖无法发放时的沉淀地址
function directRewardSinkAddress() external view returns (address);
/// @notice 平级奖无法发放时的沉淀地址
function peerRewardSinkAddress() external view returns (address);
/// @notice 级差/团队业绩/升级刷新向上层数(默认 30)
function dynamicRewardDepth() external view returns (uint256);
/// @notice 清算合约
function liquidationContract() external view returns (address);
/// @notice 矿机合约(可 bump alive)
function machineContract() external view returns (address);
/// @notice 管理费分账合约
function manageFeeContract() external view returns (address);
/// @notice 矿机产出线性释放合约
function sphLinearRelease() external view returns (address);
/// @notice true=claimMining 按价档拆锁仓入 SphLinearRelease
function enableMiningLinearRelease() external view returns (bool);
/// @notice 线性释放天数 N(入账重置),默认 100
function linearReleaseDays() external view returns (uint256);
/// @notice 价档 i 的最低价(USDT raw / 1e18 SPH),升序
function miningLockMinPrice(uint256 index) external view returns (uint256);
/// @notice 价档 i 的锁仓 bps
function miningLockBps(uint256 index) external view returns (uint256);
/// @notice 按瞬时价(USDT raw / 1e18 SPH)取锁仓 bps
function miningLockBpsForPrice(uint256 priceUsdtPerSph) external view returns (uint256);
/// @notice SPH 凭证合约
function sphCredential() external view returns (address);
/// @notice 损失额换台除数,默认 200
function liquidationLossDivisor() external view returns (uint256);
/// @notice 余数令牌:每枚凭证对应多少整枚 USDT,默认 1
function liquidationTokenUsdt() external view returns (uint256);
/// @notice 上两期本金返还比例,分母 10000,默认 5000=50%
function liquidationRefundBps() external view returns (uint256);
/// @notice 用户领取爆仓矿机时单笔最多铸造台数
function liquidationBatchMachines() external view returns (uint256);
/// @notice 是否可从凭证库存发放(爆仓余数令牌)
function addsCouldCallCredentialGrant(address account) external view returns (bool);
/// @notice 矿机合约调整活机数
function bumpMachineAliveCount(int256 delta) external;
}
// lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// src/interfaces/ILevelLogic.sol
/// @notice 可替换的等级规则:撑机/团队业绩 + 直推人数;门槛/bps 由实现合约可配
interface ILevelLogic {
/// @notice 潜在等级(业绩+直推人数门槛;不含有效用户门槛)
function computePotentialLevel(address user) external view returns (uint8);
/// @notice 当前等级:非有效用户为 0;否则同 computePotentialLevel
function currentLevel(address account) external view returns (uint8);
/// @notice 当前是否有效用户:撑机本金>0
function isEffectiveUser(address user) external view returns (bool);
/// @notice 等级对应累计级差占比(万分比)
function levelBps(uint8 level) external view returns (uint256);
/// @notice 级差总档上限(万分比)
function maxLevelBps() external view returns (uint256);
/// @notice 兼容旧名:同步撑机业绩并调整上级团队业绩缓存
function refreshFrom(address start) external;
/// @notice 按当前撑机同步 personalSupport,并对上级 depth 层 ±delta(减不够则置 0)
function syncSupportVolume(address user) external;
/// @notice 沿推荐链向上找第一个与 user 同 `currentLevel` 的上级;user 等级为 0 或找不到则返回 address(0)
function findPeerUpline(address user) external view returns (address);
}
// src/interfaces/ILiquidation.sol
interface ILiquidation {
function supportingMatchedPrincipal(address user) external view returns (uint256);
function periodJudged(uint256 period) external view returns (bool);
function periodOutcome(uint256 period) external view returns (uint8);
/// @notice Queue join/pull 兜底:判定已到期的开放期,成功则尝试连开;无待处理时不 revert
function processPeriodsCatchUp() external;
/// @notice 仅 Queue.restartCampaign 调用:打重开退本标(截止到最近一次正式开出的期)
function markRestartSettlement() external;
}
// src/interfaces/IManageFee.sol
/// @notice 管理费分账:Machine 缴费后调用
interface IManageFee {
/// @param amountRaw 本次实转 USDT raw(1e6 = 1U)
/// @param machineCount 台数(固定 3/10/1 × 台)
/// @param payer 缴费人
/// @param machineId 单台真实 ID;batch 可为 0
/// @param feeDays 本次覆盖配置天数(如 28;架子可忽略)
/// @param priceWhole 档位单价整枚 USDT/台(架子可忽略)
/// @param periodId 管理费定价期号(架子可忽略)
function sendManageFee(
uint256 amountRaw,
uint256 machineCount,
address payer,
uint256 machineId,
uint256 feeDays,
uint256 priceWhole,
uint256 periodId
) external;
}
// src/interfaces/ISPHToken.sol
interface ISPHToken {
function recycle(
uint256 amount,
address pairAddress,
address to
) external;
function mint(address to, uint256 amount) external;
function uniswapV2PairAddress() external view returns (address);
function sphToUsdt(uint256 sphAmount) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function config() external view returns (address);
}
// src/interfaces/ISphLinearRelease.sol
interface ISphLinearRelease {
/// @notice Machine 在 mint 锁仓额到本合约后通知入账
function notifyDeposit(address user, uint256 amount) external;
function claim() external;
function accounts(
address user
)
external
view
returns (uint256 balance, uint256 releasePerDay, uint256 remainDays, uint256 lastClaimDay);
}
// lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
// lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// src/MachineStorage.sol
/// @title 矿机数据
contract MachineStorage is Ownable {
uint8 public constant STATUS_INACTIVE = 0;
uint8 public constant STATUS_ACTIVE = 1;
uint8 public constant STATUS_DESTROYED = 2;
struct Machine {
address owner;
uint8 status;
uint8 mType;
uint256 power;
uint256 feePaidUntil;
uint256 inactiveSince;
}
address public machine;
uint256 public nextMachineId = 1;
mapping(uint256 => Machine) public machines;
/// @notice 热列表:未销毁机
mapping(address => uint256[]) public userMachines;
/// @notice 归档:已销毁机(供 getMachines 展示)
mapping(address => uint256[]) public userArchivedMachines;
/// @notice 管理费当期定价
uint256 public feePeriodId;
uint256 public feePricePerMachine;
/// @notice 全网 / 个人已激活算力(1e18 = 1.0)
uint256 public totalActivePower;
mapping(address => uint256) public userActivePower;
/// @notice 用户领取时钟(兼容;结算以机台 liveFrom / accrued 为准)
mapping(address => uint256) public lastClaimedDay;
mapping(address => bool) public claimInitialized;
/// @notice claim 批处理游标(热列表下标)
mapping(address => uint256) public userClaimCursor;
/// @notice 每台累计已领取记账、未领取已结算
mapping(uint256 => uint256) public claimedOutput;
mapping(uint256 => uint256) public accruedOutput;
/// @notice 销毁归档时并入的未领产出(claim 时一并领取)
mapping(address => uint256) public userPocketAccrued;
/// @notice 机台当前连续 ACTIVE 段起始系统日+1;0=当前非 live(因系统日可为 0)
mapping(uint256 => uint256) public machineLiveFromDay;
/// @notice 稀疏全网算力:仅保留最后一次快照
uint256 public powerSnapDay;
uint256 public powerSnapValue;
bool public powerSnapInit;
/// @notice 全网有效算力历史峰值(自动只增;可由 Machine 经 owner/keeper 手调)
uint256 public peakActivePower;
error ZeroAddress();
error NotMachine();
error BadMachine();
modifier onlyMachine() {
if (msg.sender != machine || machine == address(0)) revert NotMachine();
_;
}
constructor() Ownable(msg.sender) {}
function setMachine(address machine_) external onlyOwner {
if (machine_ == address(0)) revert ZeroAddress();
machine = machine_;
}
function userMachineCount(address user) external view returns (uint256) {
return userMachines[user].length;
}
function userArchivedCount(address user) external view returns (uint256) {
return userArchivedMachines[user].length;
}
function createMachine(address owner_, uint256 power) external onlyMachine returns (uint256 id) {
return _create(owner_, power, 0);
}
/// @notice 创建矿机;mType 0=排队 1=爆仓 2=赠送
function createMachineWithType(
address owner_,
uint256 power,
uint8 mType
) external onlyMachine returns (uint256 id) {
return _create(owner_, power, mType);
}
function _create(
address owner_,
uint256 power,
uint8 mType
) internal returns (uint256 id) {
id = nextMachineId;
nextMachineId = id + 1;
machines[id] = Machine({
owner: owner_,
status: STATUS_INACTIVE,
mType: mType,
power: power,
feePaidUntil: 0,
inactiveSince: 0
});
userMachines[owner_].push(id);
}
/// @notice 将已销毁机从热列表移入归档;未领 accrued 并入用户口袋
function moveToArchive(uint256 id) external onlyMachine {
Machine storage m = machines[id];
if (m.status != STATUS_DESTROYED) revert BadMachine();
address owner_ = m.owner;
uint256 owed = accruedOutput[id];
if (owed != 0) {
accruedOutput[id] = 0;
userPocketAccrued[owner_] += owed;
}
uint256[] storage hot = userMachines[owner_];
uint256 n = hot.length;
for (uint256 i; i < n; ) {
if (hot[i] == id) {
hot[i] = hot[n - 1];
hot.pop();
userArchivedMachines[owner_].push(id);
return;
}
unchecked {
++i;
}
}
}
function claimPocketAccrued(address user) external onlyMachine returns (uint256 amount) {
amount = userPocketAccrued[user];
if (amount == 0) return 0;
userPocketAccrued[user] = 0;
// 口袋金额无单机 claimed 明细,仅汇总转出
}
function setStatus(uint256 id, uint8 status, uint256 inactiveSince) external onlyMachine {
Machine storage m = machines[id];
uint8 old = m.status;
if (old == STATUS_ACTIVE && status != STATUS_ACTIVE) {
totalActivePower -= m.power;
userActivePower[m.owner] -= m.power;
} else if (old != STATUS_ACTIVE && status == STATUS_ACTIVE) {
totalActivePower += m.power;
userActivePower[m.owner] += m.power;
}
m.status = status;
m.inactiveSince = inactiveSince;
}
function setFeePaidUntil(uint256 id, uint256 until) external onlyMachine {
machines[id].feePaidUntil = until;
}
function setFeePeriod(uint256 periodId, uint256 price) external onlyMachine {
feePeriodId = periodId;
feePricePerMachine = price;
}
function setLastClaimedDay(address user, uint256 dayIndex) external onlyMachine {
lastClaimedDay[user] = dayIndex;
claimInitialized[user] = true;
}
function setUserClaimCursor(address user, uint256 cursor) external onlyMachine {
userClaimCursor[user] = cursor;
}
function setMachineLiveFromDay(uint256 id, uint256 day) external onlyMachine {
machineLiveFromDay[id] = day;
}
function addAccruedOutput(uint256 id, uint256 amount) external onlyMachine {
if (amount == 0) return;
accruedOutput[id] += amount;
}
function claimAccrued(uint256 id) external onlyMachine returns (uint256 amount) {
amount = accruedOutput[id];
if (amount == 0) return 0;
accruedOutput[id] = 0;
claimedOutput[id] += amount;
}
function setPowerSnap(uint256 day, uint256 power) external onlyMachine {
powerSnapDay = day;
powerSnapValue = power;
powerSnapInit = true;
}
/// @notice 观测算力高于 peak 时上调
function bumpPeakActivePower(uint256 observed) external onlyMachine {
if (observed > peakActivePower) {
peakActivePower = observed;
}
}
/// @notice 手调 peak(含调低);仅 Machine 合约可调
function setPeakActivePower(uint256 peak) external onlyMachine {
peakActivePower = peak;
}
}
// src/QueueStorage.sol
/// @title 排单与期模型账本。金额:入队/匹配本金为整枚 USDT。
/// @dev 普通/优先队为双向链表;仅 Queue 可写(onlyQueue)。
contract QueueStorage is Ownable {
uint8 public constant QUEUE_NONE = 0;
uint8 public constant QUEUE_NORMAL = 1;
uint8 public constant QUEUE_PRIORITY = 2;
struct Order {
address user;
uint256 amount;
uint256 period;
/// @notice 入队时间;部分匹配减额不改
uint256 joinedAt;
uint256 prev;
uint256 next;
uint8 queueKind;
}
address public queue;
uint256 public nextOrderId = 1;
mapping(uint256 => Order) public orders;
uint256 public normalHead;
uint256 public normalTail;
uint256 public normalLength;
uint256 public priorityHead;
uint256 public priorityTail;
uint256 public priorityLength;
/// @notice 扫描游标(orderId);0 表示从队头开始
uint256 public normalCursor;
uint256 public priorityCursor;
mapping(uint256 => uint256) public periodMatched;
mapping(uint256 => uint256) public periodTarget;
mapping(address => uint256[]) public userActiveOrders;
mapping(address => uint256) public userQueuedAmount;
// ------------------------------------------------------------------
// 期模型(原 Queue 状态)
// ------------------------------------------------------------------
uint256 public currentOpenPeriod;
uint256 public latestOpenedPeriod;
mapping(uint256 => uint256) public periodOpenedAt;
mapping(uint256 => uint256) public periodEndTime;
bytes32 public logicalPrefix;
uint256 public logicalSeq;
mapping(bytes32 => bool) public usedPrefixes;
mapping(uint256 => bytes32) public periodPrefix;
mapping(uint256 => uint256) public periodSeq;
mapping(bytes32 => uint256) public periodByNameHash;
error ZeroAddress();
error NotQueue();
error OrderNotFound();
error BadIndex();
error BadFill();
error NotInQueue();
modifier onlyQueue() {
if (msg.sender != queue || queue == address(0)) revert NotQueue();
_;
}
constructor() Ownable(msg.sender) {}
function setQueue(address queue_) external onlyOwner {
if (queue_ == address(0)) revert ZeroAddress();
queue = queue_;
}
function userActiveOrderCount(address user) external view returns (uint256) {
return userActiveOrders[user].length;
}
function isPriority(uint256 orderId) public view returns (bool) {
return orders[orderId].queueKind == QUEUE_PRIORITY;
}
function isInQueue(uint256 orderId) public view returns (bool) {
return orders[orderId].queueKind != QUEUE_NONE;
}
function orderNext(uint256 orderId) external view returns (uint256) {
return orders[orderId].next;
}
function orderUserAmount(uint256 orderId) external view returns (address user, uint256 amount) {
Order storage o = orders[orderId];
return (o.user, o.amount);
}
/// @notice 逻辑下标访问(0=队头);链下/兼容用,O(index)
function normalAt(uint256 index) external view returns (uint256) {
return _at(normalHead, normalLength, index);
}
function priorityAt(uint256 index) external view returns (uint256) {
return _at(priorityHead, priorityLength, index);
}
/// @notice 仍在队且已满 waitSeconds 的订单金额之和(新建矿机用)
function userMatureQueuedAmount(
address user,
uint256 waitSeconds
) external view returns (uint256 total) {
uint256[] storage list = userActiveOrders[user];
uint256 n = list.length;
for (uint256 i; i < n; ) {
Order storage o = orders[list[i]];
if (block.timestamp >= o.joinedAt + waitSeconds) {
total += o.amount;
}
unchecked {
++i;
}
}
}
// ------------------------------------------------------------------
// 订单 / 链表写
// ------------------------------------------------------------------
function createNormalOrder(
address user,
uint256 amount
) external onlyQueue returns (uint256 id) {
id = nextOrderId;
nextOrderId = id + 1;
orders[id] = Order({
user: user,
amount: amount,
period: 0,
joinedAt: block.timestamp,
prev: 0,
next: 0,
queueKind: QUEUE_NONE
});
userQueuedAmount[user] += amount;
userActiveOrders[user].push(id);
_pushBack(QUEUE_NORMAL, id);
}
function placePriority(uint256 orderId, uint256 index) external onlyQueue {
Order storage o = orders[orderId];
if (o.user == address(0)) revert OrderNotFound();
if (o.queueKind == QUEUE_NONE) revert NotInQueue();
_unlink(orderId);
if (index > priorityLength) revert BadIndex();
_insertAt(QUEUE_PRIORITY, orderId, index);
}
/// @notice 按 orderId 从所在链表摘除(须仍在队中)
function unlinkOrder(uint256 orderId) external onlyQueue {
if (orders[orderId].queueKind == QUEUE_NONE) revert NotInQueue();
_unlink(orderId);
}
function finalizeMatched(uint256 orderId) external onlyQueue {
Order memory o = orders[orderId];
if (o.user == address(0)) revert OrderNotFound();
_removeActive(o.user, orderId);
userQueuedAmount[o.user] -= o.amount;
}
function reduceOrderAmount(uint256 orderId, uint256 fill) external onlyQueue {
Order storage o = orders[orderId];
if (o.user == address(0)) revert OrderNotFound();
if (fill == 0 || fill >= o.amount) revert BadFill();
o.amount -= fill;
userQueuedAmount[o.user] -= fill;
}
function cancelOrder(uint256 orderId) external onlyQueue returns (Order memory o) {
o = orders[orderId];
if (o.user == address(0)) revert OrderNotFound();
if (o.queueKind == QUEUE_NONE) revert NotInQueue();
_unlink(orderId);
_removeActive(o.user, orderId);
userQueuedAmount[o.user] -= o.amount;
delete orders[orderId];
}
function assignOrderPeriod(uint256 orderId, uint256 period) external onlyQueue {
Order storage o = orders[orderId];
if (o.user == address(0)) revert OrderNotFound();
o.period = period;
}
function setPeriodMatched(uint256 period, uint256 amount) external onlyQueue {
periodMatched[period] = amount;
}
function setPeriodTarget(uint256 period, uint256 target) external onlyQueue {
periodTarget[period] = target;
}
function setNormalCursor(uint256 orderId) external onlyQueue {
normalCursor = orderId;
}
function setPriorityCursor(uint256 orderId) external onlyQueue {
priorityCursor = orderId;
}
function resetScanCursors() external onlyQueue {
normalCursor = 0;
priorityCursor = 0;
}
// ------------------------------------------------------------------
// 期模型写
// ------------------------------------------------------------------
function setCurrentOpenPeriod(uint256 period) external onlyQueue {
currentOpenPeriod = period;
}
function setLatestOpenedPeriod(uint256 period) external onlyQueue {
latestOpenedPeriod = period;
}
function setPeriodOpenedAt(uint256 period, uint256 openedAt) external onlyQueue {
periodOpenedAt[period] = openedAt;
}
function setPeriodEndTime(uint256 period, uint256 endTime) external onlyQueue {
periodEndTime[period] = endTime;
}
function setLogicalPrefix(bytes32 prefix) external onlyQueue {
logicalPrefix = prefix;
}
function setLogicalSeq(uint256 seq) external onlyQueue {
logicalSeq = seq;
}
function markPrefixUsed(bytes32 prefix) external onlyQueue {
usedPrefixes[prefix] = true;
}
function setPeriodPrefix(uint256 period, bytes32 prefix) external onlyQueue {
periodPrefix[period] = prefix;
}
function setPeriodSeq(uint256 period, uint256 seq) external onlyQueue {
periodSeq[period] = seq;
}
function setPeriodByNameHash(bytes32 nameHash, uint256 period) external onlyQueue {
if (periodByNameHash[nameHash] == 0) {
periodByNameHash[nameHash] = period;
}
}
// ------------------------------------------------------------------
// 链表内部
// ------------------------------------------------------------------
function _at(uint256 head, uint256 len, uint256 index) internal view returns (uint256) {
if (index >= len) revert BadIndex();
uint256 id = head;
for (uint256 i; i < index; ) {
id = orders[id].next;
unchecked {
++i;
}
}
return id;
}
function _pushBack(uint8 kind, uint256 orderId) internal {
Order storage o = orders[orderId];
o.queueKind = kind;
o.prev = 0;
o.next = 0;
if (kind == QUEUE_NORMAL) {
if (normalHead == 0) {
normalHead = orderId;
normalTail = orderId;
} else {
orders[normalTail].next = orderId;
o.prev = normalTail;
normalTail = orderId;
}
unchecked {
++normalLength;
}
} else {
if (priorityHead == 0) {
priorityHead = orderId;
priorityTail = orderId;
} else {
orders[priorityTail].next = orderId;
o.prev = priorityTail;
priorityTail = orderId;
}
unchecked {
++priorityLength;
}
}
}
function _insertAt(uint8 kind, uint256 orderId, uint256 index) internal {
if (kind == QUEUE_PRIORITY) {
if (index >= priorityLength) {
_pushBack(QUEUE_PRIORITY, orderId);
return;
}
uint256 at = _at(priorityHead, priorityLength, index);
_insertBefore(QUEUE_PRIORITY, orderId, at);
} else {
if (index >= normalLength) {
_pushBack(QUEUE_NORMAL, orderId);
return;
}
uint256 at = _at(normalHead, normalLength, index);
_insertBefore(QUEUE_NORMAL, orderId, at);
}
}
function _insertBefore(uint8 kind, uint256 orderId, uint256 beforeId) internal {
Order storage o = orders[orderId];
Order storage b = orders[beforeId];
o.queueKind = kind;
o.next = beforeId;
o.prev = b.prev;
if (b.prev == 0) {
if (kind == QUEUE_PRIORITY) priorityHead = orderId;
else normalHead = orderId;
} else {
orders[b.prev].next = orderId;
}
b.prev = orderId;
if (kind == QUEUE_PRIORITY) {
unchecked {
++priorityLength;
}
} else {
unchecked {
++normalLength;
}
}
}
function _unlink(uint256 orderId) internal {
Order storage o = orders[orderId];
uint8 kind = o.queueKind;
if (kind == QUEUE_NONE) return;
if (normalCursor == orderId) normalCursor = o.next;
if (priorityCursor == orderId) priorityCursor = o.next;
if (o.prev != 0) orders[o.prev].next = o.next;
if (o.next != 0) orders[o.next].prev = o.prev;
if (kind == QUEUE_NORMAL) {
if (normalHead == orderId) normalHead = o.next;
if (normalTail == orderId) normalTail = o.prev;
unchecked {
--normalLength;
}
} else {
if (priorityHead == orderId) priorityHead = o.next;
if (priorityTail == orderId) priorityTail = o.prev;
unchecked {
--priorityLength;
}
}
o.prev = 0;
o.next = 0;
o.queueKind = QUEUE_NONE;
}
function _removeActive(address user, uint256 orderId) internal {
uint256[] storage list = userActiveOrders[user];
uint256 n = list.length;
for (uint256 i; i < n; ) {
if (list[i] == orderId) {
list[i] = list[n - 1];
list.pop();
return;
}
unchecked {
++i;
}
}
}
}
// lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
// lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
// src/Machine.sol
interface IStakingLevelLogicView {
function levelLogic() external view returns (address);
}
/// @title 矿机写路径。台数同步、缴费、claim;只读见 MachineView
contract Machine is Ownable {
using SafeERC20 for IERC20;
uint256 private constant USDT_UNIT = 1e6;
uint256 private constant BPS = 10_000;
/// @dev 0=排队。非 0(1=爆仓,2=赠送)只看管理费,不占排队名额,不因撑机不足销毁
uint8 private constant MTYPE_QUEUE = 0;
uint8 private constant MTYPE_LIQUIDATION = 1;
uint8 private constant MTYPE_GIFT = 2;
address public config;
QueueStorage public queueStorage;
MachineStorage public machineStorage;
error ZeroAddress();
error ConfigNotSet();
error NotAuth();
error BadMachine();
error Destroyed();
error NothingToPay();
error NothingToClaim();
error SphNotSet();
error NotOwnerOrKeeper();
error ManageFeeUnset();
event ConfigSet(address indexed config);
event QueueStorageSet(address indexed queueStorage);
event MachineStorageSet(address indexed machineStorage);
event Synced(address indexed user, uint256 queued, uint256 slots);
event FeePaid(address indexed user, uint256 indexed machineId, uint256 until, uint256 price);
event MiningClaimed(address indexed user, uint256 amount);
event PeakActivePowerSet(uint256 peak);
event MachinesGifted(address indexed user, uint256 count);
constructor() Ownable(msg.sender) {}
function setConfig(address config_) external onlyOwner {
if (config_ == address(0)) revert ZeroAddress();
config = config_;
emit ConfigSet(config_);
}
function setQueueStorage(address store_) external onlyOwner {
if (store_ == address(0)) revert ZeroAddress();
queueStorage = QueueStorage(store_);
emit QueueStorageSet(store_);
}
function setMachineStorage(address store_) external onlyOwner {
if (store_ == address(0)) revert ZeroAddress();
machineStorage = MachineStorage(store_);
emit MachineStorageSet(store_);
}
function rescueToken(
address token,
address to,
uint256 amount
) external onlyOwner {
if (token == address(0) || to == address(0)) revert ZeroAddress();
IERC20(token).safeTransfer(to, amount);
}
/// @notice owner 或 config.keeper 手调全网算力峰值(可调低)
function setPeakActivePower(uint256 peak) external {
IConfig cfg = _cfg();
if (msg.sender != owner() && msg.sender != cfg.keeper()) revert NotOwnerOrKeeper();
machineStorage.setPeakActivePower(peak);
emit PeakActivePowerSet(peak);
}
function syncUser(address user) public {
IConfig cfg = _cfg();
if (
msg.sender != user &&
msg.sender != owner() &&
msg.sender != cfg.queueContract() &&
msg.sender != cfg.liquidationContract()
) revert NotAuth();
_syncSupportVolume(cfg, user);
uint256 slot = cfg.machineSlotUsdt();
uint256 queued = queueStorage.userQueuedAmount(user);
uint256 locked = _supportingMatched(cfg, user);
// 已有机占名额看撑机本金;新建只看成熟排队额
uint256 need = (queued + locked) / slot;
uint256 grace = cfg.queueForceRecycleTime() * cfg.dayLength();
uint256 softCap = cfg.machinePerUserSoftCap();
MachineStorage store = machineStorage;
_destroyExpired(store, cfg, user, grace);
{
uint256 createTarget = queueStorage.userMatureQueuedAmount(user, cfg.dayLength()) / slot;
uint256 queueAlive = _countQueueMachines(store, user);
while (queueAlive < createTarget && queueAlive < softCap) {
store.createMachine(user, cfg.machineDefaultPower());
unchecked {
++queueAlive;
}
}
}
uint256 filled;
uint256 n = store.userMachineCount(user);
for (uint256 i; i < n; ) {
filled = _syncOneMachine(store, cfg, user, i, need, filled);
unchecked {
++i;
}
}
if (!store.claimInitialized(user)) {
store.setLastClaimedDay(user, cfg.getDayIndex(block.timestamp));
}
emit Synced(user, queued + locked, need);
}
function _supportingMatched(
IConfig cfg,
address user
) internal view returns (uint256) {
address liq = cfg.liquidationContract();
if (liq == address(0)) return 0;
return ILiquidation(liq).supportingMatchedPrincipal(user);
}
function _syncSupportVolume(IConfig cfg, address user) internal {
address stakingAddr = cfg.stakingContractAddress();
if (stakingAddr == address(0)) return;
address ll = IStakingLevelLogicView(stakingAddr).levelLogic();
if (ll == address(0)) return;
ILevelLogic(ll).syncSupportVolume(user);
}
function payFee(uint256 machineId) external {
MachineStorage store = machineStorage;
(address own, uint8 status, , , uint256 feeUntil, ) = store.machines(machineId);
if (own != msg.sender) revert BadMachine();
if (status == store.STATUS_DESTROYED()) revert Destroyed();
IConfig cfg = _cfg();
uint256 price = _ensureFeePrice(cfg);
if (price == 0) revert NothingToPay();
address feeTo = _requireManageFee(cfg);
uint256 amountRaw = price * USDT_UNIT;
IERC20(cfg.usdt()).safeTransferFrom(msg.sender, feeTo, amountRaw);
uint256 until = _extendOneFee(store, machineId, feeUntil);
_dispatchManageFee(feeTo, amountRaw, 1, machineId, price);
syncUser(msg.sender);
emit FeePaid(msg.sender, machineId, until, price);
}
function payFeeBatch(uint256[] calldata machineIds) external {
uint256 n = machineIds.length;
if (n == 0) revert NothingToPay();
IConfig cfg = _cfg();
uint256 price = _ensureFeePrice(cfg);
if (price == 0) revert NothingToPay();
address feeTo = _requireManageFee(cfg);
uint256 amountRaw = price * n * USDT_UNIT;
IERC20(cfg.usdt()).safeTransferFrom(msg.sender, feeTo, amountRaw);
_extendFeesBatch(machineIds, price);
_dispatchManageFee(feeTo, amountRaw, n, 0, price);
syncUser(msg.sender);
}
function _requireManageFee(IConfig cfg) internal view returns (address feeTo) {
feeTo = cfg.manageFeeContract();
if (feeTo == address(0)) revert ManageFeeUnset();
}
function _extendOneFee(
MachineStorage store,
uint256 machineId,
uint256 feeUntil
) internal returns (uint256 until) {
IConfig cfg = _cfg();
until = (feeUntil > block.timestamp ? feeUntil : block.timestamp) +
cfg.machineFeeDays() *
cfg.dayLength();
store.setFeePaidUntil(machineId, until);
}
function _extendFeesBatch(uint256[] calldata machineIds, uint256 price) internal {
MachineStorage store = machineStorage;
IConfig cfg = _cfg();
uint256 periodLen = cfg.machineFeeDays() * cfg.dayLength();
uint256 n = machineIds.length;
for (uint256 i; i < n; ) {
uint256 machineId = machineIds[i];
(address own, uint8 status, , , uint256 feeUntil, ) = store.machines(machineId);
if (own != msg.sender) revert BadMachine();
if (status == store.STATUS_DESTROYED()) revert Destroyed();
uint256 until = (feeUntil > block.timestamp ? feeUntil : block.timestamp) + periodLen;
store.setFeePaidUntil(machineId, until);
emit FeePaid(msg.sender, machineId, until, price);
unchecked {
++i;
}
}
}
function _dispatchManageFee(
address feeTo,
uint256 amountRaw,
uint256 machineCount,
uint256 machineId,
uint256 priceWhole
) internal {
IConfig cfg = _cfg();
uint256 feeDays = cfg.machineFeeDays();
IManageFee(feeTo).sendManageFee(
amountRaw,
machineCount,
msg.sender,
machineId,
feeDays,
priceWhole,
cfg.getDayIndex(block.timestamp) / feeDays
);
}
/// @notice 领取:热列表最多 K 台 × 回溯 D 日;口袋未领一并转出
function claimMining() external {
syncUser(msg.sender);
IConfig cfg = _cfg();
address sph = cfg.sphToken();
if (sph == address(0)) revert SphNotSet();
MachineStorage store = machineStorage;
uint256 today = cfg.getDayIndex(block.timestamp);
uint256 lookback = cfg.machinePendingLookbackDays();
uint256 batch = cfg.machineClaimBatchSize();
uint256 amount = _claimHotBatch(store, cfg, msg.sender, today, lookback, batch);
amount += store.claimPocketAccrued(msg.sender);
if (!cfg.machineSkipDestroyedInSettle()) {
amount += _drainArchiveAccrued(store, msg.sender);
}
if (amount == 0) revert NothingToClaim();
store.setLastClaimedDay(msg.sender, today);
_payoutMining(cfg, sph, msg.sender, amount);
emit MiningClaimed(msg.sender, amount);
}
/// @notice 按瞬时价档拆分:即时 mint 给用户,锁仓 mint 给 SphLinearRelease 并 notify
function _payoutMining(IConfig cfg, address sph, address user, uint256 amount) internal {
uint256 lockBps;
address release = cfg.sphLinearRelease();
if (cfg.enableMiningLinearRelease() && release != address(0)) {
uint256 price = ISPHToken(sph).sphToUsdt(1 ether);
lockBps = cfg.miningLockBpsForPrice(price);
}
if (lockBps == 0) {
ISPHToken(sph).mint(user, amount);
return;
}
if (lockBps > BPS) lockBps = BPS;
uint256 locked = (amount * lockBps) / BPS;
uint256 freeAmt = amount - locked;
if (freeAmt > 0) {
ISPHToken(sph).mint(user, freeAmt);
}
if (locked > 0) {
ISPHToken(sph).mint(release, locked);
ISphLinearRelease(release).notifyDeposit(user, locked);
}
}
function _drainArchiveAccrued(
MachineStorage store,
address user
) internal returns (uint256 amount) {
uint256 n = store.userArchivedCount(user);
for (uint256 i; i < n; ) {
amount += store.claimAccrued(store.userArchivedMachines(user, i));
unchecked {
++i;
}
}
}
function _dailyCapAt(uint256 dayIndex) internal view returns (uint256) {
IConfig cfg = _cfg();
uint256 cap = cfg.machineDailyOutputCap();
uint256 every = cfg.machineReduceDays();
if (every == 0) return cap;
uint256 reductions = dayIndex / every;
uint256 keep = BPS - cfg.machineReduceRatio();
for (uint256 i; i < reductions; ) {
cap = (cap * keep) / BPS;
unchecked {
++i;
}
}
return cap;
}
function _claimHotBatch(
MachineStorage store,
IConfig cfg,
address user,
uint256 today,
uint256 lookback,
uint256 batch
) internal returns (uint256 amount) {
uint256 n = store.userMachineCount(user);
if (n == 0) return 0;
uint256 cursor = store.userClaimCursor(user) % n;
uint256 limit = batch < n ? batch : n;
for (uint256 step; step < limit; ) {
amount += _claimOneHot(store, cfg, user, today, lookback, cursor, step, n);
unchecked {
++step;
}
}
store.setUserClaimCursor(user, (cursor + limit) % n);
}
function _claimOneHot(
MachineStorage store,
IConfig cfg,
address user,
uint256 today,
uint256 lookback,
uint256 cursor,
uint256 step,
uint256 n
) internal returns (uint256) {
uint256 i = cursor + step;
if (i >= n) {
i -= n;
}
uint256 id = store.userMachines(user, i);
(, uint8 status, , , , ) = store.machines(id);
bool keep = status == store.STATUS_ACTIVE();
if (keep || store.machineLiveFromDay(id) != 0) {
_settleMachine(store, cfg, id, today, lookback, keep);
}
return store.claimAccrued(id);
}
/// @notice 清算合约批量铸造爆仓矿机(不受 softCap)
function createLiquidationMachines(
address user,
uint256 count
) external returns (uint256 created) {
IConfig cfg = _cfg();
if (msg.sender != cfg.liquidationContract()) revert NotAuth();
if (user == address(0) || count == 0) return 0;
MachineStorage store = machineStorage;
uint256 power = cfg.machineDefaultPower();
for (; created < count; ) {
store.createMachineWithType(user, power, MTYPE_LIQUIDATION);
unchecked {
++created;
}
}
}
/// @notice 项目方按台数赠送矿机(mType=2)。未激活、不占排队名额、不受 softCap;一次铸完
function giftMachines(address user, uint256 count) external onlyOwner returns (uint256 created) {
if (user == address(0)) revert ZeroAddress();
if (count == 0) return 0;
IConfig cfg = _cfg();
MachineStorage store = machineStorage;
uint256 power = cfg.machineDefaultPower();
for (; created < count; ) {
store.createMachineWithType(user, power, MTYPE_GIFT);
unchecked {
++created;
}
}
emit MachinesGifted(user, created);
}
function _countQueueMachines(
MachineStorage store,
address user
) internal view returns (uint256 n) {
uint256 total = store.userMachineCount(user);
for (uint256 i; i < total; ) {
(, uint8 status, uint8 mType, , , ) = store.machines(store.userMachines(user, i));
if (status != store.STATUS_DESTROYED() && mType == MTYPE_QUEUE) {
unchecked {
++n;
}
}
unchecked {
++i;
}
}
}
function _syncOneMachine(
MachineStorage store,
IConfig cfg,
address user,
uint256 i,
uint256 need,
uint256 filled
) internal returns (uint256) {
uint256 id = store.userMachines(user, i);
(, uint8 status, uint8 mType, , uint256 feeUntil, uint256 inactiveSince) = store
.machines(id);
if (status == store.STATUS_DESTROYED()) return filled;
// 爆仓矿机与赠送矿机:不占排队名额、不进入销毁宽限;只看管理费
if (mType != MTYPE_QUEUE) {
_syncLiquidationMachine(store, cfg, id, feeUntil);
return filled;
}
if (filled < need) {
unchecked {
++filled;
}
_syncQueueSlotMachine(store, cfg, id, feeUntil, inactiveSince);
} else if (status != store.STATUS_INACTIVE() || inactiveSince == 0) {
_applyStatus(store, cfg, id, store.STATUS_INACTIVE(), block.timestamp);
}
return filled;
}
function _syncLiquidationMachine(
MachineStorage store,
IConfig cfg,
uint256 id,
uint256 feeUntil
) internal {
if (feeUntil > block.timestamp) {
_applyStatus(store, cfg, id, store.STATUS_ACTIVE(), 0);
} else {
_applyStatus(store, cfg, id, store.STATUS_INACTIVE(), 0);
}
}
function _syncQueueSlotMachine(
MachineStorage store,
IConfig cfg,
uint256 id,
uint256 feeUntil,
uint256 inactiveSince
) internal {
if (feeUntil > block.timestamp) {
_applyStatus(store, cfg, id, store.STATUS_ACTIVE(), 0);
return;
}
uint256 since = 0;
if (feeUntil != 0) {
since = inactiveSince == 0 ? feeUntil : inactiveSince;
}
_applyStatus(store, cfg, id, store.STATUS_INACTIVE(), since);
}
function _applyStatus(
MachineStorage store,
IConfig cfg,
uint256 id,
uint8 newStatus,
uint256 inactiveSince
) internal {
(, uint8 oldStatus, , , , ) = store.machines(id);
if (oldStatus == newStatus) {
if (newStatus != store.STATUS_ACTIVE()) {
store.setStatus(id, newStatus, inactiveSince);
}
return;
}
uint256 today = cfg.getDayIndex(block.timestamp);
if (oldStatus == store.STATUS_ACTIVE() && newStatus != store.STATUS_ACTIVE()) {
_settleMachine(store, cfg, id, today, 0, false);
store.setMachineLiveFromDay(id, 0);
} else if (
newStatus == store.STATUS_DESTROYED() && store.machineLiveFromDay(id) != 0
) {
_settleMachine(store, cfg, id, today, 0, false);
store.setMachineLiveFromDay(id, 0);
}
store.setStatus(id, newStatus, inactiveSince);
if (oldStatus == store.STATUS_ACTIVE() || newStatus == store.STATUS_ACTIVE()) {
_noteGlobalPower(store, cfg);
}
// 普通机与爆仓机均计入管理费档位用的全网有效台数(ACTIVE = 撑机+费覆盖)
{
if (oldStatus != store.STATUS_ACTIVE() && newStatus == store.STATUS_ACTIVE()) {
cfg.bumpMachineAliveCount(1);
} else if (oldStatus == store.STATUS_ACTIVE() && newStatus != store.STATUS_ACTIVE()) {
cfg.bumpMachineAliveCount(-1);
}
}
if (oldStatus != store.STATUS_ACTIVE() && newStatus == store.STATUS_ACTIVE()) {
store.setMachineLiveFromDay(id, today + 1);
}
if (newStatus == store.STATUS_DESTROYED()) {
store.moveToArchive(id);
}
}
/// @param maxDays 0=不限制回溯;keepLive 时按实际结算窗口推进 liveFrom
function _settleMachine(
MachineStorage store,
IConfig cfg,
uint256 id,
uint256 today,
uint256 maxDays,
bool keepLive
) internal {
uint256 liveRaw = store.machineLiveFromDay(id);
if (liveRaw == 0) {
if (keepLive && _machineStillEarnable(store, id)) {
store.setMachineLiveFromDay(id, today + 1);
}
return;
}
uint256 from = liveRaw - 1;
uint256 end = _earnEndDay(store, cfg, id, today);
if (from >= end) {
if (keepLive && _machineStillEarnable(store, id)) {
store.setMachineLiveFromDay(id, today + 1);
} else if (!keepLive) {
store.setMachineLiveFromDay(id, 0);
}
return;
}
uint256 winEnd = end;
if (maxDays != 0) {
uint256 capped = from + maxDays;
if (capped < winEnd) winEnd = capped;
}
uint256 amount = _pendingRange(store, cfg, id, from, winEnd);
if (amount > 0) {
store.addAccruedOutput(id, amount);
}
if (!keepLive) return;
if (_machineStillEarnable(store, id)) {
store.setMachineLiveFromDay(id, winEnd + 1);
} else {
store.setMachineLiveFromDay(id, 0);
}
}
function _machineStillEarnable(
MachineStorage store,
uint256 id
) internal view returns (bool) {
(, uint8 status, , , uint256 feeUntil, ) = store.machines(id);
return status == store.STATUS_ACTIVE() && feeUntil > block.timestamp;
}
function _earnEndDay(
MachineStorage store,
IConfig cfg,
uint256 id,
uint256 today
) internal view returns (uint256 end) {
end = today;
(, , , , uint256 feeUntil, ) = store.machines(id);
if (feeUntil <= block.timestamp) {
uint256 feeDay = cfg.getDayIndex(feeUntil);
if (feeDay < end) end = feeDay;
}
}
function _pendingRange(
MachineStorage store,
IConfig cfg,
uint256 id,
uint256 from,
uint256 end
) internal view returns (uint256 amount) {
(, , , uint256 power, , ) = store.machines(id);
if (power == 0) return 0;
for (uint256 d = from; d < end; ) {
uint256 tot = _totalPowerOnDay(store, cfg, d);
if (tot > 0) {
uint256 cap = _dailyCapAt(d);
uint256 networkOut = tot < cap ? tot : cap;
amount += (networkOut * power) / tot;
}
unchecked {
++d;
}
}
}
function _noteGlobalPower(MachineStorage store, IConfig cfg) internal {
uint256 day = cfg.getDayIndex(block.timestamp);
uint256 cur = store.totalActivePower();
store.setPowerSnap(day, cur);
store.bumpPeakActivePower(cur);
}
function _totalPowerOnDay(
MachineStorage store,
IConfig cfg,
uint256 day
) internal view returns (uint256) {
uint256 today = cfg.getDayIndex(block.timestamp);
if (day > today) return 0;
uint256 observed;
if (day == today) {
observed = store.totalActivePower();
} else if (!store.powerSnapInit()) {
return 0;
} else {
observed = store.powerSnapValue();
}
return _applyPowerFloor(store, cfg, observed);
}
/// @notice 结算分母:max(观测, peak × floorBps / 10000);floorBps=0 或 peak=0 时用观测值
function _applyPowerFloor(
MachineStorage store,
IConfig cfg,
uint256 observed
) internal view returns (uint256) {
uint256 bps = cfg.machinePowerFloorBps();
uint256 peak = store.peakActivePower();
if (bps == 0 || peak == 0) return observed;
uint256 floor_ = (peak * bps) / BPS;
return observed < floor_ ? floor_ : observed;
}
function _ensureFeePrice(IConfig cfg) internal returns (uint256 price) {
MachineStorage store = machineStorage;
uint256 feeDays = cfg.machineFeeDays();
uint256 periodId = cfg.getDayIndex(block.timestamp) / feeDays;
if (store.feePeriodId() == periodId && store.feePricePerMachine() != 0) {
return store.feePricePerMachine();
}
price = cfg.machineFeePriceByAlive(cfg.machineAliveCount());
store.setFeePeriod(periodId, price);
}
function _destroyExpired(
MachineStorage store,
IConfig cfg,
address user,
uint256 grace
) internal {
uint256 i;
while (i < store.userMachineCount(user)) {
uint256 id = store.userMachines(user, i);
(, uint8 status, uint8 mType, , , uint256 inactiveSince) = store.machines(id);
if (
mType == MTYPE_QUEUE &&
status != store.STATUS_DESTROYED() &&
inactiveSince != 0 &&
block.timestamp >= inactiveSince + grace
) {
_applyStatus(store, cfg, id, store.STATUS_DESTROYED(), inactiveSince);
// 归档后热列表缩短,不递增 i
} else {
unchecked {
++i;
}
}
}
}
function _cfg() internal view returns (IConfig) {
address c = config;
if (c == address(0)) revert ConfigNotSet();
return IConfig(c);
}
}Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.