// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
uint16 constant squaresCount = 100;
uint16 constant colorsCount = 6; // 0 is reserved as empty color
interface ICanvas {
function setSquareColor(uint16 squareIndex, uint24 color) external;
function resetCanvas() external;
function getColors() external view returns (uint24[squaresCount] memory);
function getSquareColor(uint16 squareIndex) external view returns (uint24);
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../canvas/ICanvas.sol";
struct ColorData {
uint16 rank;
uint16 count;
}
interface ISession {
function startSession() external;
function hasStarted() external view returns (bool);
function sessionEndTime() external view returns (uint256);
function getAvailableColors() external view returns (uint24[] memory);
function getRewardShare(address painter) external view returns (uint256);
function getPainters() external view returns (address[squaresCount] memory);
function getCosts() external view returns (uint256[squaresCount] memory);
function getPainter(uint16 squareIndex) external view returns (address);
function getCost(uint16 squareIndex) external view returns (uint256);
function getColorsData() external view returns (ColorData[colorsCount] memory);
function getColorCount(uint24) external view returns (uint16);
function getSessionRewards() external view returns (uint256);
function getCrownRewards() external view returns (uint256);
function paintSquares(
uint16[] calldata squareIndex,
uint24 newColor
) external;
function calculatePaintingRewards() external;
function isSessionEnd() external view returns (bool);
function isWriteEnabled() external view returns (bool);
}
// 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);
}
}
// 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;
}
}
// Dogcasso facilitates team-based, onchain art battles with $DOG. May the best dog win :)
// Twitter: https://x.com/dogcasso
// Telegram: https://t.me/dogcasso
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../canvas/ICanvas.sol";
import "./ISession.sol";
abstract contract SessionInternal is ISession, Ownable, ReentrancyGuard {
/// @dev The canvas for the painting session.
ICanvas immutable _canvas;
/// @dev The address of the next session.
ISession public nextSession;
/// @dev The address of the token.
IERC20 public token;
/// @dev The premium added on top of the price to paint over a square.
uint256 public constant OVERWRITE_PERCENT = 10;
/// @dev The decimals of the token.
uint256 constant TOKEN_DECIMALS = 9;
/// @dev The price to paint an empty square.
uint256 public constant START_PAINT_PRICE = 1 * (10 ** TOKEN_DECIMALS);
/// @dev The initial duration of a session (initially 6hrs)
uint256 public initialDuration = 6 * 60 * 60;
/// @dev Once the timer dips below the blitz threshold, it can never go higher than it
uint256 public blitzThreshold = 20 * 60;
/// @dev The number of seconds added to the session duration before blitz threshold is reached
uint256 public paintAddSecondsBeforeBlitz = 10;
/// @dev The number of seconds added to the session duration after blitz threshold is reached
uint256 public paintAddSecondsAfterBlitz = 20;
/// @dev Percentage of session rewards to contract balance.
uint256 public sessionRewardPercentage = 5;
/// @dev Percentage of crown to session rewards.
uint256 public crownPercentage = 10;
/// @dev Total squares painted count. Updated during active session. To be reset after each session.
uint16 public totalSquaresPainted;
/// @dev The total rewards that have not been claimed by painters for the session,
uint256 public unclaimedRewards;
/// @dev The rewards for eligible painters. Calculated when the session is over.
mapping(address => uint256) internal _painterTotalRewards;
/// @dev The unix timestamp for when the session ends.
uint256 private _sessionEndTime;
/// @dev The avaliable colors to paint with.
uint24[] private _colors = [1, 2, 3, 4, 5];
/// @dev The current number of squares painted a certain color. Updated during active session.
ColorData[colorsCount] private _colorData;
/// @dev Painters who have paint on the board.
address[squaresCount] private _canvasPainter;
/// @dev Cost of each square on the board.
uint256[squaresCount] private _canvasCost;
/// @dev The state of rewards calculation.
bool private _isRewardsCalculated;
/// @dev Mapping of crownPainter to each color at session end.
mapping(uint24 => address) private _crownPainter;
/// @dev Mapping of count of squares painted by each painter for each color.
mapping(uint24 => mapping(address => uint16)) private _colorPainterCount;
event SessionStarted(uint256 sessionEndTime);
event SquarePainted(
uint256 sessionEndTime,
uint16 squareIndex,
uint24 newColor,
address painter,
uint256 cost,
uint16 colorCount
);
event RewardsCalculated(
uint24 mostPopularColor,
uint16 mostPopularSquaresCount,
uint256 ethRewardPerSquare
);
event RewardsClaimed(address painter, uint256 claimed);
constructor(
address canvasAddress,
address initialOwner
) Ownable(initialOwner) {
require(
canvasAddress != address(0),
"Canvas address cannot be the zero address"
);
_canvas = ICanvas(canvasAddress);
}
modifier writeEnabled() {
require(isWriteEnabled(), "Session is not active");
_;
}
modifier onlyOwnerOrSession() {
require(
msg.sender == owner() || msg.sender == address(nextSession),
"Only owner or next session can call this function"
);
_;
}
modifier squareInBounds(uint16 squareIndex) {
require(squareIndex < squaresCount, "Index out of bounds");
_;
}
modifier colorInBounds(uint24 color) {
require(color < colorsCount, "Color out of bounds");
require(color > 0, "Color cannot be empty");
_;
}
receive() external payable {}
/// @dev Sets the token address. Once set, it cannot be changed.
function setToken(address tokenAddress) external onlyOwner {
require(address(token) == address(0), "Token has already been set");
token = IERC20(tokenAddress);
}
/// @dev Sets the next session address. Once set, it cannot be changed.
function setNextSession(address nextSessionAddress) external onlyOwner {
require(
address(nextSession) == address(0),
"Next session has already been set"
);
nextSession = ISession(nextSessionAddress);
}
/// @dev Sets the initial duration of the session.
function setInitialDuration(uint256 initialDuration_) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(
initialDuration_ <= 86400,
"Initial duration cannot be more than 1 day"
);
initialDuration = initialDuration_;
}
/// @dev Sets the amount of seconds added to the session duration before blitz threshold is reached.
function setPaintAddSecondsBeforeBlitz(
uint256 paintAddSecondsBeforeBlitz_
) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(
paintAddSecondsBeforeBlitz_ <= 60,
"Cannot add more than 1 minute per square"
);
paintAddSecondsBeforeBlitz = paintAddSecondsBeforeBlitz_;
}
/// @dev Sets the amount of seconds added to the session duration after blitz threshold is reached.
function setPaintAddSecondsAfterBlitz(
uint256 paintAddSecondsAfterBlitz_
) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(
paintAddSecondsAfterBlitz_ <= 60,
"Cannot add more than 1 minute per square"
);
paintAddSecondsAfterBlitz = paintAddSecondsAfterBlitz_;
}
/// @dev Sets percentage of the session rewards to be distributed based on contract balance.
function setSessionRewardPercentage(
uint256 sessionRewardPercentage_
) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(
sessionRewardPercentage_ <= 50,
"Session reward percentage cannot be more than 50%"
);
sessionRewardPercentage = sessionRewardPercentage_;
}
/// @dev Sets the percentage of crown rewards based on session rewards.
function setCrownPercentage(uint256 crownPercentage_) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(crownPercentage_ <= 20, "Crown reward cannot be more than 20%");
crownPercentage = crownPercentage_;
}
/// @dev Sets the blitz threshold.
function setBlitzThreshold(uint256 blitzThreshold_) external onlyOwner {
require(_sessionEndTime == 0, "Session already started");
require(
blitzThreshold_ <= initialDuration,
"Blitz threshold cannot be greater than initialDuration"
);
blitzThreshold = blitzThreshold_;
}
/// @dev Starts the session
function startSession() external onlyOwnerOrSession {
require(_sessionEndTime == 0, "Session already started");
require(
address(nextSession) != address(0),
"Next session has not been set"
);
require(
!nextSession.hasStarted(),
"Cannot start while next session is active"
);
_sessionEndTime = block.timestamp + initialDuration;
_isRewardsCalculated = false;
_colorData[0] = ColorData(0, squaresCount);
emit SessionStarted(_sessionEndTime);
}
/// @dev Returns whether the session has started
function hasStarted() external view returns (bool) {
return _sessionEndTime != 0;
}
/// @dev Returns the end time of the session.
function sessionEndTime() external view returns (uint256) {
return _sessionEndTime;
}
/// @dev Returns the colors of the canvas.
function getAvailableColors() external view returns (uint24[] memory) {
return _colors;
}
/// @dev Returns the rewards for a painter for the recently concluded session.
function getRewardShare(address painter) external view returns (uint256) {
return _painterTotalRewards[painter];
}
/// @dev Returns the painters of all squares.
function getPainters()
external
view
returns (address[squaresCount] memory)
{
return _canvasPainter;
}
/// @dev Returns the costs of all squares.
function getCosts() external view returns (uint256[squaresCount] memory) {
return _canvasCost;
}
/// @dev Returns the painter of a square.
function getPainter(
uint16 squareIndex
) external view squareInBounds(squareIndex) returns (address) {
return _canvasPainter[squareIndex];
}
/// @dev Returns the cost of painting a square.
function getCost(
uint16 squareIndex
) external view squareInBounds(squareIndex) returns (uint256) {
return _canvasCost[squareIndex];
}
/// @dev Returns the counts of all the colors during the session. Reset after the session concludes
function getColorsData()
external
view
returns (ColorData[colorsCount] memory)
{
return _colorData;
}
/// @dev Returns the counts of a color during the session. Reset after the session concludes
function getColorCount(
uint24 color
) external view colorInBounds(color) returns (uint16) {
return _colorData[color].count;
}
/// @dev Returns the allocated rewards for the session.
function getSessionRewards() external view returns (uint256) {
return
((address(this).balance - unclaimedRewards) *
sessionRewardPercentage) / 100;
}
/// @dev Returns the allocated crown rewards for the session. Crown rewards are a percentage of session rewards.
function getCrownRewards() external view returns (uint256) {
return
((address(this).balance - unclaimedRewards) *
sessionRewardPercentage *
crownPercentage) / 10000;
}
/// @notice External function to paint squares on the canvas
/// @dev Main function to paint during an active painting session.
function paintSquares(
uint16[] calldata squareIndex,
uint24 newColor
) external writeEnabled colorInBounds(newColor) nonReentrant {
require(squareIndex.length > 0, "No squares to paint");
require(
squareIndex.length <= 10,
"Cannot paint more than 10 squares at once"
);
uint16 _len = uint16(squareIndex.length);
uint256 _cost;
totalSquaresPainted += _len;
_colorData[newColor].rank = totalSquaresPainted;
_addTimerSeconds(_len);
for (uint256 i = 0; i < _len; ++i) {
_paintSquare(squareIndex[i], newColor);
_cost += _canvasCost[squareIndex[i]]; // _paintSquare already updates this to be the overwrite cost
}
bool sent = token.transferFrom(msg.sender, address(this), _cost);
require(sent, "Failed to send PVP");
}
/// @notice Function to calculate painting rewards through the most popular color(s) on the canvas
/// @dev Called when the painting session is over.
function calculatePaintingRewards() external nonReentrant {
require(isSessionEnd(), "Session has not ended");
require(!isRewardsCalculated(), "Rewards have already been calculated");
_isRewardsCalculated = true;
delete _sessionEndTime; // refund gas
// rewards carry over to the next session if no squares painted
if (totalSquaresPainted == 0) {
ISession(nextSession).startSession();
emit RewardsCalculated(0, 0, 0);
return;
}
(
uint24 _mostPopularColor,
uint16 _mostPopularSquaresCount
) = _calculateMostPopularColor();
// availableRewards is contract's ETH balance minus unclaimedRewards
uint256 availableRewards = address(this).balance - unclaimedRewards;
// rewards per square is available rewards divided by squares painted most popular color
uint256 _ethRewardPerSquare = (availableRewards *
sessionRewardPercentage) /
100 /
_mostPopularSquaresCount;
// crownReward is the rewards allocated for the crown painter (portion of session rewards)
uint256 _crownRewardPerColor = (availableRewards *
sessionRewardPercentage *
crownPercentage) / 10000;
delete totalSquaresPainted; // refund gas
// adds mostPopularColor rewards to painters AND calculates crownPainters
for (uint16 i = 0; i < squaresCount; ++i) {
uint24 _color = _canvas.getSquareColor(i);
address _painter = _canvasPainter[i];
++_colorPainterCount[_color][_painter];
unchecked {
if (_color == _mostPopularColor) {
_painterTotalRewards[_painter] += _ethRewardPerSquare;
unclaimedRewards += _ethRewardPerSquare;
}
// calculates crown painters
if (
_colorPainterCount[_color][_painter] >
_colorPainterCount[_color][_crownPainter[_color]]
) {
_crownPainter[_color] = _painter;
}
}
}
// cleans up colorPainterCount
for (uint16 i = 0; i < squaresCount; ++i) {
delete _colorPainterCount[_canvas.getSquareColor(i)][
_canvasPainter[i]
]; // refund gas
delete _canvasPainter[i]; // refund gas
delete _canvasCost[i]; // refund gas
}
// adds crown rewards to crown painters
for (uint24 i = 1; i < colorsCount; ++i) {
if (_crownPainter[i] != address(0)) {
_painterTotalRewards[_crownPainter[i]] += _crownRewardPerColor;
unclaimedRewards += _crownRewardPerColor;
delete _crownPainter[i]; // refund gas
}
}
// burn all tokens used during the session
bool sent = token.transfer(address(0), token.balanceOf(address(this)));
require(sent, "Failed to send PVP");
_canvas.resetCanvas();
ISession(nextSession).startSession();
emit RewardsCalculated(
_mostPopularColor,
_mostPopularSquaresCount,
_ethRewardPerSquare
);
}
function isSessionEnd() public view returns (bool) {
return _sessionEndTime <= block.timestamp;
}
function isWriteEnabled() public view returns (bool) {
return _sessionEndTime > 0 && !isSessionEnd();
}
function isRewardsCalculated() public view returns (bool) {
return _isRewardsCalculated;
}
/// @dev Gets the price to paint a single square on the canvas
function getOverwriteSquarePrice(
uint16 squareIndex
) public view squareInBounds(squareIndex) returns (uint256) {
uint _cost = _canvasCost[squareIndex];
if (_cost == 0) return START_PAINT_PRICE;
return _cost + (_cost * OVERWRITE_PERCENT) / 100;
}
/// @dev Gets the total price to paint multiple squares on the canvas
function getOverwriteSquaresPrice(
uint16[] calldata squareIndex
) public view returns (uint256) {
uint256 _cost = 0;
for (uint256 i = 0; i < squareIndex.length; ++i) {
_cost += getOverwriteSquarePrice(squareIndex[i]);
}
return _cost;
}
/// @dev Sets the amount of seconds added to the session duration when a square is painted.
function _addTimerSeconds(uint16 numSquares) private {
if (_sessionEndTime < block.timestamp + blitzThreshold) {
// blitz threshold has been reached
uint256 secondsToAdd = numSquares * paintAddSecondsAfterBlitz;
_sessionEndTime += secondsToAdd;
if (_sessionEndTime > block.timestamp + blitzThreshold) {
_sessionEndTime = block.timestamp + blitzThreshold;
}
} else {
// blitz threshold has not been reached
uint256 secondsToAdd = numSquares * paintAddSecondsBeforeBlitz;
_sessionEndTime += secondsToAdd;
}
}
/// @notice Function to paint a single square on the canvas
function _paintSquare(
uint16 squareIndex,
uint24 newColor
) private squareInBounds(squareIndex) {
uint24 _oldColor = _canvas.getSquareColor(squareIndex);
require(
_oldColor != newColor,
"Square cannot be painted its existing color"
);
unchecked {
if (_colorData[_oldColor].count > 0) --_colorData[_oldColor].count;
++_colorData[newColor].count;
}
_canvasPainter[squareIndex] = msg.sender;
_canvasCost[squareIndex] = getOverwriteSquarePrice(squareIndex);
_canvas.setSquareColor(squareIndex, newColor);
emit SquarePainted(
_sessionEndTime,
squareIndex,
newColor,
msg.sender,
_canvasCost[squareIndex],
_colorData[newColor].count
);
}
/// @dev Calculates the most popular color on the canvas.
/// If there is a tie in color count, the more recently painted color is the winner.
function _calculateMostPopularColor() private returns (uint24, uint16) {
uint16 _maxRank = 0;
uint24 _mostPopularColor = 0;
uint16 _mostPopularSquaresCount = 1; // to avoid division by zero
// Not possible to paint with i = 0
for (uint16 i = 1; i < colorsCount; ++i) {
uint16 _colorCount = _colorData[i].count;
uint16 _colorRank = _colorData[i].rank;
if (
_mostPopularSquaresCount < _colorCount ||
(_maxRank < _colorRank &&
_mostPopularSquaresCount == _colorCount)
) {
_mostPopularSquaresCount = _colorCount;
_maxRank = _colorData[i].rank;
_mostPopularColor = i;
}
delete _colorData[i]; // refund gas
}
return (_mostPopularColor, _mostPopularSquaresCount);
}
}
contract SessionAlpha is SessionInternal {
constructor(
address canvasAddress,
address initialOwner
) SessionInternal(canvasAddress, initialOwner) {}
/// @dev Function to claim ETH rewards. Can be claimed any time and is built up after each session.
function claimRewards() external nonReentrant {
uint256 _rewardsShare = _painterTotalRewards[msg.sender];
require(_rewardsShare > 0, "You have no painting rewards to claim");
delete _painterTotalRewards[msg.sender];
if (unclaimedRewards > 0) unclaimedRewards -= _rewardsShare;
(bool sent, ) = payable(msg.sender).call{value: _rewardsShare}("");
require(sent, "Failed to send Ether");
emit RewardsClaimed(msg.sender, _rewardsShare);
}
/// @dev Function for owner to action a claim of ETH rewards for a painter.
// Should only be used if there are unexpected issues with a painter claiming rewards.
function claimRewardsPortion(
address painter,
uint256 amount
) external onlyOwner {
require(amount > 0, "Amount must be greater than 0");
require(
_painterTotalRewards[painter] >= amount,
"Insufficient total rewards"
);
_painterTotalRewards[painter] -= amount;
if (unclaimedRewards > 0) unclaimedRewards -= amount;
(bool sent, ) = payable(painter).call{value: amount}("");
require(sent, "Failed to send Ether");
emit RewardsClaimed(painter, amount);
}
}
contract SessionBeta is SessionInternal {
constructor(
address canvasAddress,
address initialOwner
) SessionInternal(canvasAddress, initialOwner) {}
/// @dev Function to claim ETH rewards. Can be claimed any time and is built up after each session.
function claimRewards() external nonReentrant {
uint256 _rewardsShare = _painterTotalRewards[msg.sender];
require(_rewardsShare > 0, "You have no painting rewards to claim");
delete _painterTotalRewards[msg.sender];
if (unclaimedRewards > 0) unclaimedRewards -= _rewardsShare;
(bool sent, ) = payable(msg.sender).call{value: _rewardsShare}("");
require(sent, "Failed to send Ether");
emit RewardsClaimed(msg.sender, _rewardsShare);
}
/// @dev Function for owner to action a claim of ETH rewards for a painter.
// Should only be used if there are unexpected issues with a painter claiming rewards.
function claimRewardsPortion(
address painter,
uint256 amount
) external onlyOwner {
require(amount > 0, "Amount must be greater than 0");
require(
_painterTotalRewards[painter] >= amount,
"Insufficient total rewards"
);
_painterTotalRewards[painter] -= amount;
if (unclaimedRewards > 0) unclaimedRewards -= amount;
(bool sent, ) = payable(painter).call{value: amount}("");
require(sent, "Failed to send Ether");
emit RewardsClaimed(painter, amount);
}
}
{
"compilationTarget": {
"contracts/session/Session.sol": "SessionBeta"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": false,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"canvasAddress","type":"address"},{"internalType":"address","name":"initialOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint24","name":"mostPopularColor","type":"uint24"},{"indexed":false,"internalType":"uint16","name":"mostPopularSquaresCount","type":"uint16"},{"indexed":false,"internalType":"uint256","name":"ethRewardPerSquare","type":"uint256"}],"name":"RewardsCalculated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"painter","type":"address"},{"indexed":false,"internalType":"uint256","name":"claimed","type":"uint256"}],"name":"RewardsClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"sessionEndTime","type":"uint256"}],"name":"SessionStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"sessionEndTime","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"squareIndex","type":"uint16"},{"indexed":false,"internalType":"uint24","name":"newColor","type":"uint24"},{"indexed":false,"internalType":"address","name":"painter","type":"address"},{"indexed":false,"internalType":"uint256","name":"cost","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"colorCount","type":"uint16"}],"name":"SquarePainted","type":"event"},{"inputs":[],"name":"OVERWRITE_PERCENT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"START_PAINT_PRICE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"blitzThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"calculatePaintingRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"painter","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"claimRewardsPortion","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"crownPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAvailableColors","outputs":[{"internalType":"uint24[]","name":"","type":"uint24[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint24","name":"color","type":"uint24"}],"name":"getColorCount","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getColorsData","outputs":[{"components":[{"internalType":"uint16","name":"rank","type":"uint16"},{"internalType":"uint16","name":"count","type":"uint16"}],"internalType":"struct ColorData[6]","name":"","type":"tuple[6]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"squareIndex","type":"uint16"}],"name":"getCost","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCosts","outputs":[{"internalType":"uint256[100]","name":"","type":"uint256[100]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCrownRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"squareIndex","type":"uint16"}],"name":"getOverwriteSquarePrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16[]","name":"squareIndex","type":"uint16[]"}],"name":"getOverwriteSquaresPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"squareIndex","type":"uint16"}],"name":"getPainter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPainters","outputs":[{"internalType":"address[100]","name":"","type":"address[100]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"painter","type":"address"}],"name":"getRewardShare","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSessionRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hasStarted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isRewardsCalculated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isSessionEnd","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isWriteEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextSession","outputs":[{"internalType":"contract ISession","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paintAddSecondsAfterBlitz","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paintAddSecondsBeforeBlitz","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16[]","name":"squareIndex","type":"uint16[]"},{"internalType":"uint24","name":"newColor","type":"uint24"}],"name":"paintSquares","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sessionEndTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sessionRewardPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"blitzThreshold_","type":"uint256"}],"name":"setBlitzThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"crownPercentage_","type":"uint256"}],"name":"setCrownPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialDuration_","type":"uint256"}],"name":"setInitialDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"nextSessionAddress","type":"address"}],"name":"setNextSession","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"paintAddSecondsAfterBlitz_","type":"uint256"}],"name":"setPaintAddSecondsAfterBlitz","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"paintAddSecondsBeforeBlitz_","type":"uint256"}],"name":"setPaintAddSecondsBeforeBlitz","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"sessionRewardPercentage_","type":"uint256"}],"name":"setSessionRewardPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"setToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startSession","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSquaresPainted","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unclaimedRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]