Contract Name:
TetherDeathPredictionMarket
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 v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../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.
*
* 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);
}
} <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 v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 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);
} <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 v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
} <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 v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
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
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// 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
pragma solidity ^0.8.20;
// Import OpenZeppelin's Ownable contract
import "@openzeppelin/contracts/access/Ownable.sol";
// Import IERC20 interface
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
// Uniswap V3 Pool interface
interface IUniswapV3Pool {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function token0() external view returns (address);
function token1() external view returns (address);
}
// Uniswap V2 Pair interface
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function token0() external view returns (address);
function token1() external view returns (address);
}
contract TetherDeathPredictionMarket is Ownable, ReentrancyGuard {
IUniswapV3Pool public uniswapV3Pool = IUniswapV3Pool(0x3416cF6C708Da44DB2624D63ea0AAef7113527C6);
IUniswapV2Pair public uniswapV2Pair = IUniswapV2Pair(0x3041CbD36888bECc7bbCBc0045E3B1f144466f5f);
constructor() Ownable(msg.sender) {}
uint256 public constant BASE_COST = 0.005 ether; // 10 USDC with 6 decimals
uint256 public constant FIRST_THRESHOLD = 1000; // At 1,000 bets
uint256 public constant SECOND_THRESHOLD = 10000; // At 10,000 bets
uint256 public constant FEE_PERCENT = 20; // 20%
uint256 public constant TOTAL_QUARTERS = 8; // Q4 2024 to Q3 2027
uint256 public constant TETHER_IS_LEGIT = 0; // Special ID for "Tether is Legit"
uint256 public constant Q4_2024_START = 1727740800; // October 1, 2024
uint256 public constant QUARTER_DURATION = 91 days;
address public constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public constant USDC_TOKEN_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
uint256 public tetherDeathTimestamp;
uint256 public winningQuarter;
bool public tetherIsDead;
// Mapping from quarter ID to total bets
mapping(uint256 => uint256) public totalBetsPerQuarter;
mapping(uint256 => uint256) public totalBetsPerQuarterValue;
// Mapping from quarter ID to user address to number of bets
mapping(uint256 => mapping(address => uint256)) public betsPerQuarterPerUser;
// Mapping to check if a user has withdrawn their winnings
mapping(address => bool) public hasWithdrawn;
event BetPlaced(address indexed user, uint256 quarter, uint256 numBets);
event TetherDeclaredDead(uint256 timestamp, uint256 quarter);
event TetherDeclaredLegit(uint256 timestamp);
event WinningsWithdrawn(address indexed user, uint256 amount);
receive() external payable {}
// Function to place bets on quarters with bonding curve pricing
function betOnQuarters(uint256[] calldata quarterIds, uint256[] calldata numBetsArray) external payable nonReentrant {
require(!tetherIsDead, "Betting is closed, Tether has died");
require(quarterIds.length > 0 && quarterIds.length <= TOTAL_QUARTERS, "Invalid number of quarters");
require(quarterIds.length == numBetsArray.length, "quarterIds and numBets length mismatch");
uint256 totalCost = 0;
for (uint256 i = 0; i < quarterIds.length; i++) {
uint256 quarterId = quarterIds[i];
uint256 numBets = numBetsArray[i];
require(quarterId <= TOTAL_QUARTERS || quarterId == TETHER_IS_LEGIT, "Invalid quarter ID");
require(numBets > 0, "Number of bets must be greater than zero");
// Calculate cost for this quarter and number of bets
uint256 betCost = getTotalBetCost(quarterId, numBets);
totalCost += betCost;
// Update bets per user
betsPerQuarterPerUser[quarterId][msg.sender] += numBets;
// Update total bets per quarter
totalBetsPerQuarter[quarterId] += numBets;
// Update total bets value per quarter (excluding fee)
uint256 netBetAmount = (betCost * (100 - FEE_PERCENT)) / 100;
totalBetsPerQuarterValue[quarterId] += netBetAmount;
emit BetPlaced(msg.sender, quarterId, numBets);
}
// Ensure the user sent the correct amount of ETH
require(msg.value >= totalCost, "Incorrect ETH amount sent");
// Calculate fee
uint256 totalFee = (totalCost * FEE_PERCENT) / 100;
// Transfer fee to owner
(bool success, ) = payable(owner()).call{value: totalFee}("");
require(success, "Fee transfer to owner failed");
// The remaining ETH stays in the contract automatically
}
// Function to calculate the total cost for a number of bets on a quarter
function getTotalBetCost(uint256 quarterId, uint256 numBets) public view returns (uint256) {
uint256 totalCost = 0;
uint256 n = totalBetsPerQuarter[quarterId]; // Existing bets on the quarter
for (uint256 i = 1; i <= numBets; i++) {
uint256 costPerBet = getCostPerBet(n + i);
totalCost += costPerBet;
}
return totalCost;
}
// Function to get the cost per bet based on the number of existing bets
function getCostPerBet(uint256 n) public pure returns (uint256) {
if (n <= FIRST_THRESHOLD) {
// Linear increase from 0.01 ETH to 1 ETH over the first 1,000 bets
uint256 costPerBet = BASE_COST + ((n - 1) * (1 ether - BASE_COST)) / (FIRST_THRESHOLD - 1);
return costPerBet;
} else if (n <= SECOND_THRESHOLD) {
// Linear increase from 1 ETH to 1000 ETH over the next 9,000 bets
uint256 costPerBet = 1 ether + ((n - FIRST_THRESHOLD) * (1000 ether - 1 ether)) / (SECOND_THRESHOLD - FIRST_THRESHOLD);
return costPerBet;
} else {
// Exponential increase, doubling each bet after 10,000 bets
uint256 exponent = n - SECOND_THRESHOLD;
uint256 costPerBet = 1000 ether * (2 ** exponent);
return costPerBet;
}
}
// Function to check the price for a number of bets on a quarter
function checkBetPrice(uint256 quarterId, uint256 numBets) external view returns (uint256 totalCost, uint256[] memory costPerBetArray) {
uint256 n = totalBetsPerQuarter[quarterId]; // Existing bets on the quarter
totalCost = 0;
costPerBetArray = new uint256[](numBets);
for (uint256 i = 1; i <= numBets; i++) {
uint256 costPerBet = getCostPerBet(n + i);
costPerBetArray[i - 1] = costPerBet;
totalCost += costPerBet;
}
return (totalCost, costPerBetArray);
}
// Function to declare Tether dead
function declareTetherDead() onlyOwner public {
require(!tetherIsDead, "Tether is already declared dead");
require(block.timestamp <= getQuarterEndTimestamp(TOTAL_QUARTERS), "Cannot declare Tether dead after betting period");
uint256 priceV3 = getUSDTPriceInUSDC_V3();
uint256 priceV2 = getUSDTPriceInUSDC_V2();
require(priceV3 <= 100000 && priceV2 <= 100000, "Tether is not dead yet"); // 0.1 USDC per USDT
tetherIsDead = true;
tetherDeathTimestamp = block.timestamp;
winningQuarter = getQuarterId(tetherDeathTimestamp);
emit TetherDeclaredDead(tetherDeathTimestamp, winningQuarter);
}
// Function to declare Tether legit after betting period ends
function declareTetherLegit() onlyOwner public {
require(!tetherIsDead, "Tether is already declared dead");
require(block.timestamp > getQuarterEndTimestamp(TOTAL_QUARTERS), "Betting period is not over yet");
tetherIsDead = true;
tetherDeathTimestamp = block.timestamp;
winningQuarter = TETHER_IS_LEGIT;
emit TetherDeclaredLegit(tetherDeathTimestamp);
}
// Function to withdraw winnings
function withdrawWinnings() external nonReentrant {
require(tetherIsDead, "Tether is not dead yet");
require(!hasWithdrawn[msg.sender], "Winnings already withdrawn");
uint256 userBets = betsPerQuarterPerUser[winningQuarter][msg.sender];
require(userBets > 0, "You did not bet on the winning quarter");
uint256 totalBets = totalBetsPerQuarter[winningQuarter];
uint256 contractBalance = address(this).balance;
uint256 winnings = (contractBalance * userBets) / totalBets;
// Mark as withdrawn
hasWithdrawn[msg.sender] = true;
(bool success, ) = msg.sender.call{value: winnings}("");
require(success, "ETH transfer failed");
emit WinningsWithdrawn(msg.sender, winnings);
}
// Function to get the USDT price in USDC from Uniswap V3
function getUSDTPriceInUSDC_V3() public view returns (uint256 price) {
(uint160 sqrtPriceX96, , , , , , ) = uniswapV3Pool.slot0();
address token0 = uniswapV3Pool.token0();
address token1 = uniswapV3Pool.token1();
address usdcAddress = USDC_TOKEN_ADDRESS;
address usdtAddress = USDT_TOKEN_ADDRESS;
uint256 decimalFactor = 1e6; // USDC and USDT have 6 decimals
if (token0 == usdcAddress && token1 == usdtAddress) {
// Price of USDT in USDC
uint256 numerator = uint256(sqrtPriceX96) * uint256(sqrtPriceX96) * decimalFactor;
uint256 denominator = 1 << 192;
price = numerator / denominator;
} else if (token0 == usdtAddress && token1 == usdcAddress) {
// Price of USDT in USDC
uint256 numerator = uint256(1 << 192) * decimalFactor;
uint256 denominator = uint256(sqrtPriceX96) * uint256(sqrtPriceX96);
price = numerator / denominator;
} else {
revert("Invalid V3 pool tokens");
}
}
// Function to get the USDT price in USDC from Uniswap V2
function getUSDTPriceInUSDC_V2() public view returns (uint256 price) {
(uint112 reserve0, uint112 reserve1, ) = uniswapV2Pair.getReserves();
address token0 = uniswapV2Pair.token0();
address token1 = uniswapV2Pair.token1();
address usdcAddress = USDC_TOKEN_ADDRESS;
address usdtAddress = USDT_TOKEN_ADDRESS;
uint256 decimalFactor = 1e6; // USDC and USDT have 6 decimals
if (token0 == usdcAddress && token1 == usdtAddress) {
// Price of USDT in USDC: reserveUSDC / reserveUSDT
price = (uint256(reserve0) * decimalFactor) / uint256(reserve1);
} else if (token0 == usdtAddress && token1 == usdcAddress) {
// Price of USDT in USDC: reserveUSDC / reserveUSDT
price = (uint256(reserve1) * decimalFactor) / uint256(reserve0);
} else {
revert("Invalid V2 pool tokens");
}
}
// Function to get the quarter ID based on a timestamp
function getQuarterId(uint256 timestamp) public pure returns (uint256) {
if (timestamp < Q4_2024_START) {
revert("Timestamp is before betting period starts");
}
uint256 timeSinceStart = timestamp - Q4_2024_START;
uint256 quarterId = (timeSinceStart / QUARTER_DURATION) + 1;
if (quarterId > TOTAL_QUARTERS) {
// After the last quarter, it's "Tether is Legit"
return TETHER_IS_LEGIT;
}
return quarterId;
}
// Function to get the end timestamp of a quarter
function getQuarterEndTimestamp(uint256 quarterId) public pure returns (uint256) {
require(quarterId >= 1 && quarterId <= TOTAL_QUARTERS, "Invalid quarter ID");
return Q4_2024_START + (quarterId * QUARTER_DURATION) - 1;
}
// Function to change the owner address
function changeOwner(address newOwner) external onlyOwner {
transferOwnership(newOwner);
}
// Function to get the total net USDC bet on a specific quarter (excluding fees)
function getTotalETHBetOnQuarter(uint256 quarterId) public view returns (uint256) {
return totalBetsPerQuarterValue[quarterId];
}
// Function to get the number of bets a user has on a specific quarter
function getUserBetsOnQuarter(address user, uint256 quarterId) external view returns (uint256) {
return betsPerQuarterPerUser[quarterId][user];
}
function getQuarterInfo(uint256 quarterId, address user) external view returns (uint256, uint256, uint256) {
return (totalBetsPerQuarter[quarterId], totalBetsPerQuarterValue[quarterId], betsPerQuarterPerUser[quarterId][user]);
}
function getContractBalance() external view returns (uint256) {
return address(this).balance;
}
function getTetherTrustScore() external view returns (uint256) {
uint256 allETH = address(this).balance;
uint256 USDTTrust = getTotalETHBetOnQuarter(0);
uint256 USDCTrustScore = (USDTTrust * 10000) / allETH;
return USDCTrustScore;
}
function getTetherPrice() external view returns (uint256) {
uint256 priceV3 = getUSDTPriceInUSDC_V3();
uint256 priceV2 = getUSDTPriceInUSDC_V2();
return (priceV3 + priceV2) / 2;
}
}