Contract Name:
DiamondStakingMigrated
Contract Source Code:
<i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.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.
*
* By default, the owner account will be the one that deploys the contract. 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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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[EIP 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);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
interface IPrivixNFTPass {
function getTier(uint256 tokenId) external view returns (string memory);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address owner) external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
contract DiamondStakingMigrated is Ownable, ReentrancyGuard {
using SafeMath for uint256;
/* ─────────────────── Constants ─────────────────── */
uint256 public constant STAKING_AMOUNT = 5000 * 10**9; // 5000 PRIVIX (9 decimals)
uint256 public constant LOCKUP_PERIOD = 30 days; // 30 days lockup
uint256 public constant REWARD_PERIOD = 30 days; // 30 days reward period
uint256 public constant DIAMOND_START = 501; // Diamond NFT range start
uint256 public constant DIAMOND_END = 1000; // Diamond NFT range end
/* ─────────────────── Contract References ─────────────────── */
IERC20 public immutable privixToken;
IERC20 public immutable usdtToken;
IPrivixNFTPass public immutable nftContract;
/* ─────────────────── Staking Data ─────────────────── */
struct StakeInfo {
uint256 amount; // Amount of PRIVIX staked
uint256 stakeTime; // Timestamp when staked
uint256 lastClaimTime; // Last time rewards were claimed
uint256 diamondTokenId; // Diamond NFT token ID used for staking
bool isActive; // Whether stake is active
uint256 totalClaimed; // Total USDT claimed by this user
bool isMigrated; // Whether this stake was migrated from old contract
uint256 originalStakeTime; // Original stake time from old contract (for migrated stakes)
}
mapping(address => StakeInfo) public stakes;
mapping(uint256 => bool) public nftUsedForStaking; // Track which NFTs are being used for staking
/* ─────────────────── Staker Tracking ─────────────────── */
address[] public activeStakers; // Array of all active staker addresses
mapping(address => uint256) public stakerIndex; // Maps staker address to their index in activeStakers array
/* ─────────────────── Pool Stats ─────────────────── */
uint256 public totalStaked;
uint256 public totalStakers;
uint256 public totalRewardsPaid;
uint256 public totalMigratedStakers; // Track migrated stakers
uint256 public totalMigratedAmount; // Track migrated amounts
/* ─────────────────── Migration Support ─────────────────── */
bool public migrationMode = true; // Allow migration initially
address public migrationOperator; // Address authorized to perform migrations
uint256 public migrationDeadline; // After this, migration is locked forever
/* ─────────────────── Events ─────────────────── */
event Staked(address indexed user, uint256 amount, uint256 diamondTokenId, uint256 timestamp);
event Unstaked(address indexed user, uint256 amount, uint256 timestamp);
event RewardsClaimed(address indexed user, uint256 amount, uint256 timestamp);
event StakeMigrated(address indexed user, uint256 amount, uint256 diamondTokenId, uint256 originalStakeTime);
event MigrationCompleted(uint256 totalMigrated, uint256 totalAmount);
event MigrationModeDisabled();
/* ─────────────────── Constructor ─────────────────── */
constructor(
address _privixToken,
address _usdtToken,
address _nftContract,
address _migrationOperator
) {
require(_privixToken != address(0), "Invalid PRIVIX token address");
require(_usdtToken != address(0), "Invalid USDT token address");
require(_nftContract != address(0), "Invalid NFT contract address");
require(_migrationOperator != address(0), "Invalid migration operator address");
privixToken = IERC20(_privixToken);
usdtToken = IERC20(_usdtToken);
nftContract = IPrivixNFTPass(_nftContract);
migrationOperator = _migrationOperator;
// Set migration deadline to 30 days from deployment
migrationDeadline = block.timestamp + 30 days;
}
/* ─────────────────── Migration Functions ─────────────────── */
/// Migrate a staker from the old contract
function migrateStaker(
address staker,
uint256 amount,
uint256 originalStakeTime,
uint256 lastClaimTime,
uint256 diamondTokenId,
uint256 totalClaimed
) external {
require(migrationMode, "Migration mode disabled");
require(msg.sender == migrationOperator || msg.sender == owner(), "Not authorized for migration");
require(block.timestamp <= migrationDeadline, "Migration deadline passed");
require(!stakes[staker].isActive, "Staker already active");
require(amount == STAKING_AMOUNT, "Invalid stake amount");
require(diamondTokenId >= DIAMOND_START && diamondTokenId <= DIAMOND_END, "Invalid diamond token ID");
// Verify NFT ownership (current owner should still own the NFT)
require(nftContract.ownerOf(diamondTokenId) == staker, "Staker no longer owns NFT");
// Verify NFT tier
string memory tier = nftContract.getTier(diamondTokenId);
require(keccak256(bytes(tier)) == keccak256(bytes("Diamond")), "NFT is not Diamond tier");
require(!nftUsedForStaking[diamondTokenId], "NFT already used for staking");
// Create migrated stake record
stakes[staker] = StakeInfo({
amount: amount,
stakeTime: block.timestamp, // Current time for lockup calculations
lastClaimTime: lastClaimTime, // Preserve last claim time
diamondTokenId: diamondTokenId,
isActive: true,
totalClaimed: totalClaimed, // Preserve total claimed
isMigrated: true, // Mark as migrated
originalStakeTime: originalStakeTime // Preserve original stake time
});
// Mark NFT as used for staking
nftUsedForStaking[diamondTokenId] = true;
// Add to active stakers tracking
_addStaker(staker);
// Update pool stats
totalStaked = totalStaked.add(amount);
totalStakers = totalStakers.add(1);
totalMigratedStakers = totalMigratedStakers.add(1);
totalMigratedAmount = totalMigratedAmount.add(amount);
emit StakeMigrated(staker, amount, diamondTokenId, originalStakeTime);
}
/// Migrate multiple stakers in batch
function batchMigrateStakers(
address[] calldata stakers,
uint256[] calldata amounts,
uint256[] calldata originalStakeTimes,
uint256[] calldata lastClaimTimes,
uint256[] calldata diamondTokenIds,
uint256[] calldata totalClaimeds
) external {
require(migrationMode, "Migration mode disabled");
require(msg.sender == migrationOperator || msg.sender == owner(), "Not authorized for migration");
require(block.timestamp <= migrationDeadline, "Migration deadline passed");
uint256 length = stakers.length;
require(length == amounts.length, "Arrays length mismatch");
require(length == originalStakeTimes.length, "Arrays length mismatch");
require(length == lastClaimTimes.length, "Arrays length mismatch");
require(length == diamondTokenIds.length, "Arrays length mismatch");
require(length == totalClaimeds.length, "Arrays length mismatch");
for (uint256 i = 0; i < length; i++) {
// Call individual migration function for each staker
this.migrateStaker(
stakers[i],
amounts[i],
originalStakeTimes[i],
lastClaimTimes[i],
diamondTokenIds[i],
totalClaimeds[i]
);
}
}
/// Complete migration and disable migration mode
function completeMigration() external onlyOwner {
require(migrationMode, "Migration already completed");
migrationMode = false;
emit MigrationCompleted(totalMigratedStakers, totalMigratedAmount);
emit MigrationModeDisabled();
}
/* ─────────────────── Staking Functions ─────────────────── */
/// Stake PRIVIX tokens with diamond NFT verification (for new stakers post-migration)
function stake(uint256 diamondTokenId) external nonReentrant {
require(!migrationMode, "Contract in migration mode - new staking disabled");
require(!stakes[msg.sender].isActive, "Already staking");
require(diamondTokenId >= DIAMOND_START && diamondTokenId <= DIAMOND_END, "Invalid diamond token ID");
require(nftContract.ownerOf(diamondTokenId) == msg.sender, "Not owner of this NFT");
require(!nftUsedForStaking[diamondTokenId], "NFT already used for staking");
// Verify NFT tier
string memory tier = nftContract.getTier(diamondTokenId);
require(keccak256(bytes(tier)) == keccak256(bytes("Diamond")), "NFT is not Diamond tier");
// Transfer PRIVIX tokens
require(
privixToken.transferFrom(msg.sender, address(this), STAKING_AMOUNT),
"PRIVIX transfer failed"
);
// Record stake
stakes[msg.sender] = StakeInfo({
amount: STAKING_AMOUNT,
stakeTime: block.timestamp,
lastClaimTime: block.timestamp,
diamondTokenId: diamondTokenId,
isActive: true,
totalClaimed: 0,
isMigrated: false,
originalStakeTime: block.timestamp
});
// Mark NFT as used for staking
nftUsedForStaking[diamondTokenId] = true;
// Add to active stakers tracking
_addStaker(msg.sender);
// Update pool stats
totalStaked = totalStaked.add(STAKING_AMOUNT);
totalStakers = totalStakers.add(1);
emit Staked(msg.sender, STAKING_AMOUNT, diamondTokenId, block.timestamp);
}
/// Claim rewards
function claimRewards() external nonReentrant {
require(!migrationMode, "Contract in migration mode");
require(stakes[msg.sender].isActive, "No active stake");
uint256 pendingRewards = getPendingRewards(msg.sender);
require(pendingRewards > 0, "No rewards to claim");
// Check if enough time has passed since last claim
require(
block.timestamp >= stakes[msg.sender].lastClaimTime.add(REWARD_PERIOD),
"Reward period not elapsed"
);
// Update last claim time
stakes[msg.sender].lastClaimTime = block.timestamp;
stakes[msg.sender].totalClaimed = stakes[msg.sender].totalClaimed.add(pendingRewards);
// Update total rewards paid
totalRewardsPaid = totalRewardsPaid.add(pendingRewards);
// Transfer USDT rewards
require(usdtToken.transfer(msg.sender, pendingRewards), "USDT transfer failed");
emit RewardsClaimed(msg.sender, pendingRewards, block.timestamp);
}
/// Unstake PRIVIX tokens
function unstake() external nonReentrant {
require(!migrationMode, "Contract in migration mode");
require(stakes[msg.sender].isActive, "No active stake");
require(canUnstake(msg.sender), "Cannot unstake yet");
StakeInfo memory stakeInfo = stakes[msg.sender];
// Clear stake data
stakes[msg.sender].isActive = false;
nftUsedForStaking[stakeInfo.diamondTokenId] = false;
// Remove from active stakers
_removeStaker(msg.sender);
// Update pool stats
totalStaked = totalStaked.sub(stakeInfo.amount);
totalStakers = totalStakers.sub(1);
// Transfer PRIVIX tokens back
require(privixToken.transfer(msg.sender, stakeInfo.amount), "PRIVIX transfer failed");
emit Unstaked(msg.sender, stakeInfo.amount, block.timestamp);
}
/* ─────────────────── View Functions ─────────────────── */
/// Get pending rewards for a staker
function getPendingRewards(address staker) public view returns (uint256) {
if (!stakes[staker].isActive) return 0;
uint256 contractUsdtBalance = usdtToken.balanceOf(address(this));
if (contractUsdtBalance == 0 || totalStakers == 0) return 0;
// Simple equal distribution among all stakers
return contractUsdtBalance.div(totalStakers);
}
/// Check if a staker can unstake (30 days lockup from stake time)
function canUnstake(address staker) public view returns (bool) {
if (!stakes[staker].isActive) return false;
return block.timestamp >= stakes[staker].stakeTime.add(LOCKUP_PERIOD);
}
/// Check if staker still owns their NFT
function stakerStillOwnsNFT(address staker) public view returns (bool) {
if (!stakes[staker].isActive) return false;
try nftContract.ownerOf(stakes[staker].diamondTokenId) returns (address owner) {
return owner == staker;
} catch {
return false;
}
}
/// Get comprehensive staker info
function getStakeInfo(address staker) external view returns (
uint256 amount,
uint256 stakeTime,
uint256 lastClaimTime,
uint256 diamondTokenId,
bool isActive,
bool canUnstakeNow,
bool isMigrated,
uint256 originalStakeTime
) {
StakeInfo memory stakeInfo = stakes[staker];
return (
stakeInfo.amount,
stakeInfo.stakeTime,
stakeInfo.lastClaimTime,
stakeInfo.diamondTokenId,
stakeInfo.isActive,
canUnstake(staker),
stakeInfo.isMigrated,
stakeInfo.originalStakeTime
);
}
/// Get pool statistics
function getPoolStats() external view returns (
uint256 _totalStaked,
uint256 _totalStakers,
uint256 _totalRewardsPaid,
uint256 _contractUsdtBalance,
uint256 _contractPrivixBalance,
uint256 _totalMigratedStakers,
uint256 _totalMigratedAmount
) {
return (
totalStaked,
totalStakers,
totalRewardsPaid,
usdtToken.balanceOf(address(this)),
privixToken.balanceOf(address(this)),
totalMigratedStakers,
totalMigratedAmount
);
}
/// Get all active stakers
function getAllStakers() external view returns (address[] memory) {
return activeStakers;
}
/// Get all stakers with details (for compatibility with existing scripts)
function getAllStakersWithDetails() external view returns (
address[] memory stakers,
uint256[] memory amounts,
uint256[] memory stakeTimes,
uint256[] memory diamondTokenIds,
bool[] memory canUnstakeFlags
) {
uint256 count = activeStakers.length;
stakers = new address[](count);
amounts = new uint256[](count);
stakeTimes = new uint256[](count);
diamondTokenIds = new uint256[](count);
canUnstakeFlags = new bool[](count);
for (uint256 i = 0; i < count; i++) {
address staker = activeStakers[i];
StakeInfo memory stakeInfo = stakes[staker];
stakers[i] = staker;
amounts[i] = stakeInfo.amount;
stakeTimes[i] = stakeInfo.originalStakeTime; // Use original stake time for migrated stakers
diamondTokenIds[i] = stakeInfo.diamondTokenId;
canUnstakeFlags[i] = canUnstake(staker);
}
return (stakers, amounts, stakeTimes, diamondTokenIds, canUnstakeFlags);
}
/* ─────────────────── Helper Functions ─────────────────── */
/// Add staker to active stakers array
function _addStaker(address staker) internal {
activeStakers.push(staker);
stakerIndex[staker] = activeStakers.length - 1;
}
/// Remove staker from active stakers array
function _removeStaker(address staker) internal {
uint256 index = stakerIndex[staker];
uint256 lastIndex = activeStakers.length - 1;
if (index != lastIndex) {
address lastStaker = activeStakers[lastIndex];
activeStakers[index] = lastStaker;
stakerIndex[lastStaker] = index;
}
activeStakers.pop();
delete stakerIndex[staker];
}
/* ─────────────────── Owner Functions ─────────────────── */
/// Emergency withdraw USDT (owner only)
function emergencyWithdrawUSDT(uint256 amount) external onlyOwner {
require(amount <= usdtToken.balanceOf(address(this)), "Insufficient USDT balance");
require(usdtToken.transfer(owner(), amount), "USDT transfer failed");
}
/// Emergency withdraw PRIVIX (owner only)
function emergencyWithdrawPrivix(uint256 amount) external onlyOwner {
require(amount <= privixToken.balanceOf(address(this)), "Insufficient PRIVIX balance");
require(privixToken.transfer(owner(), amount), "PRIVIX transfer failed");
}
/// Set migration operator
function setMigrationOperator(address newOperator) external onlyOwner {
require(newOperator != address(0), "Invalid operator address");
migrationOperator = newOperator;
}
/// Extend migration deadline (can only extend, not reduce)
function extendMigrationDeadline(uint256 newDeadline) external onlyOwner {
require(migrationMode, "Migration already completed");
require(newDeadline > migrationDeadline, "Can only extend deadline");
migrationDeadline = newDeadline;
}
}