Contract Source Code:
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;
/// @notice All errors of the app
interface IAppErrors {
//region ERC20Errors
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
//endregion ERC20Errors
//region ERC721Errors
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
//endregion ERC721Errors
error ZeroAddress();
error ZeroValueNotAllowed();
error ZeroToken();
error LengthsMismatch();
error NotEnoughBalance();
error NotEnoughAllowance();
error EmptyNameNotAllowed();
error NotInitialized();
error AlreadyInitialized();
error ReentrancyGuardReentrantCall();
error TooLongString();
error AlreadyDeployed(address deployed);
//region Restrictions
error ErrorNotDeployer(address sender);
error ErrorNotGoc();
error NotGovernance(address sender);
error ErrorOnlyEoa();
error NotEOA(address sender);
error ErrorForbidden(address sender);
error AdminOnly();
error ErrorNotItemController(address sender);
error ErrorNotHeroController(address sender);
error ErrorNotDungeonFactory(address sender);
error ErrorNotObjectController(address sender);
error ErrorNotStoryController();
error ErrorNotAllowedSender();
error MintNotAllowed();
//endregion Restrictions
//region PackingLib
error TooHighValue(uint value);
error IntValueOutOfRange(int value);
error OutOfBounds(uint index, uint length);
error UnexpectedValue(uint expected, uint actual);
error WrongValue(uint newValue, uint actual);
error IntOutOfRange(int value);
error ZeroValue();
/// @notice packCustomDataChange requires an input string with two zero bytes at the beginning
/// 0xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0000
/// This error happens if these bytes are not zero
error IncompatibleInputString();
error IncorrectOtherItemTypeKind(uint8 kind);
//endregion PackingLib
//region Hero
error ErrorHeroIsNotRegistered(address heroToken);
error ErrorHeroIsDead(address heroToken, uint heroTokenId);
error ErrorHeroNotInDungeon();
error HeroInDungeon();
error ErrorNotOwner(address token, uint tokenId);
error Staked(address heroToken, uint heroId);
error NameTaken();
error TooBigName();
error WrongSymbolsInTheName();
error NoPayToken(address token, uint payTokenAmount);
error AlreadyHaveReinforcement();
/// @notice SIP-001 - Reinforcement requires 3 skills
error ErrorReinforcementRequiresThreeSkills();
error WrongTier(uint tier);
error NotEnoughNgLevel(uint8 ngLevel);
error NgpNotActive(address hero);
error RebornNotAllowed();
error AlreadyPrePaidHero();
//endregion Hero
//region Dungeon
error ErrorDungeonIsFreeAlready();
error ErrorNoEligibleDungeons();
error ErrorDungeonBusy();
error ErrorNoDungeonsForBiome(uint8 heroBiome);
error ErrorDungeonCompleted();
error ErrorAlreadyInDungeon();
error NotEnoughTokens(uint balance, uint expectedBalance);
error DungeonAlreadySpecific(uint16 dungNum);
error DungeonAlreadySpecific2(uint16 dungNum);
error WrongSpecificDungeon();
//endregion Dungeon
//region Items
error ErrorItemNotEligibleForTheSlot(uint itemType, uint8 itemSlot);
error ErrorItemSlotBusyHand(uint8 slot);
error ErrorItemSlotBusy();
error ErrorItemNotInSlot();
error ErrorConsumableItemIsUsed(address item);
error ErrorCannotRemoveItemFromMap();
error ErrorCannotRemoveDataFromMap();
error EquippedItemsExist();
error ItemEquipped(address item, uint itemId);
error ZeroItemMetaType();
error NotZeroOtherItemMetaType();
error ZeroLevel();
error ItemTypeChanged();
error ItemMetaTypeChanged();
error UnknownItem(address item);
error ErrorEquipForbidden();
error EquipForbiddenInDungeon();
error TakeOffForbiddenInDungeon();
error Consumable(address item);
error NotConsumable(address item);
error Broken(address item);
error ZeroLife();
error RequirementsToItemAttributes();
error NotEquipped(address item);
error ZeroDurability();
error ZeroAugmentation();
error TooHighAgLevel(uint8 augmentationLevel);
error UseForbiddenZeroPayToken();
error IncorrectMinMaxAttributeRange(int32 min, int32 max);
error SameIdsNotAllowed();
error ZeroFragility();
error OtherTypeItemNotRepairable();
error NotOther();
error DoubleItemUsageForbidden(uint itemIndex, address[] items);
error ItemAlreadyUsedInSlot(address item, uint8 equippedSlot);
error WrongWayToRegisterItem();
error UnionItemNotFound(address item);
error WrongListUnionItemTokens(address item, uint countTokens, uint requiredCountTokens);
error UnknownUnionConfig(uint unionConfigId);
error UserHasNoKeyPass(address user, address keyPassItem);
error MaxValue(uint value);
error UnexpectedOtherItem(address item);
error NotExist();
//endregion Items
//region Stages
error ErrorWrongStage(uint stage);
error ErrorNotStages();
//endregion Stages
//region Level
error ErrorWrongLevel(uint heroLevel);
error ErrorLevelTooLow(uint heroLevel);
error ErrorHeroLevelStartFrom1();
error ErrorWrongLevelUpSum();
error ErrorMaxLevel();
//endregion Level
//region Treasure
error ErrorNotValidTreasureToken(address treasureToken);
//endregion Treasure
//region State
error ErrorPaused();
error ErrorNotReady();
error ErrorNotObject1();
error ErrorNotObject2();
error ErrorNotCompleted();
//endregion State
//region Biome
error ErrorNotBiome();
error ErrorIncorrectBiome(uint biome);
error TooHighBiome(uint biome);
//endregion Biome
//region Misc
error ErrorWrongMultiplier(uint multiplier);
error ErrorNotEnoughMana(uint32 mana, uint requiredMana);
error ErrorExperienceMustNotDecrease();
error ErrorNotEnoughExperience();
error ErrorNotChances();
error ErrorNotEligible(address heroToken, uint16 dungNum);
error ErrorZeroKarmaNotAllowed();
//endregion Misc
//region GOC
error GenObjectIdBiomeOverflow(uint8 biome);
error GenObjectIdSubTypeOverflow(uint subType);
error GenObjectIdIdOverflow(uint id);
error UnknownObjectTypeGoc1(uint8 objectType);
error UnknownObjectTypeGoc2(uint8 objectType);
error UnknownObjectTypeGocLib1(uint8 objectType);
error UnknownObjectTypeGocLib2(uint8 objectType);
error UnknownObjectTypeForSubtype(uint8 objectSubType);
error FightDelay();
error ZeroChance();
error TooHighChance(uint32 chance);
error TooHighRandom(uint random);
error EmptyObjects();
error ObjectNotFound();
error WrongGetObjectTypeInput();
error WrongChances(uint32 chances, uint32 maxChances);
//endregion GOC
//region Story
error PageNotRemovedError(uint pageId);
error NotItem1();
error NotItem2();
error NotRandom(uint32 random);
error NotHeroData();
error NotGlobalData();
error ZeroStoryIdRemoveStory();
error ZeroStoryIdStoryAction();
error ZeroStoryIdAction();
error NotEnoughAmount(uint balance, uint requiredAmount);
error NotAnswer();
error AnswerStoryIdMismatch(uint16 storyId, uint16 storyIdFromAnswerHash);
error AnswerPageIdMismatch(uint16 pageId, uint16 pageIdFromAnswerHash);
//endregion Story
//region FightLib
error NotMagic();
error NotAType(uint atype);
//endregion FightLib
//region MonsterLib
error NotYourDebuffItem();
error UnknownAttackType(uint attackType);
error NotYourAttackItem();
/// @notice The skill item cannot be used because it doesn't belong either to the hero or to the hero's helper
error NotYourBuffItem();
//endregion MonsterLib
//region GameToken
error ApproveToZeroAddress();
error MintToZeroAddress();
error TransferToZeroAddress();
error TransferAmountExceedsBalance(uint balance, uint value);
error InsufficientAllowance();
error BurnAmountExceedsBalance();
error NotMinter(address sender);
//endregion GameToken
//region NFT
error TokenTransferNotAllowed();
error IdOverflow(uint id);
error NotExistToken(uint tokenId);
error EquippedItemIsNotAllowedToTransfer(uint tokenId);
//endregion NFT
//region CalcLib
error TooLowX(uint x);
//endregion CalcLib
//region Controller
error NotFutureGovernance(address sender);
//endregion Controller
//region Oracle
error OracleWrongInput();
//endregion Oracle
//region ReinforcementController
error AlreadyStaked();
error MaxFee(uint8 fee);
error MinFee(uint8 fee);
error StakeHeroNotStats();
error NotStaked();
error NoStakedHeroes();
error GuildHelperNotAvailable(uint guildId, address helper, uint helperId);
error HelperNotAvailableInGivenBiome();
//endregion ReinforcementController
//region SponsoredHero
error InvalidHeroClass();
error ZeroAmount();
error InvalidProof();
error NoHeroesAvailable();
error AlreadyRegistered();
//endregion SponsoredHero
//region SacraRelay
error SacraRelayNotOwner();
error SacraRelayNotDelegator();
error SacraRelayNotOperator();
error SacraRelayInvalidChainId(uint callChainId, uint blockChainId);
error SacraRelayInvalidNonce(uint callNonce, uint txNonce);
error SacraRelayDeadline();
error SacraRelayDelegationExpired();
error SacraRelayNotAllowed();
error SacraRelayInvalidSignature();
/// @notice This error is generated when custom error is caught
/// There is no info about custom error in SacraRelay
/// but you can decode custom error by selector, see tests
error SacraRelayNoErrorSelector(bytes4 selector, string tracingInfo);
/// @notice This error is generated when custom error is caught
/// There is no info about custom error in SacraRelay
/// but you can decode custom error manually from {errorBytes} as following:
/// if (keccak256(abi.encodeWithSignature("MyError()")) == keccak256(errorBytes)) { ... }
error SacraRelayUnexpectedReturnData(bytes errorBytes, string tracingInfo);
error SacraRelayCallToNotContract(address notContract, string tracingInfo);
//endregion SacraRelay
//region Misc
error UnknownHeroClass(uint heroClass);
error AbsDiff(int32 a, int32 b);
//region Misc
//region ------------------------ UserController
error NoAvailableLootBox(address msgSender, uint lootBoxKind);
error FameHallHeroAlreadyRegistered(uint8 openedNgLevel);
//endregion ------------------------ UserController
//region ------------------------ Guilds
error AlreadyGuildMember();
error NotGuildMember();
error WrongGuild();
error GuildActionForbidden(uint right);
error GuildHasMaxSize(uint guildSize);
error GuildHasMaxLevel(uint level);
error TooLongUrl();
error TooLongDescription();
error CannotRemoveGuildOwnerFromNotEmptyGuild();
error GuildControllerOnly();
error GuildAlreadyHasShelter();
error ShelterIsBusy();
error ShelterIsNotRegistered();
error ShelterIsNotOwnedByTheGuild();
error ShelterIsInUse();
error GuildHasNoShelter();
error ShelterBidIsNotAllowedToBeUsed();
error ShelterHasHeroesInside();
error SecondGuildAdminIsNotAllowed();
error NotEnoughGuildBankBalance(uint guildId);
error GuildReinforcementCooldownPeriod();
error NoStakedGuildHeroes();
error NotStakedInGuild();
error ShelterHasNotEnoughLevelForReinforcement();
error NotBusyGuildHelper();
error GuildRequestNotActive();
error GuildRequestNotAvailable();
error NotAdminCannotAddMemberWithNotZeroRights();
//endregion ------------------------ Guilds
//region ------------------------ Shelters
error ErrorNotShelterController();
error ErrorNotGuildController();
error ShelterHasNotItem(uint shelterId, address item);
error MaxNumberItemsSoldToday(uint numSoldItems, uint limit);
error GuildHasNotEnoughPvpPoints(uint64 pointsAvailable, uint pointRequired);
error FreeShelterItemsAreNotAllowed(uint shelterId, address item);
error TooLowShelterLevel(uint8 shelterLevel, uint8 allowedShelterLevel);
error NotEnoughPvpPointsCapacity(address user, uint usedPoints, uint pricePvpPoints, uint64 capactiy);
error IncorrectShelterLevel(uint8 shelterLevel);
//endregion ------------------------ Shelters
//region ------------------------ Auction
error WrongAuctionPosition();
error AuctionPositionClosed();
error AuctionBidOpened(uint positionId);
error TooLowAmountToBid();
error AuctionEnded();
error TooLowAmountForNewBid();
error AuctionSellerOnly();
error AuctionBuyerOnly();
error AuctionBidNotFound();
error AuctionBidClosed();
error OnlyShelterAuction();
error CannotCloseLastBid();
error AuctionNotEnded();
error NotShelterAuction();
error AuctionPositionOpened(uint positionId);
error AuctionSellerCannotBid();
error AuctionGuildWithShelterCannotBid();
error AuctionBidExists();
//endregion ------------------------ Auction
//region ------------------------ Pawnshop
error AuctionPositionNotSupported(uint positionId);
error PositionNotSupported(uint positionId);
error NotNftPositionNotSupported(uint positionId);
error CallFailed(bytes callResultData);
error PawnShopZeroOwner();
error PawnShopZeroFeeRecipient();
error PawnShopNotOwner();
error PawnShopAlreadyAnnounced();
error PawnShopTimeLock();
error PawnShopWrongAddressValue();
error PawnShopWrongUintValue();
error PawnShopZeroAddress();
error PawnShopTooHighValue();
error PawnShopZeroAToken();
error PawnShopZeroCToken();
error PawnShopWrongAmounts();
error PawnShopPosFeeForInstantDealForbidden();
error PawnShopPosFeeAbsurdlyHigh();
error PawnShopIncorrect();
error PawnShopWrongId();
error PawnShopNotBorrower();
error PawnShopPositionClosed();
error PawnShopPositionExecuted();
error PawnShopWrongBidAmount();
error PawnShopTooLowBid();
error PawnShopNewBidTooLow();
error PawnShopBidAlreadyExists();
error PawnShopAuctionEnded();
error PawnShopNotLender();
error PawnShopTooEarlyToClaim();
error PawnShopPositionNotExecuted();
error PawnShopAlreadyClaimed();
error PawnShopAuctionNotEnded();
error PawnShopBidClosed();
error PawnShopNoBids();
error PawnShopAuctionBidNotFound();
error PawnShopWrongBid();
error PawnShopBidNotFound();
//endregion ------------------------ Pawnshop
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;
import "../openzeppelin/EnumerableSet.sol";
import "../openzeppelin/ECDSA.sol";
import "../interfaces/IAppErrors.sol";
/// @title Sacra relay contract
contract SacraRelay {
using EnumerableSet for EnumerableSet.AddressSet;
//region ------------------------ Data types
/// @notice Relay call with user signature verification for ERC 2771 compliance
struct CallWithERC2771 {
uint chainId;
address target;
bytes data;
address user;
uint userNonce;
uint userDeadline;
}
//endregion ------------------------ Data types
//region ------------------------ Constants
string public constant NAME = "SacraRelay";
string public constant VERSION = "1.0.1";
uint public immutable DELEGATION_DEADLINE = 1 weeks;
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant CALL_ERC2771_TYPEHASH =
keccak256(
bytes(
"CallERC2771(uint256 chainId,address target,bytes data,address user,uint256 userNonce,uint256 userDeadline)"
)
);
//endregion ------------------------ Constants
//region ------------------------ Variables
/// @dev Suppose to be the game governance
address public owner;
/// @dev Allowed EOAs to call game contract on behalf of users
EnumerableSet.AddressSet private _operators;
/// @dev Allowance is a sequence of numbers where any non zero value means that operator is allowed to call game contract on behalf of user
mapping(address => bool) public allowance;
/// @dev Nonce for each user to prevent tx duplication
mapping(address => uint) public userTxNonce;
/// @dev User => Delegator. A user can allow another EOA to call any game action on behalf of him
mapping(address => address) public delegatedCallers;
/// @dev Delegator => Deadline for delegation
mapping(address => uint) public delegatedDeadline;
//endregion ------------------------ Variables
//region ------------------------ Events
event CalledFromOperator(CallWithERC2771 callData);
event CalledFromDelegator(CallWithERC2771 callData);
//endregion ------------------------ Events
//region ------------------------ Constructor
constructor(address owner_) {
owner = owner_;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
bytes(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
)
),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
block.chainid,
address(this)
)
);
}
//endregion ------------------------ Constructor
//region ------------------------ Views
/// @dev Get all operators
function operatorsList() external view returns (address[] memory) {
return _operators.values();
}
/// @dev Get user info
function userInfo(address user) external view returns (uint nonce, bool allowed, address delegator, uint delegatorDeadline) {
delegator = delegatedCallers[user];
return (userTxNonce[user], allowance[user], delegator, delegatedDeadline[delegator]);
}
//endregion ------------------------ Views
//region ------------------------ Owner actions
/// @dev Change owner of this contract
function changeOwner(address newOwner) external {
if (msg.sender != owner) revert IAppErrors.SacraRelayNotOwner();
owner = newOwner;
}
/// @dev Add or remove operator
function changeOperator(address operator, bool add) external {
if (msg.sender != owner) revert IAppErrors.SacraRelayNotOwner();
if (add) {
_operators.add(operator);
} else {
_operators.remove(operator);
}
}
//endregion ------------------------ Owner actions
//region ------------------------ Main logic
/// @dev Approve or disapprove operator to call game contract on behalf of users
function approve(bool status) external {
allowance[msg.sender] = status;
}
/// @dev Allow to call game contract on behalf of user for given EOA.
/// Zero delegator address means that user revoke permission for this EOA.
/// A user can refuel his delegator by sending some ether with this call.
function delegate(address delegator) external payable {
address oldDelegator = delegatedCallers[msg.sender];
delegatedCallers[msg.sender] = delegator;
delete delegatedDeadline[oldDelegator];
delegatedDeadline[delegator] = block.timestamp + DELEGATION_DEADLINE;
if (msg.value > 0) {
payable(delegator).transfer(msg.value);
}
}
/// @dev Close delegation for user.
/// Delegator can send back ether to user with this call.
function closeDelegation(address user) external payable {
if (delegatedCallers[user] != msg.sender) revert IAppErrors.SacraRelayNotDelegator();
delete delegatedCallers[user];
delete delegatedDeadline[msg.sender];
if (msg.value > 0) {
payable(user).transfer(msg.value);
}
}
/// @dev Call from delegator. No user signature required.
/// We assume delegator is under control of user.
function callFromDelegator(CallWithERC2771 calldata callInfo) external {
if (delegatedCallers[callInfo.user] != msg.sender) revert IAppErrors.SacraRelayNotDelegator();
if (callInfo.chainId != block.chainid) revert IAppErrors.SacraRelayInvalidChainId(callInfo.chainId, block.chainid);
uint _userTxNonce = userTxNonce[callInfo.user];
if (callInfo.userNonce != _userTxNonce) revert IAppErrors.SacraRelayInvalidNonce(callInfo.userNonce, _userTxNonce);
if (callInfo.userDeadline != 0 && callInfo.userDeadline < block.timestamp) revert IAppErrors.SacraRelayDeadline();
if (delegatedDeadline[msg.sender] < block.timestamp) revert IAppErrors.SacraRelayDelegationExpired();
userTxNonce[callInfo.user] = _userTxNonce + 1;
_revertingContractCall(callInfo.target, _encodeERC2771Context(callInfo.data, callInfo.user), "SacraRelay.DelegatedCall");
emit CalledFromDelegator(callInfo);
}
/// @dev Call game contract on behalf of user. Require user signature for every call.
function callFromOperator(CallWithERC2771 calldata callInfo, bytes calldata userSignature_) external {
if (!_operators.contains(msg.sender)) revert IAppErrors.SacraRelayNotOperator();
if (callInfo.chainId != block.chainid) revert IAppErrors.SacraRelayInvalidChainId(callInfo.chainId, block.chainid);
// a user should allow this contract to call game contracts on behalf of him
if (!allowance[callInfo.user]) revert IAppErrors.SacraRelayNotAllowed();
uint _userTxNonce = userTxNonce[callInfo.user];
if (callInfo.userNonce != _userTxNonce) revert IAppErrors.SacraRelayInvalidNonce(callInfo.userNonce, _userTxNonce);
if (callInfo.userDeadline != 0 && callInfo.userDeadline < block.timestamp) revert IAppErrors.SacraRelayDeadline();
// Verify user's signature
_requireCallERC2771Signature(callInfo, userSignature_);
userTxNonce[callInfo.user] = _userTxNonce + 1;
_revertingContractCall(callInfo.target, _encodeERC2771Context(callInfo.data, callInfo.user), "SacraRelay.CallERC2771");
emit CalledFromOperator(callInfo);
}
//endregion ------------------------ Main logic
//region ------------------------ Internal logic
/// @dev from GelatoCallUtils
function _revertingContractCall(
address _contract,
bytes memory _data,
string memory _errorMsg
) internal returns (bytes memory returnData) {
bool success;
(success, returnData) = _contract.call(_data);
// solhint-disable-next-line max-line-length
// https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/f9b6fc3fdab7aca33a9cfa8837c5cd7f67e176be/contracts/utils/AddressUpgradeable.sol#L177
if (success) {
if (returnData.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (!_isContract(_contract)) revert IAppErrors.SacraRelayCallToNotContract(_contract, _errorMsg);
}
} else {
_revertWithError(returnData, _errorMsg);
}
}
/// @dev NOT SECURE CHECK! Just for more clear error messages
function _isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
function _revertWithError(bytes memory _bytes, string memory _tracingInfo) internal pure {
// 68: 32-location, 32-length, 4-ErrorSelector, UTF-8 err
if (_bytes.length % 32 == 4) {
bytes4 selector;
assembly {
selector := mload(add(0x20, _bytes))
}
if (selector == 0x08c379a0) {
// Function selector for Error(string)
assembly {
_bytes := add(_bytes, 68)
}
revert(string(abi.encodePacked(_tracingInfo, string(_bytes))));
} else {
revert IAppErrors.SacraRelayNoErrorSelector(selector, _tracingInfo);
}
} else {
revert IAppErrors.SacraRelayUnexpectedReturnData(_bytes, _tracingInfo);
}
}
/// @dev vanilla ERC2771 context encoding
function _encodeERC2771Context(bytes calldata _data, address _msgSender) pure internal returns (bytes memory){
return abi.encodePacked(_data, _msgSender);
}
function _requireCallERC2771Signature(CallWithERC2771 calldata callInfo, bytes calldata signature_) internal view returns (bytes32 digest) {
digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(_abiEncodeCallERC2771(callInfo))
)
);
(address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, signature_);
if (error != ECDSA.RecoverError.NoError || recovered != callInfo.user) revert IAppErrors.SacraRelayInvalidSignature();
}
function _abiEncodeCallERC2771(CallWithERC2771 calldata callInfo) internal pure returns (bytes memory){
return abi.encode(
CALL_ERC2771_TYPEHASH,
callInfo.chainId,
callInfo.target,
keccak256(callInfo.data),
callInfo.user,
callInfo.userNonce,
callInfo.userDeadline
);
}
//endregion ------------------------ Internal logic
receive() external payable {}
}