Verified contractExactUNLICENCED
SubscriptionCardWallet
Address0x3a1967fa0e5ef9a845129c347b39070ca5dceb4b
- Balance
0 ETH
- Transactions
685
- Compiler
solc 0.8.25
- Same code
1 more contract
Details
- Compiler
- solc 0.8.25+commit.b61c2a91
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- UNLICENCED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,932,316
- Creation transaction
- 0x7839024879…db81f00523
31 files
- contracts/SubscriptionCardWallet/SubscriptionCardWallet.solmain31.88 KB
- @openzeppelin/contracts/access/AccessControl.sol8.12 KB
- @openzeppelin/contracts/access/AccessControlEnumerable.sol2.41 KB
- @openzeppelin/contracts/access/IAccessControl.sol2.92 KB
- @openzeppelin/contracts/access/IAccessControlEnumerable.sol1.23 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol12.62 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol2.25 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol4.46 KB
- @openzeppelin/contracts/utils/Address.sol8.31 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.4 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- @openzeppelin/contracts/utils/structs/EnumerableSet.sol12.68 KB
- contracts/@galaxis/registries/contracts/CommunityList.sol1.49 KB
- contracts/@galaxis/registries/contracts/CommunityRegistry.sol6.58 KB
- contracts/@galaxis/registries/contracts/IRegistry.sol1.17 KB
- contracts/@galaxis/registries/contracts/UsesGalaxisRegistry.sol298 B
- contracts/@galaxis/registries/contracts/Versionable/IGenericVersionable.sol435 B
- contracts/@galaxis/registries/contracts/Versionable/IVersionable.sol344 B
- contracts/CardWallet/ICardWalletGenericBalanceConsumer.sol289 B
- contracts/Community/CommunityTokensRegistry.sol4.45 KB
- contracts/Community/ICommunityTokensRegistry.sol274 B
- contracts/SubscriptionCardWallet/TokenTransferSecurity.sol3.62 KB
- contracts/SubscriptionCardWallet/TokenTransferSecurityCentre.sol8.16 KB
- contracts/SubscriptionDeposit/DateTime.sol14.55 KB
- contracts/SubscriptionDeposit/MembershipLevel.sol5.97 KB
- contracts/SubscriptionDeposit/RoyaltySplitterOverride.sol2.26 KB
contracts/SubscriptionCardWallet/SubscriptionCardWallet.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "../@galaxis/registries/contracts/Versionable/IVersionable.sol";
import "../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";
import "../@galaxis/registries/contracts/CommunityList.sol";
import "../@galaxis/registries/contracts/CommunityRegistry.sol";
import {TokenRecord,CommunityTokensRegistry} from "../Community/CommunityTokensRegistry.sol";
import "../SubscriptionDeposit/DateTime.sol";
import {MembershipLevel} from "../SubscriptionDeposit/MembershipLevel.sol";
import "../CardWallet/ICardWalletGenericBalanceConsumer.sol";
import "../SubscriptionDeposit/RoyaltySplitterOverride.sol";
import "./TokenTransferSecurity.sol";
struct SubscriptionRecord {
uint256 updatedTo;
uint256 lastBalance;
uint256 periodCost;
uint256 membershipTierId;
bool annual;
bool enabled;
}
struct SubscriptionInfo {
uint256 projectedExpiryDate;
uint256 currentPeriodEnds;
uint256 currentBalance;
SubscriptionRecord storedData;
}
interface IERC721S {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
/**
* @title SubscriptionCardWallet
* @author galaxis.xyz
* @notice This contract serves as a CardWallet and SubscriptionCardWallet for a given community.
*/
contract SubscriptionCardWallet is IVersionable, UsesGalaxisRegistry, TokenTransferSecurity {
using DateTime for uint256;
using Strings for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
// Used to store subscription and token balance information for each membership card
mapping(uint256 => SubscriptionRecord) public subscriptions;
// ID of the community this SubscriptionCardWallet belongs to
uint32 public thisCommunityId;
// CommunityRegistry for this community
CommunityRegistry public thisCommunityRegistry;
// The token this SubscriptionCardWallet works with
IERC20 public paymentToken;
// Name of the payment token
bytes32 public paymentTokenName;
// The currency ID used to identify the payment token
// 0 - stable, 1 - galaxis, 2 - custom token
uint256 public currencyId;
// Address that will receive revenue from this contract
address public paymentAddress;
// The membership card contract used for this SubscriptionCardWallet
IERC721S public membershipCard;
// Indicates which membership level contract to look for
string public MembershipContractKey;
// Enumerable set to store subscriptions in the order they were created
EnumerableSet.UintSet private subscriptionOrder;
/////////////////////
/// EVENTS
/////////////////////
event SubscriptionStarted(
uint256 membershipCardId,
uint256 membershipTierId,
bool annual
);
event SubscriptionCancelled(
uint256 membershipCardId
);
event FundsAdded(
uint256 membershipCardId,
uint256 amount,
uint256 newBalance
);
event FundsWithdrawn(
uint256 membershipCardId,
uint256 amount,
uint256 newBalance
);
event FundsClaimed(
uint256 paymentReceiverAmount,
uint256 royaltyAmount
);
/////////////////////
// MODIFERS
/////////////////////
modifier onlyCardOwner(uint256 _cardId) {
require(msg.sender == membershipCard.ownerOf(_cardId),"SubscriptionCardWallet: You do not own this card");
_;
}
// Version of the contract
function version() public pure virtual returns (uint256) {
return 2025053101;
}
/**
*
* @param _galaxisRegistry Galaxis registry address
* @param _communityId Id of community this SubscriptionCardWallet belongs to
* @param _currencyId Used to identify the payment token, 0 - stable, 1 - galaxis, 2 - custom token
* @param _paymentAddress Address that will receive revenue from this contract
*/
constructor(
address _galaxisRegistry,
uint32 _communityId,
uint256 _currencyId,
address _paymentAddress
) UsesGalaxisRegistry(_galaxisRegistry) TokenTransferSecurity(_galaxisRegistry, _communityId){
if (_communityId == 0) return; // for goldens
// Validate the currency id provided
TokenRecord[] memory tr = CommunityTokensRegistry(
galaxisRegistry.getRegistryAddress("COMMUNITY_TOKEN_REGISTRY")
).getPaymentTokens(_communityId);
require(_currencyId < tr.length, "SubscriptionCardWallet: Invalid currency ID");
currencyId = _currencyId;
// Set up community registry
thisCommunityId = _communityId;
CommunityList communityList = CommunityList(galaxisRegistry.getRegistryAddress("COMMUNITY_LIST"));
(, address crAddr, ) = communityList.communities(_communityId);
require(crAddr != address(0), "SubscriptionCardWallet: Invalid community ID");
thisCommunityRegistry = CommunityRegistry( crAddr );
// Set up payment token
require(tr[_currencyId]._address != address(0), "SubscriptionCardWallet: Payment token missing");
paymentToken = IERC20(tr[_currencyId]._address);
paymentTokenName = tr[_currencyId]._name;
// Set up membership card contract
address membershipAddress = CommunityRegistry( crAddr ).getRegistryAddress("TOKEN_1");
require(membershipAddress != address(0), "SubscriptionCardWallet: Membership collection missing");
membershipCard = IERC721S(membershipAddress);
// Set up payment receiver
paymentAddress = _paymentAddress;
// Set membership contract key
if (_currencyId == 0) {
MembershipContractKey = "MEMBERSHIP_LEVELS_STABLE";
} else if (_currencyId == 1) {
MembershipContractKey = "MEMBERSHIP_LEVELS_GALAXIS";
} else if (_currencyId == 2) {
MembershipContractKey = "MEMBERSHIP_LEVELS_CUSTOM_TOKEN";
}
}
/**
* @notice Allows the owner of a membership card to top up their card with funds.
* @dev This assumes that the owner has already approved this contract to spend the specified amount of the payment token.
* @param membershipCardId The ID of the membership card.
* @param amount The amount of funds to add.
*/
function addFunds(
uint256 membershipCardId,
uint256 amount
) external onlyCardOwner(membershipCardId) {
paymentToken.safeTransferFrom(msg.sender,address(this),amount);
_addFunds(membershipCardId,amount);
}
/**
* @notice Internal function to add funds to a membership card.
* @dev This function updates the subscription record for the given membership card ID.
* @param membershipCardId The ID of the membership card.
* @param amount The amount of funds to add.
*/
function _addFunds(uint256 membershipCardId, uint256 amount) internal {
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCardId);
sendTokensHome(owing);
subRec.lastBalance = amount + balance;
setLastTxTime();
emit FundsAdded(membershipCardId, amount, subRec.lastBalance);
}
/**
* @notice Starts a subscription for a membership card.
* @param membershipCardId The ID of the membership card.
* @param membershipTierId The ID of the membership tier.
* @param annual true if the subscription should be paid annualy, false if it is monthly.
* @dev Immediately takes the payment for the first period(month or year)
*/
function startSubscription(
uint256 membershipCardId,
uint256 membershipTierId,
bool annual
) external onlyCardOwner(membershipCardId){
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoForUpdate(membershipCardId);
sendTokensHome(owing);
// Set up membership related information
address MembershipLevelContractAddress = thisCommunityRegistry.getRegistryAddress(MembershipContractKey);
require(MembershipLevelContractAddress != address(0),string.concat("SubscriptionCardWallet: Membership level contract not found : ", MembershipContractKey));
MembershipLevel MembershipLevelContract = MembershipLevel(MembershipLevelContractAddress);
subRec.annual = annual;
subRec.membershipTierId = membershipTierId;
if (annual) {
subRec.periodCost = MembershipLevelContract.getMembershipAmountTwelve(membershipTierId);
subRec.updatedTo = getTimeStamp().addYears(1);
}else {
subRec.periodCost = MembershipLevelContract.getMembershipAmountOne(membershipTierId);
subRec.updatedTo = getTimeStamp().addMonths(1);
}
// Makes sure first period can be baid
require(balance >= subRec.periodCost,"SubscriptionCardWallet: Insufficient funds to start subscription");
// Take payment for first period and activate subscription
subRec.lastBalance = balance - subRec.periodCost;
subRec.enabled = true;
sendTokensHome(subRec.periodCost);
subscriptionOrder.add(membershipCardId);
setLastTxTime();
emit SubscriptionStarted(membershipCardId, membershipTierId, annual);
}
/**
* @notice Sends tokens to the payment receiver and the royalty receiver
* @param amountToCollect The amount of tokens to collect and send.
* @dev This function splits the collected funds between the owner and the royalty receiver.
* @dev It uses the RoyaltySplitterOverride contract to get the split configuration.
*/
function sendTokensHome(uint256 amountToCollect) internal {
// Ignore if there is nothing to collect
if (amountToCollect == 0) return;
// Royalty splitting
RoyaltySplitterOverride SplitterConfigAddress = RoyaltySplitterOverride(galaxisRegistry.getRegistryAddress("GLOBAL_SUBSCRIPTION_SPLITTER_CONFIG"));
(uint256 millis, address receiverAddress) = SplitterConfigAddress.getSplitConfig(thisCommunityId);
// Calculate amounts to transfer
// millis = 100 means 1% royalty, millis = 10000 means 100% royalty
uint256 royaltyAmount = amountToCollect * millis / 10000;
uint256 ownerAmount = amountToCollect - royaltyAmount;
// transfer to owner
paymentToken.safeTransfer( paymentAddress, ownerAmount);
// transfer to royalty receiver
paymentToken.safeTransfer( receiverAddress, royaltyAmount);
emit FundsClaimed(ownerAmount, royaltyAmount);
}
/**
* @notice Allows the payment receiver to claim owed funds from a membership card.
* @param membershipCardId The ID of the membership card.
* @dev This function can only be called by the paymentAddress.
*/
function claimFunds(uint256 membershipCardId) external {
require(msg.sender == paymentAddress,"SubscriptionCardWallet: unauthorised");
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCardId);
sendTokensHome(owing);
subRec.lastBalance = balance;
setLastTxTime();
}
/**
* @notice Allows the payment receiver to bulk claim funds from multiple membership cards.
* @param membershipCards An array of membership card IDs.
* @dev This function can only be called by the paymentAddress.
*/
function bulkClaimFunds(uint256[] calldata membershipCards) external {
require(msg.sender == paymentAddress,"SubscriptionCardWallet: unauthorised");
uint256 totalOwing;
// Calculate the total claimable funds from the given membership cards
for (uint256 j = 0; j < membershipCards.length; j++) {
SubscriptionRecord storage subRec = subscriptions[membershipCards[j]];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCards[j]);
totalOwing += owing;
subRec.lastBalance = balance;
}
// Send the total amount in one transfer
sendTokensHome(totalOwing);
setLastTxTime();
}
/**
* @notice Cancels the subscription for a membership card.
* @param membershipCardId The ID of the membership card.
* @dev This function can only be called by the owner of the membership card.
* @dev The cancelled subscriptions will still be actived for the period they were paid for.
*/
function cancelSubscription(uint256 membershipCardId) external onlyCardOwner(membershipCardId) {
_disableSubscriptionFor(membershipCardId);
}
/**
* @notice Allows the payment receiver to bulk cancel subscriptions for multiple membership cards.
* @param membershipCardIds An array of membership card IDs.
* @dev The cancelled subscriptions will still be actived for the period they were paid for.
*/
function ownerBulkCancel(uint256[] calldata membershipCardIds) public {
require(msg.sender==paymentAddress,"SubscriptionCardWallet: unauthorised");
for(uint256 i = 0; i < membershipCardIds.length; i++) {
_disableSubscriptionFor(membershipCardIds[i]);
}
}
/**
* @notice Internal function to disable the subscription for a membership card.
* @param membershipCardId The ID of the membership card.
* @dev Updates the subscription record
*/
function _disableSubscriptionFor(uint256 membershipCardId) internal {
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCardId);
sendTokensHome(owing);
// Disable the subscription and update balance
subRec.enabled = false;
subRec.lastBalance = balance;
emit SubscriptionCancelled(membershipCardId);
}
/**
* @notice Allows the owner of a membership card to withdraw funds from their card.
* @param membershipCardId The ID of the membership card.
* @param amount The amount of funds to withdraw.
* @dev This function can only be called by the owner of the membership card.
*/
function withdrawFunds(uint256 membershipCardId, uint256 amount) external onlyCardOwner(membershipCardId) {
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCardId);
require(balance >= amount, "SubscriptionCardWallet: insufficient balance");
sendTokensHome(owing);
// Update balance and transfer funds
subRec.lastBalance = balance - amount;
paymentToken.safeTransfer(msg.sender,amount);
emit FundsWithdrawn(membershipCardId, amount, subRec.lastBalance);
}
/**
* @notice Allows the transfer of funds from one SubscriptionCardWallet to another.
* @param membershipCardId The ID of the membership card.
* @param destinationCardId The ID of the destination membership card.
* @param amount The amount of funds to transfer.
*/
function payToCard(uint256 membershipCardId, uint256 destinationCardId, uint256 amount) external onlyCardOwner(membershipCardId) {
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,) = _balanceInfoWithUpdate(membershipCardId);
require(balance >= amount, "SubscriptionCardWallet: insufficient balance");
// Checks if the destination card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRecD = subscriptions[destinationCardId];
(,uint256 owingD,) = _balanceInfoWithUpdate(destinationCardId);
sendTokensHome(owing+owingD);
RoyaltySplitterOverride SplitterConfigAddress = RoyaltySplitterOverride(galaxisRegistry.getRegistryAddress("GLOBAL_SUBSCRIPTION_SPLITTER_CONFIG"));
(uint256 millis, address receiverAddress) = SplitterConfigAddress.getSplitConfig(thisCommunityId);
// Calculate amounts to transfer
// millis = 100 means 1% royalty, millis = 10000 means 100% royalty
uint256 royaltyAmount = amount * millis / 10000;
uint256 ownerAmount = amount - royaltyAmount;
// update blances
subRec.lastBalance -= amount;
subRecD.lastBalance += ownerAmount;
// transfer to royalty receiver
paymentToken.safeTransfer( receiverAddress, royaltyAmount);
}
/**
* @notice Updates and returns the balance information for a given membership card.
* @param cardId The ID of the membership card.
* @return balance The available balance for the membership card.
* @return owing The amount of funds that are owed by the membership card.
* @return updateableDate The date when the subscription will end.
* @dev Uses _balanceInfoForUpdate to get the balance information and updates the subscription record.
* @dev It also cancel the subscription if it has expired.
*/
function _balanceInfoWithUpdate(uint256 cardId) internal returns (uint256 balance, uint256 owing, uint256 updateableDate) {
SubscriptionRecord storage subRec = subscriptions[cardId];
( balance, owing, updateableDate) = _balanceInfoForUpdate(cardId);
if (updateableDate < getTimeStamp()) {
subRec.updatedTo = getTimeStamp();
// subscription has expired
subRec.enabled = false;
} else {
subRec.updatedTo = updateableDate;
}
return (balance,owing,updateableDate);
}
// To allow time based testing with TestSubscriptionCardWallet
function setLastTxTime() virtual internal {}
/////////////////////
// CARD WALLET FEATURES
/////////////////////
/**
* @param membershipCardId The ID of the membership card.
* @param _tokenAddress The address of the token to take.
* @param _amount The amount of tokens to take.
* @param _userData Additional user data, should contain the community ID in bytes32 format.
* @dev Every contract that wants to intereact with SubcriptionEngine needs to impmenet ICardWalletGenericBalanceConsumer interface.
* @dev This function will transfer the funds to this contract and add them to the membership card balance of a given community card.
*/
function takeMyTokens(
uint256 membershipCardId,
address _tokenAddress,
uint256 _amount,
bytes calldata _userData
) external approvedSpender(msg.sender) {
require(_tokenAddress == address(paymentToken),"SubscriptionCardWallet: Invalid ERC20 transfer");
require(_getOwnerOfCard(membershipCardId) != address(0),"SubscriptionCardWallet: invalid card ID");
require(_userData.length == 32,"SubscriptionCardWallet : Invalid data length");
uint32 requestedCommunity = uint32(uint256(bytes32(_userData[0:32])));
require(requestedCommunity == thisCommunityId,"SubscriptionCardWallet: Invalid requested community");
// Contract takes tokens from msg.sender and adds them to the membership card balance
paymentToken.safeTransferFrom( msg.sender, address(this), _amount);
_addFunds(membershipCardId,_amount);
}
/**
* @param membershipCardId The ID of the membership card.
* @param destination The address of the destination contract.
* @param amount The amount of funds to approve for transfer.
* @param userData Additional user data to be passed to the destination contract.
* @dev This function can only be called by the owner of the membership card.
* @dev The destination contract must implement ICardWalletGenericBalanceConsumer interface.
* @dev This function allows the user to spend funds from their MembershipCard on apporved destination contracts.
* @dev The approved addresses can be set by community managers
*/
function approveAndCall(
uint256 membershipCardId,
address destination,
uint256 amount,
bytes calldata userData
) public onlyCardOwner(membershipCardId) approvedBuyer(destination) {
// Checks if the card is left behind with payments and takes tokens accordingly
SubscriptionRecord storage subRec = subscriptions[membershipCardId];
(uint256 balance, uint256 owing,uint256 updateableDate) = _balanceInfoForUpdate(membershipCardId);
sendTokensHome(owing);
require(balance >= amount, "SubscriptionCardWallet: Insufficent funds");
// Update subscription status
if (updateableDate < getTimeStamp()) {
subRec.updatedTo = getTimeStamp();
subRec.enabled = false;
// subscription has expired
} else {
subRec.updatedTo = updateableDate;
}
subRec.lastBalance = balance - amount;
setLastTxTime();
// allow destination to transfer balance from this contract
paymentToken.safeApprove(destination, amount);
// THEN tell destination to take it
// and then do something for it.
ICardWalletGenericBalanceConsumer(destination).takeMyTokens(
membershipCardId,
address(paymentToken),
amount,
userData
);
require( paymentToken.allowance(address(this), destination) == 0 ,"SubscriptionCardWallet: funds not taken") ;
}
/////////////////////
// VIEW FUNCTIONS
/////////////////////
/**
* @notice Returns the available balance for a given membership card.
* @param cardId The ID of the membership card.
* @return balance The available balance for the membership card.
* @dev The balance of a membership card is the amount of funds that can be used by the owner of the card
* @dev If a membership card has an active subscription, the balance available to the card owner
* is calculated based on the lastBalance and the cost of the unprocessed periods.
*/
function availableBalance(uint256 cardId) external view returns (uint256 balance) {
(balance,,) = _balanceInfoForUpdate(cardId);
}
/**
* @notice Checks if a subscription is active for a given membership card.
* @param cardId The ID of the membership card.
* @return bool indicating whether the subscription is active or not
* @dev A subscription is considered active if updateableDate is in the future
*/
function isSubscriptionActive(uint256 cardId) external view returns (bool) {
(,,uint256 updateableDate) = _balanceInfoForUpdate(cardId);
return (updateableDate > getTimeStamp());
}
/**
* @notice Returns the amount of funds that can be claimed from a membership card.
* @param cardId The ID of the membership card.
* @return owing The amount of funds that can be claimed.
* @dev This function calculates the amount of funds that can be claimed based on the subscription record
* @dev It returns the amount of funds that are owed by the membership card
*/
function fundsClaimable(uint256 cardId) external view returns (uint256 owing) {
(,owing,) = _balanceInfoForUpdate(cardId);
}
/**
* @notice Returns the balance information for a given membership card.
* @param cardId The ID of the membership card.
* @return balance The available balance for the membership card.
* @return owing The amount of funds that are owed by the membership card.
* @return updateableDate The date when the subscription will end.
* @dev Calculates the balance, owing amount, and updateable date for a given membership card.
* @dev If a membership card has an active subscription, the balance available to the card owner
* is calculated based on the lastBalance and the cost of the unprocessed periods.
*
*/
function _balanceInfoForUpdate(uint256 cardId) internal view returns (uint256 balance, uint256 owing, uint256 updateableDate) {
SubscriptionRecord memory rec = subscriptions[cardId];
// If the updateTo is in the future, no calcualtions are needed, up until that date all payments are settled
if (rec.updatedTo > getTimeStamp()) return (rec.lastBalance,0,rec.updatedTo);
// If the subscription is not active no calculations needed, all payments are settled
if (!rec.enabled) return (rec.lastBalance,0,getTimeStamp());
// Calculate how many periods have passed since the last update
uint256 periodsSinceUpdated;
if (rec.annual) {
periodsSinceUpdated = rec.updatedTo.diffYears(getTimeStamp()) + 1;
} else{
periodsSinceUpdated = rec.updatedTo.diffMonths(getTimeStamp() ) + 1;
}
// Check if more periods passed than can be paid for
// The funds owed will only be calculated until the point where the balance was able to cover the full cost of a subscription
// Any leftower will remain on the card and can be used for future payments
if (periodsSinceUpdated * rec.periodCost > rec.lastBalance) {
// Not enough funds to cover everything
uint256 paidPeriods = rec.lastBalance / rec.periodCost;
if (rec.annual) {
updateableDate = rec.updatedTo.addYears(paidPeriods);
} else {
updateableDate = rec.updatedTo.addMonths(paidPeriods );
}
owing = paidPeriods * rec.periodCost;
balance = rec.lastBalance - owing;
return (balance,owing,updateableDate);
}
// If there are enough funds to cover all the periods, calculate the balance and owing amount
owing = periodsSinceUpdated * rec.periodCost;
balance = rec.lastBalance - owing;
if (rec.annual) {
updateableDate = rec.updatedTo.addYears(periodsSinceUpdated);
} else{
updateableDate = rec.updatedTo.addMonths(periodsSinceUpdated );
}
return (balance,owing,updateableDate);
}
/**
* @notice Returns the current timestamp.
* @return uint256 The current block timestamp.
* @dev This function is used to get the current time in seconds since the Unix epoch based on the current block.
*/
function getTimeStamp() public view virtual returns (uint256) {
return block.timestamp;
}
/**
* @notice Returns the owner of a given card ID.
* @param cardId The ID of the card.
* @return address The address of the owner of the card.
*/
function _getOwnerOfCard(uint256 cardId) internal view returns (address){
return IERC721S(thisCommunityRegistry.getRegistryAddress("TOKEN_1")).ownerOf(cardId);
}
/**
* @notice Returns the number of currently active subscriptions
* @dev This number might be greater than the actualy number of subscriptions
* @dev It includes subscriptions that dont have enough funds remaining to pay for the current period but are not interacted with.
* @dev The above mentioned subscription will be removed on the next interaction with the card.
*/
function getSubscriptionRecordsLength() public view returns (uint256) {
return subscriptionOrder.length();
}
/**
* @notice Returns the subscription record for the given card IDs.
* @param recordIds The IDs of the membership cards.
* @return SubscriptionRecord array containing the subscription records for the given card IDs.
*/
function getSubscriptionRecordsFor(uint256[] memory recordIds) external view returns(SubscriptionInfo[] memory) {
uint256 limit = recordIds.length;
SubscriptionInfo[] memory results = new SubscriptionInfo[](limit);
for(uint256 i = 0; i < limit; i++) {
results[i].storedData = subscriptions[recordIds[i]];
(
results[i].currentBalance,
, // uint256 owing
results[i].currentPeriodEnds
) = _balanceInfoForUpdate(recordIds[i]);
if (
(results[i].currentPeriodEnds > getTimeStamp()) && results[i].storedData.enabled
) {
uint256 periods = results[i].currentBalance / results[i].storedData.periodCost;
results[i].projectedExpiryDate = results[i].storedData.annual ?
results[i].currentPeriodEnds.addYears(periods) :
results[i].currentPeriodEnds.addMonths(periods);
}
}
return results;
}
/**
* @notice Returns the card IDs from a given index range from subscriptionOrder
* @param start The starting index for the records.
* @param limit The maximum number of records to return.
* @return uint256 array containing card IDs
*/
function getSubscriptionRecordIds(uint256 start, uint256 limit) public view returns (uint256[] memory) {
uint256 max = subscriptionOrder.length();
uint256 end = start+limit;
if(end >= max) {
end = max;
}
uint256[] memory records = new uint[](end-start);
uint256 y = 0;
for(uint256 i = start; i < end; i++) {
records[y] = subscriptionOrder.at(i);
y++;
}
return records;
}
/**
* @notice Returns all active subscription ids for the community.
* @return SubscriptionInfo array containing all active subscription ids
* @dev This function might fail if there are too many subscription ids.
*/
function getActiveSubscriptionIds() external view returns (uint256[] memory) {
uint256 limit = subscriptionOrder.length();
uint256[] memory tempResults = new uint256[](limit);
uint256 y = 0;
for (uint256 i = 0; i < limit; i++) {
(, , uint256 currentPeriodEnds) = _balanceInfoForUpdate(subscriptionOrder.at(i));
if (currentPeriodEnds > getTimeStamp()) {
tempResults[y] = subscriptionOrder.at(i);
y++;
}
}
uint256[] memory results = new uint256[](y);
for (uint256 i = 0; i < y; i++) {
results[i] = tempResults[i];
}
return results;
}
}@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
@openzeppelin/contracts/access/AccessControlEnumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@openzeppelin/contracts/access/IAccessControlEnumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@openzeppelin/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @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.
*
* ```
* 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 of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @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._indexes[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 read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 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 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[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._indexes[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) {
return _values(set._inner);
}
// 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 on 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;
}
}
contracts/@galaxis/registries/contracts/CommunityList.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "./Versionable/IVersionable.sol";
contract CommunityList is AccessControlEnumerable, IVersionable {
function version() external pure returns (uint256) {
return 2024040301;
}
bytes32 public constant CONTRACT_ADMIN = keccak256("CONTRACT_ADMIN");
uint256 public numberOfEntries;
struct community_entry {
string name;
address registry;
uint32 id;
}
mapping(uint32 => community_entry) public communities; // community_id => record
mapping(uint256 => uint32) public index; // entryNumber => community_id for enumeration
event CommunityAdded(uint256 pos, string community_name, address community_registry, uint32 community_id);
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CONTRACT_ADMIN,msg.sender);
}
function addCommunity(uint32 community_id, string memory community_name, address community_registry) external onlyRole(CONTRACT_ADMIN) {
uint256 pos = numberOfEntries++;
index[pos] = community_id;
communities[community_id] = community_entry(community_name, community_registry, community_id);
emit CommunityAdded(pos, community_name, community_registry, community_id);
}
}contracts/@galaxis/registries/contracts/CommunityRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Versionable/IVersionable.sol";
import "./UsesGalaxisRegistry.sol";
contract CommunityRegistry is AccessControlEnumerable, UsesGalaxisRegistry, IVersionable {
function version() virtual external pure returns(uint256) {
return 2024040401;
}
bytes32 public constant COMMUNITY_REGISTRY_ADMIN = keccak256("COMMUNITY_REGISTRY_ADMIN");
uint32 public community_id;
string public community_name;
mapping(bytes32 => address) addresses;
mapping(bytes32 => uint256) uints;
mapping(bytes32 => bool) booleans;
mapping(bytes32 => string) strings;
mapping (uint => string) public addressEntries;
mapping (uint => string) public uintEntries;
mapping (uint => string) public boolEntries;
mapping (uint => string) public stringEntries;
uint public numberOfAddresses;
uint public numberOfUINTs;
uint public numberOfBooleans;
uint public numberOfStrings;
bool initialised;
bool public independant;
event IndependanceDay(bool gain_independance);
modifier onlyAdmin() {
require(
isUserCommunityAdmin(COMMUNITY_REGISTRY_ADMIN,msg.sender)
,"CommunityRegistry : Unauthorised");
_;
}
modifier onlyPropertyAdmin() {
require(
isUserCommunityAdmin(COMMUNITY_REGISTRY_ADMIN,msg.sender) ||
hasRole(COMMUNITY_REGISTRY_ADMIN,msg.sender)
,"CommunityRegistry : Unauthorised");
_;
}
function isUserCommunityAdmin(bytes32 role, address user) public view returns (bool) {
if (hasRole(DEFAULT_ADMIN_ROLE,user) ) return true; // community_admin can do anything
if (independant){
return(
hasRole(role,user)
);
} else { // for Factories
return(roleManager().hasRole(role,user));
}
}
function roleManager() internal view returns (IAccessControlEnumerable) {
address addr = galaxisRegistry.getRegistryAddress("ROLE_MANAGER"); // universal
if (addr != address(0)) return IAccessControlEnumerable(addr);
addr = galaxisRegistry.getRegistryAddress("MAINNET_CHAIN_IMPLEMENTER"); // mainnet
if (addr != address(0)) return IAccessControlEnumerable(addr);
addr = galaxisRegistry.getRegistryAddress("L2_RECEIVER"); // mainnet
require(addr != address(0),"CommunityRegistry : no higher authority found");
return IAccessControlEnumerable(addr);
}
function grantRole(bytes32 key, address user) public override(AccessControl,IAccessControl) onlyAdmin {
_grantRole(key,user); // need to be able to grant it
}
constructor (
address _galaxisRegistry,
uint32 _community_id,
address _community_admin,
string memory _community_name
) UsesGalaxisRegistry(_galaxisRegistry){
_init(_community_id,_community_admin,_community_name);
}
function init(
uint32 _community_id,
address _community_admin,
string memory _community_name
) external {
_init(_community_id,_community_admin,_community_name);
}
function _init(
uint32 _community_id,
address _community_admin,
string memory _community_name
) internal {
require(!initialised,"This can only be called once");
initialised = true;
community_id = _community_id;
community_name = _community_name;
_setupRole(DEFAULT_ADMIN_ROLE, _community_admin); // default admin = launchpad
}
event AdminUpdated(address user, bool isAdmin);
event AppAdminChanged(address app,address user,bool state);
//===
event AddressChanged(string key, address value);
event UintChanged(string key, uint256 value);
event BooleanChanged(string key, bool value);
event StringChanged(string key, string value);
function setIndependant(bool gain_independance) external onlyAdmin {
if (independant != gain_independance) {
independant = gain_independance;
emit IndependanceDay(gain_independance);
}
}
function setAdmin(address user,bool status ) external onlyAdmin {
if (status)
_grantRole(COMMUNITY_REGISTRY_ADMIN,user);
else
_revokeRole(COMMUNITY_REGISTRY_ADMIN,user);
}
function hash(string memory field) internal pure returns (bytes32) {
return keccak256(abi.encode(field));
}
function setRegistryAddress(string memory fn, address value) external onlyPropertyAdmin {
bytes32 hf = hash(fn);
addresses[hf] = value;
addressEntries[numberOfAddresses++] = fn;
emit AddressChanged(fn,value);
}
function setRegistryBool(string memory fn, bool value) external onlyPropertyAdmin {
bytes32 hf = hash(fn);
booleans[hf] = value;
boolEntries[numberOfBooleans++] = fn;
emit BooleanChanged(fn,value);
}
function setRegistryString(string memory fn, string memory value) external onlyPropertyAdmin {
bytes32 hf = hash(fn);
strings[hf] = value;
stringEntries[numberOfStrings++] = fn;
emit StringChanged(fn,value);
}
function setRegistryUINT(string memory fn, uint value) external onlyPropertyAdmin {
bytes32 hf = hash(fn);
uints[hf] = value;
uintEntries[numberOfUINTs++] = fn;
emit UintChanged(fn,value);
}
function getRegistryAddress(string memory key) external view returns (address) {
return addresses[hash(key)];
}
function getRegistryBool(string memory key) external view returns (bool) {
return booleans[hash(key)];
}
function getRegistryUINT(string memory key) external view returns (uint256) {
return uints[hash(key)];
}
function getRegistryString(string memory key) external view returns (string memory) {
return strings[hash(key)];
}
}contracts/@galaxis/registries/contracts/IRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;
interface IRegistry {
function setRegistryAddress(string memory fn, address value) external ;
function setRegistryBool(string memory fn, bool value) external ;
function setRegistryUINT(string memory key) external returns (uint256) ;
function setRegistryString(string memory fn, string memory value) external ;
function setAdmin(address user,bool status ) external;
function setAppAdmin(address app, address user, bool state) external;
function getRegistryAddress(string memory key) external view returns (address) ;
function getRegistryBool(string memory key) external view returns (bool);
function getRegistryUINT(string memory key) external view returns (uint256) ;
function getRegistryString(string memory key) external view returns (string memory) ;
function isAdmin(address user) external view returns (bool) ;
function isAppAdmin(address app, address user) external view returns (bool);
function numberOfAddresses() external view returns(uint256);
function addressEntries(uint256) external view returns(string memory);
}contracts/@galaxis/registries/contracts/UsesGalaxisRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.25;
import "./IRegistry.sol";
contract UsesGalaxisRegistry {
IRegistry immutable public galaxisRegistry;
constructor(address _galaxisRegistry) {
galaxisRegistry = IRegistry(_galaxisRegistry);
}
}contracts/@galaxis/registries/contracts/Versionable/IGenericVersionable.sol
//SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.25;
import "./IVersionable.sol";
/**
* @title IGenericVersionable
* @dev Interface for generic versionable contracts extending IVersionable.
*/
interface IGenericVersionable is IVersionable {
/**
* @notice Get the base version of the contract.
* @return The base version.
*/
function baseVersion() external pure returns (uint256);
}
contracts/@galaxis/registries/contracts/Versionable/IVersionable.sol
//SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.25;
/**
* @title IVersionable
* @dev Interface for versionable contracts.
*/
interface IVersionable {
/**
* @notice Get the current version of the contract.
* @return The current version.
*/
function version() external pure returns (uint256);
}
contracts/CardWallet/ICardWalletGenericBalanceConsumer.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
interface ICardWalletGenericBalanceConsumer {
function takeMyTokens(
uint256 membershipCardId,
address _tokenAddress,
uint256 _amount,
bytes calldata _userData
) external;
}
contracts/Community/CommunityTokensRegistry.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";
import "../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";
import "../@galaxis/registries/contracts/CommunityList.sol";
import "../@galaxis/registries/contracts/CommunityRegistry.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./ICommunityTokensRegistry.sol";
contract CommunityTokensRegistry is AccessControlEnumerable, IGenericVersionable, UsesGalaxisRegistry {
using SafeERC20 for IERC20;
mapping(uint256 => TokenRecord) public TokenRecords;
IERC20 public paymentToken;
uint256 public accessFee;
address public paymentReceiver;
address communityListAddress;
function baseVersion() public pure virtual returns (uint256) {
return 2025040101;
}
function version() public pure virtual returns (uint256) {
return 2025040101;
}
event CommunityTokenUpdated(uint32 communityId);
constructor(
address _galaxisRegistry,
address _adminSafe,
uint256 _accessFee,
address _paymentReceiver
) UsesGalaxisRegistry(_galaxisRegistry) {
paymentToken = IERC20(IRegistry(_galaxisRegistry).getRegistryAddress("GALAXIS_TOKEN"));
accessFee = _accessFee;
paymentReceiver = _paymentReceiver;
communityListAddress = IRegistry(_galaxisRegistry).getRegistryAddress("COMMUNITY_LIST");
_setupRole(DEFAULT_ADMIN_ROLE, _adminSafe);
}
function payAccessFee(
uint32 _communityId,
bytes32 _name,
address _address
) public {
TokenRecord storage thisCommunityRecords = TokenRecords[_communityId];
require(thisCommunityRecords._address == address(0), "CommunityTokensRegistry - Community already paid access fee");
require(isCommunityAdmin(msg.sender, _communityId), "CommunityTokensRegistry - Only community admins can pay access fee");
thisCommunityRecords._name = _name;
thisCommunityRecords._address = _address;
emit CommunityTokenUpdated(_communityId);
paymentToken.safeTransferFrom(msg.sender, paymentReceiver, accessFee);
}
function getPaymentTokens(uint32 communityId) public view returns (TokenRecord[] memory) {
TokenRecord[] memory results = new TokenRecord[](3);
results[0]._address = galaxisRegistry.getRegistryAddress("SUBSCRIPTION_PAYMENT_TOKEN");
results[0]._name = bytes32(bytes( ERC20(results[0]._address).symbol() ));
results[1]._address = galaxisRegistry.getRegistryAddress("GALAXIS_TOKEN");
results[1]._name = "Galaxis";
results[2]._address = TokenRecords[communityId]._address;
results[2]._name = TokenRecords[communityId]._name;
return results;
}
/// ADMIN FUNCTIONS
function setAccessFee(uint256 _accessFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
accessFee = _accessFee;
}
function setPaymentReceiver(address _paymentReceiver) external onlyRole(DEFAULT_ADMIN_ROLE) {
paymentReceiver = _paymentReceiver;
}
function setPaymentToken(address _paymentToken) external onlyRole(DEFAULT_ADMIN_ROLE) {
paymentToken = IERC20(_paymentToken);
}
/// @dev only used by galaxis admins in case a user pays the fee and gives the wrong token address
function setForCommunity(
uint32 _communityId,
bytes32 _name,
address _address
) public onlyRole(DEFAULT_ADMIN_ROLE){
TokenRecord storage thisCommunityRecords = TokenRecords[_communityId];
thisCommunityRecords._name = _name;
thisCommunityRecords._address = _address;
emit CommunityTokenUpdated(_communityId);
}
/// HELPER FUNCTIONS
function isCommunityAdmin(address sender, uint32 communityId) internal view returns (bool) {
(,address _communityRegistry,) = CommunityList(communityListAddress).communities(communityId);
CommunityRegistry communityRegistry = CommunityRegistry(_communityRegistry);
return communityRegistry.hasRole(DEFAULT_ADMIN_ROLE, sender);
}
}contracts/Community/ICommunityTokensRegistry.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
struct TokenRecord {
bytes32 _name;
address _address;
}
interface ICommunityTokensRegistry {
function getPaymentTokens(uint32 communityId) external view returns (TokenRecord[] memory);
}contracts/SubscriptionCardWallet/TokenTransferSecurity.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "../@galaxis/registries/contracts/IRegistry.sol";
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";
import "./TokenTransferSecurityCentre.sol";
/**
* @title TokenTransferSecurity
* @author galaxis.xyz
* @notice This contract serves as a security layer to manage and validate
* token transfer destinations for SubscriptionCardWallet contracts.
*/
contract TokenTransferSecurity {
IRegistry private galaxisRegistry;
// Bytes32 representation of roles
bytes32 public constant COMMUNITY_REGISTRY_ADMIN = keccak256("COMMUNITY_REGISTRY_ADMIN");
// Enumerable set of addresses where tokens can be transfered to.
EnumerableSet.AddressSet private validTokenTransfers;
uint32 private communityId;
// Check if tokens can be sent to the destination address - used in approveAndCall
modifier approvedBuyer(address destination) {
require(TSC().isValidBuyer(communityId,destination),"TokenTransferSecurity : destination not allowed to receive tokens");
_;
}
// Check if sender is allowed to send us tokens - used in takeMyTokens
modifier approvedSpender(address destination) {
require(TSC().isValidSpender(communityId,destination),"TokenTransferSecurity : source cannot buy with tokens");
_;
}
constructor(address _galaxisRegistry,uint32 _communityId) {
// Initialize role manager contract
galaxisRegistry = IRegistry(_galaxisRegistry);
communityId = _communityId;
}
function TSC() internal view returns (TokenTransferSecurityCentre) {
return TokenTransferSecurityCentre(galaxisRegistry.getRegistryAddress("TOKEN_SECURITY_CENTRE"));
}
/**
* @notice Gets the number of valid addresses for token transfers.
* @return The number of addresses that are valid for token transfers.
*/
function numberOfValidBuyers() external view returns (uint256) {
return TSC().numberOfValidBuyers(communityId);
}
function numberOfValidSpenders() external view returns (uint256) {
return TSC().numberOfValidSpenders(communityId);
}
/**
* @notice Returns a list of all valid token transfer addresses.
* @return An array of addresses that are valid for token transfers.
*/
function allValidBuyers() external view returns (address[] memory) {
return TSC().allValidBuyers(communityId);
}
function allValidSpenders() external view returns (address[] memory) {
return TSC().allValidSpenders(communityId);
}
/**
* @notice Lists valid token transfer addresses in a paginated manner.
* @param start The starting index for pagination.
* @param count The number of addresses to return.
* @return An array of addresses that are valid for token transfers.
* @dev listTokenTransfers is used if there are too mant token Transfers.
* This is highly unlikely in this application but here for safety
*/
function listValidBuyers(uint256 start, uint256 count) external view returns (address[] memory) {
return TSC().listValidBuyers(communityId,start,count);
}
function listValidSpenders(uint256 start, uint256 count) external view returns (address[] memory) {
return TSC().listValidSpenders(communityId,start,count);
}
}contracts/SubscriptionCardWallet/TokenTransferSecurityCentre.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "../@galaxis/registries/contracts/IRegistry.sol";
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";
/**
* @title TokenTransferSecurityCentre
* @author galaxis.xyz
* @notice This contract serves as a security layer to manage and validate
* token transfer destinations for SubscriptionCardWallet contracts.
*/
contract TokenTransferSecurityCentre {
using EnumerableSet for EnumerableSet.AddressSet;
// Bytes32 representation of roles
bytes32 public constant COMMUNITY_REGISTRY_ADMIN = keccak256("COMMUNITY_REGISTRY_ADMIN");
// Enumerable set of valid spenders and buyers for each community
mapping(uint32 => EnumerableSet.AddressSet) private validSpenders;
mapping(uint32 => EnumerableSet.AddressSet) private validBuyers;
// Role manager interface to check permissions
IAccessControl private roleManager;
////////////////
/// EVENTS
////////////////
event ValidSpenderUpdated(uint32 communityId, address spender, bool enabled);
event ValidBuyerUpdated(uint32 communityId, address spender, bool enabled);
// Checks if the caller is COMMUNITY_REGISTRY_ADMIN
// This means admin of the CommunityRegistry contract, not admin for a given community
modifier approvedTransferSetter() {
require(roleManager.hasRole(COMMUNITY_REGISTRY_ADMIN,msg.sender),"TokenTransferSecurity : unauthorised");
_;
}
// CONSTRUCTOR
constructor(address _galaxisRegistry) {
// Initialize role manager contract
address roleManagerAddress = IRegistry(_galaxisRegistry).getRegistryAddress("ROLE_MANAGER");
require(roleManagerAddress != address(0),"TokenTransferSecurity : ROLE MANAGER not set");
roleManager = IAccessControl(roleManagerAddress);
}
/**
* @notice Adds or removes an address from the list of valid spenders
* @param target The address to be added or removed.
* @param enabled If true, adds the address; if false, removes it.
* @dev This function can only be called by an address with the COMMUNITY_REGISTRY_ADMIN role.
*/
function manageSpendAddress(uint32 _communityId,address target, bool enabled) external approvedTransferSetter {
_manageAddress(validSpenders,_communityId,target,enabled);
emit ValidSpenderUpdated(_communityId, target, enabled);
}
/**
* @notice Adds or removes an address from the list of valid buyers
* @param target The address to be added or removed.
* @param enabled If true, adds the address; if false, removes it.
* @dev This function can only be called by an address with the COMMUNITY_REGISTRY_ADMIN role.
*/
function manageBuyAddress(uint32 _communityId,address target, bool enabled) external approvedTransferSetter {
_manageAddress(validBuyers,_communityId, target,enabled);
emit ValidBuyerUpdated(_communityId, target, enabled);
}
/**
* @notice Helper function to set validSpenders and validBuyers
* @param validTokenTransfers The mapping in which we want to set values
* @param _communityId The community ID for which to manage the address.
* @param target The address to be added or removed.
* @param enabled If true, adds the address; if false, removes it.
*/
function _manageAddress(mapping(uint32 => EnumerableSet.AddressSet) storage validTokenTransfers, uint32 _communityId,address target, bool enabled) internal {
if (enabled)
validTokenTransfers[_communityId].add(target);
else
validTokenTransfers[_communityId].remove(target);
}
/**
* @notice Gets the number of valid spenders
* @return The number of addresses that are valid for token transfers.
*/
function numberOfValidSpenders(uint32 _communityId) external view returns (uint256) {
return validSpenders[_communityId].length();
}
/**
* @notice Gets the number of valid buyers
* @return The number of addresses that are valid for token transfers.
*/
function numberOfValidBuyers(uint32 _communityId) external view returns (uint256) {
return validBuyers[_communityId].length();
}
/**
* @notice Returns a list of all valid token transfer addresses.
* @return An array of addresses that are valid for token transfers.
*/
function allValidBuyers(uint32 _communityId) external view returns(address[] memory) {
return allValidTokenTransfers(validBuyers,_communityId);
}
/**
* @notice Returns a list of all valid spenders.
*/
function allValidSpenders(uint32 _communityId) external view returns(address[] memory) {
return allValidTokenTransfers(validSpenders,_communityId);
}
/**
@notice Helper function to return valid spenders or buyers
*/
function allValidTokenTransfers(mapping(uint32 => EnumerableSet.AddressSet) storage validTokenTransfers, uint32 _communityId) internal view returns (address[] memory) {
return validTokenTransfers[_communityId].values();
}
/**
* @notice Lists valid token transfer addresses in a paginated manner.
* @param start The starting index for pagination.
* @param count The number of addresses to return.
* @return An array of addresses that are valid buyers
* @dev listTokenTransfers is used if there are too many token Transfers.
* This is highly unlikely in this application but here for safety
*/
function listValidBuyers(uint32 _communityId, uint256 start, uint256 count) external view returns (address[] memory) {
return listValidTokenTransfers(validBuyers,_communityId,start,count);
}
/**
* @notice Lists valid spenders in a paginated manner.
* @param start The starting index for pagination.
* @param count The number of addresses to return.
* @return An array of addresses that are valid spenders
* @dev listTokenTransfers is used if there are too many token Transfers.
* This is highly unlikely in this application but here for safety
*/
function listValidSpenders(uint32 _communityId, uint256 start, uint256 count) external view returns (address[] memory) {
return listValidTokenTransfers(validSpenders,_communityId,start,count);
}
/**
* @notice Helper function to list valid token transfers.
* @param validTokenTransfers The mapping of valid token transfers.
* @param _communityId The community ID for which to list valid transfers.
* @param start The starting index for pagination.
* @param count The number of addresses to return.
* @return An array of addresses that are valid token transfers.
*/
function listValidTokenTransfers(mapping(uint32 => EnumerableSet.AddressSet) storage validTokenTransfers, uint32 _communityId, uint256 start, uint256 count) internal view returns (address[] memory) {
uint256 length = validTokenTransfers[_communityId].length();
if (start >= length) {
return new address[](0);
}
if (start + count > length) {
count = length - start;
}
address[] memory results = new address[](count);
for (uint256 j = 0; j < count; j++) {
results[j] = validTokenTransfers[_communityId].at(start + j);
}
return results;
}
// Check if address is a valid spender
function isValidSpender(uint32 _communityId, address _destination) external view returns (bool) {
return validSpenders[_communityId].contains(_destination);
}
// Check if address is a valid buyer
function isValidBuyer(uint32 _communityId, address _destination) external view returns (bool) {
return validBuyers[_communityId].contains(_destination);
}
}contracts/SubscriptionDeposit/DateTime.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ----------------------------------------------------------------------------
// DateTime Library v2.0
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2440588;
uint256 constant DOW_MON = 1;
uint256 constant DOW_TUE = 2;
uint256 constant DOW_WED = 3;
uint256 constant DOW_THU = 4;
uint256 constant DOW_FRI = 5;
uint256 constant DOW_SAT = 6;
uint256 constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4
+ (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12
- (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
int256 __days = int256(_days);
int256 L = __days + 68569 + OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
}
function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
)
internal
pure
returns (uint256 timestamp)
{
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR
+ minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
}
function timestampToDateTime(uint256 timestamp)
internal
pure
returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second)
{
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
}
function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second)
internal
pure
returns (bool valid)
{
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {
(uint256 year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {
(uint256 year, uint256 month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
function getYear(uint256 timestamp) internal pure returns (uint256 year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint256 timestamp) internal pure returns (uint256 month) {
(, month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint256 timestamp) internal pure returns (uint256 day) {
(,, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint256 timestamp) internal pure returns (uint256 hour) {
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {
uint256 secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint256 timestamp) internal pure returns (uint256 second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = ((month - 1) % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = (yearMonth % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear, uint256 fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear, uint256 toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}contracts/SubscriptionDeposit/MembershipLevel.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";
import "../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";
import "../@galaxis/registries/contracts/CommunityList.sol";
import "../@galaxis/registries/contracts/CommunityRegistry.sol";
import "../Community/ICommunityTokensRegistry.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
struct MembershipLevelStoredData {
bytes32 name;
uint256 amountOne;
uint256 amountTwelve;
bytes metadata;
bool isActive;
}
struct MembershipLevelInfo {
uint256 order;
uint256 position;
bytes32 name;
uint256 amountOne;
uint256 amountTwelve;
bytes metadata;
bool isActive;
}
contract MembershipLevel is IGenericVersionable, UsesGalaxisRegistry {
function baseVersion() public pure virtual returns (uint256) {
return 2025040601;
}
function version() public pure virtual returns (uint256) {
return 2025040601;
}
uint256 public communityId;
CommunityRegistry public communityRegistry;
IERC20 public PaymentToken;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
uint256 public lastOrderId = 1;
uint256 public levelCount = 0;
mapping(uint256 => MembershipLevelStoredData) public data;
mapping(uint256 => uint256) public ordering;
event MembershipLevelCreated(uint256 id, bytes32 name, uint256 amountOne, uint256 amountTwelve);
event MembershipLevelUpdated(uint256 id, bytes32 name, uint256 amountOne, uint256 amountTwelve);
event MembershipLevelStatusChanged(uint256 position, bool isActive);
constructor(
address _galaxisRegistry,
uint32 _communityId,
uint8 _paymentTokenId
) UsesGalaxisRegistry(_galaxisRegistry) {
if (_communityId == 0) return; // for deploying goldens
communityId = _communityId;
CommunityList communityList = CommunityList(galaxisRegistry.getRegistryAddress("COMMUNITY_LIST"));
(, address crAddr, ) = communityList.communities(_communityId);
require(crAddr != address(0), "MembershipLevel: Invalid community id");
communityRegistry = CommunityRegistry( crAddr );
ICommunityTokensRegistry ComunityTokenRegistry = ICommunityTokensRegistry(
galaxisRegistry.getRegistryAddress("COMMUNITY_TOKEN_REGISTRY")
);
TokenRecord[] memory PaymentTokenAddresses = ComunityTokenRegistry.getPaymentTokens(_communityId);
PaymentToken = IERC20(PaymentTokenAddresses[_paymentTokenId]._address);
}
function addLevel(
bytes32[] memory name,
uint256[] memory amountOne,
uint256[] memory amountTwelve,
bytes[] memory metadata
) public {
require(communityRegistry.hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MembershipLevel: addLevel DEFAULT_ADMIN_ROLE required");
for(uint8 i = 0; i < name.length; i++) {
data[lastOrderId] = MembershipLevelStoredData(name[i], amountOne[i], amountTwelve[i], metadata[i],true);
ordering[lastOrderId] = lastOrderId;
lastOrderId++;
levelCount++;
emit MembershipLevelCreated(lastOrderId - 1, name[i], amountOne[i], amountTwelve[i]);
}
}
function updateLevel(
uint256 position,
bytes32 name,
uint256 amountOne,
uint256 amountTwelve,
bytes memory metadata
) public {
require(communityRegistry.hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MembershipLevel: updateLevel DEFAULT_ADMIN_ROLE required");
bool isActive = data[position].isActive;
data[position] = MembershipLevelStoredData(name, amountOne, amountTwelve, metadata,isActive);
emit MembershipLevelUpdated(position, name, amountOne, amountTwelve);
}
function setLevelStatus(uint256 position, bool isActive) public {
require(data[position].isActive != isActive, "MembershipLevel: Level is already in the desired state");
require(communityRegistry.hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MembershipLevel: updateLevel DEFAULT_ADMIN_ROLE required");
data[position].isActive = isActive;
emit MembershipLevelStatusChanged(position, isActive);
}
function updateOrdering(
uint256[] memory positions,
uint256[] memory ids
) public {
require(communityRegistry.hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MembershipLevel: updateOrdering DEFAULT_ADMIN_ROLE required");
for(uint8 i = 0; i < ids.length; i++) {
ordering[positions[i]] = ids[i];
}
}
function getMembershipLevels() public view returns (MembershipLevelInfo[] memory) {
MembershipLevelInfo[] memory results = new MembershipLevelInfo[](levelCount);
for(uint8 i = 1; i <= levelCount; i++) {
MembershipLevelStoredData storage stored = data[ordering[i]];
results[i-1] = MembershipLevelInfo(
i,
ordering[i],
stored.name,
stored.amountOne,
stored.amountTwelve,
stored.metadata,
stored.isActive
);
}
return results;
}
function getMembershipData(uint256 index) public view returns (MembershipLevelStoredData memory) {
return data[index];
}
function getMembershipAmountOne(uint256 index) public view returns (uint256) {
require(data[index].isActive,"MembershipLevel : level not active");
return data[index].amountOne;
}
function getMembershipAmountTwelve(uint256 index) public view returns (uint256) {
require(data[index].isActive,"MembershipLevel : level not active");
return data[index].amountTwelve;
}
}contracts/SubscriptionDeposit/RoyaltySplitterOverride.sol
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.25;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "../@galaxis/registries/contracts/Versionable/IGenericVersionable.sol";
import "../@galaxis/registries/contracts/UsesGalaxisRegistry.sol";
contract RoyaltySplitterOverride is AccessControlEnumerable, IGenericVersionable, UsesGalaxisRegistry {
function baseVersion() public pure virtual returns (uint256) {
return 2025270101;
}
function version() public pure virtual returns (uint256) {
return 2025270101;
}
struct configItem {
bool enabled;
uint256 value;
}
mapping(uint256 => configItem) splitterConfig;
uint256 public globalSplitterConfig = 500; // 5%
address public globalSplitterAddress ; // 5%
constructor(
address _galaxisRegistry,
address _adminSafe,
address _outputSafe
) UsesGalaxisRegistry(_galaxisRegistry) {
_setupRole(DEFAULT_ADMIN_ROLE, _adminSafe);
globalSplitterAddress = _outputSafe;
}
function getSplitConfig(uint256 _communityId) public view returns (uint256, address) {
uint256 retVal;
configItem storage item = splitterConfig[_communityId];
if(item.enabled) {
retVal = item.value;
} else {
retVal = globalSplitterConfig;
}
return (retVal, globalSplitterAddress);
}
function overrideDefault(uint256 _communityId, bool _enabled, uint256 _millis) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(_millis >= 0 && _millis <= 10000, "RoyaltySplitterOverride: millis has to be 0 to 10000");
configItem storage item = splitterConfig[_communityId];
item.enabled = _enabled;
item.value = _millis;
}
function setGlobalMillis(uint256 _millis) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(_millis >= 0 && _millis <= 10000, "RoyaltySplitterOverride: millis has to be 0 to 10000");
globalSplitterConfig = _millis;
}
}Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.