Verified contractExactMIT
CyanPaymentPlanV1
Address0x52ab06b7a6eefaf50587cdb7d896a999970067be
- Balance
0 ETH
- Transactions
66
- Compiler
solc 0.8.13
- Same code
Only this contract
Details
- Compiler
- solc 0.8.13+commit.abaa5c0e
- Language
- solidity
- Optimization
- Yes, 500 runs
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 14,902,346
- Creation transaction
- 0x8a0cd47a01…cbca62e8d5
37 files
- contracts/CyanPaymentPlanV1.solmain29.66 KB
- @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol8.46 KB
- @openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol2.93 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.1 KB
- @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol2.76 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.2 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol4.03 KB
- @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol998 B
- @openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol1.33 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol7.32 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol2.04 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol1.52 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol864 B
- @openzeppelin/contracts/access/AccessControl.sol7.42 KB
- @openzeppelin/contracts/access/IAccessControl.sol2.92 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.66 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol11.81 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol3.92 KB
- @openzeppelin/contracts/token/ERC721/ERC721.sol13.62 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.74 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol964 B
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol791 B
- @openzeppelin/contracts/utils/Address.sol7.91 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.03 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.32 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- contracts/CyanVaultTokenV1.sol1.27 KB
- contracts/CyanVaultV1.sol15.88 KB
- contracts/CyanWrappedNFTV1.sol6.8 KB
- contracts/IStableSwapSTETH.sol738 B
contracts/CyanPaymentPlanV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./CyanWrappedNFTV1.sol";
import "./CyanVaultV1.sol";
contract CyanPaymentPlanV1 is AccessControl, ReentrancyGuard {
using ECDSA for bytes32;
bytes32 public constant CYAN_ROLE = keccak256("CYAN_ROLE");
uint256 private _claimableServiceFee;
address private _cyanSigner;
event CreatedBNPL(
address indexed wNFTContract,
uint256 indexed tokenId,
uint256 amount,
uint256 interestRate
);
event FundedBNPL(address indexed wNFTContract, uint256 indexed tokenId);
event ActivatedBNPL(address indexed wNFTContract, uint256 indexed tokenId);
event ActivatedAdminFundedBNPL(
address indexed wNFTContract,
uint256 indexed tokenId
);
event RejectedBNPL(address indexed wNFTContract, uint256 indexed tokenId);
event CreatedPAWN(
address indexed wNFTContract,
uint256 indexed tokenId,
uint256 amount,
uint256 interestRate
);
event LiquidatedPaymentPlan(
address indexed wNFTContract,
uint256 indexed tokenId,
uint256 estimatedPrice,
uint256 unpaidAmount,
address lastOwner
);
event Paid(
address indexed wNFTContract,
uint256 indexed tokenId,
address indexed from,
uint256 amount
);
event Completed(
address indexed wNFTContract,
uint256 indexed tokenId,
address indexed from,
uint256 amount,
address receiver
);
enum PaymentPlanStatus {
BNPL_CREATED,
BNPL_FUNDED,
BNPL_ACTIVE,
BNPL_DEFAULTED,
PAWN_ACTIVE,
PAWN_DEFAULTED
}
struct PaymentPlan {
uint256 amount;
uint256 interestRate;
uint256 createdDate;
uint256 term;
address createdUserAddress;
uint8 totalNumberOfPayments;
uint8 counterPaidPayments;
PaymentPlanStatus status;
}
mapping(address => mapping(uint256 => PaymentPlan)) public _paymentPlan;
constructor(address cyanSigner, address cyanSuperAdmin) {
require(cyanSigner != address(0), "Cyan signer address cannot be zero");
_claimableServiceFee = 0;
_cyanSigner = cyanSigner;
_setupRole(DEFAULT_ADMIN_ROLE, cyanSuperAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice Create BNPL payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
* @param amount Original price of the token
* @param interestRate Cyan interest rate
* @param signedBlockNum Signed block number
* @param term Term of payment plan in seconds
* @param totalNumberOfPayments Total number of payments required for completion
* @param signature Signature signed by Cyan signer
*/
function createBNPLPaymentPlan(
address wNFTContract,
uint256 wNFTTokenId,
uint256 amount,
uint256 interestRate,
uint256 signedBlockNum,
uint256 term,
uint8 totalNumberOfPayments,
bytes memory signature
) external payable nonReentrant {
verifySignature(
wNFTContract,
wNFTTokenId,
amount,
interestRate,
signedBlockNum,
term,
totalNumberOfPayments,
signature
);
require(
signedBlockNum <= block.number,
"Signed block number must be older"
);
require(signedBlockNum + 50 >= block.number, "Signature expired");
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments == 0,
"Payment plan already exists"
);
require(amount > 0, "Price of token is non-positive");
require(interestRate > 0, "Interest rate is non-positive");
require(msg.value > 0, "Downpayment amount is non-positive");
require(term > 0, "Term is non-positive");
require(
totalNumberOfPayments > 0,
"Total number of payments is non-positive"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(
!_cyanWrappedNFTV1.exists(wNFTTokenId),
"Token is already wrapped"
);
_paymentPlan[wNFTContract][wNFTTokenId] = PaymentPlan(
amount, //amount
interestRate, //interestRate
block.timestamp, // createdDate
term, //term
msg.sender, // createdUserAddress
totalNumberOfPayments, // totalNumberOfPayments
0, //counterPaidPayments
PaymentPlanStatus.BNPL_CREATED // status
);
(, , , uint256 currentPayment, ) = getNextPayment(
wNFTContract,
wNFTTokenId
);
require(currentPayment == msg.value, "Downpayment amount incorrect");
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments++;
emit CreatedBNPL(wNFTContract, wNFTTokenId, amount, interestRate);
}
/**
* @notice Lending ETH from Vault for BNPL payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function fundBNPL(address wNFTContract, uint256 wNFTTokenId)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments == 1,
"Only downpayment must be paid"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_CREATED,
"BNPL payment plan must be at CREATED stage"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(!_cyanWrappedNFTV1.exists(wNFTTokenId), "Wrapped token exist");
_paymentPlan[wNFTContract][wNFTTokenId].status = PaymentPlanStatus
.BNPL_FUNDED;
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
CyanVaultV1 _cyanVaultV1 = CyanVaultV1(payable(_cyanVaultAddress));
_cyanVaultV1.lend(
msg.sender,
_paymentPlan[wNFTContract][wNFTTokenId].amount
);
emit FundedBNPL(wNFTContract, wNFTTokenId);
}
/**
* @notice Activating a BNPL payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function activateBNPL(address wNFTContract, uint256 wNFTTokenId)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments == 1,
"Only downpayment must be paid"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_FUNDED,
"BNPL payment plan must be at FUNDED stage"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(!_cyanWrappedNFTV1.exists(wNFTTokenId), "Wrapped token exist");
(
uint256 payAmountForCollateral,
uint256 payAmountForInterest,
uint256 payAmountForService,
,
) = getNextPayment(wNFTContract, wNFTTokenId);
_paymentPlan[wNFTContract][wNFTTokenId].status = PaymentPlanStatus
.BNPL_ACTIVE;
_cyanWrappedNFTV1.wrap(
msg.sender,
_paymentPlan[wNFTContract][wNFTTokenId].createdUserAddress,
wNFTTokenId
);
_claimableServiceFee += payAmountForService;
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
transferEarnedAmountToCyanVault(
_cyanVaultAddress,
payAmountForCollateral,
payAmountForInterest
);
emit ActivatedBNPL(wNFTContract, wNFTTokenId);
}
/**
* @notice Activating a BNPL payment plan that admin funded
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function activateAdminFundedBNPL(address wNFTContract, uint256 wNFTTokenId)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments == 1,
"Only downpayment must be paid"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_CREATED,
"BNPL payment plan must be at CREATED stage"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(!_cyanWrappedNFTV1.exists(wNFTTokenId), "Wrapped token exist");
(
uint256 payAmountForCollateral,
uint256 payAmountForInterest,
uint256 payAmountForService,
,
) = getNextPayment(wNFTContract, wNFTTokenId);
_paymentPlan[wNFTContract][wNFTTokenId].status = PaymentPlanStatus
.BNPL_ACTIVE;
_cyanWrappedNFTV1.wrap(
msg.sender,
_paymentPlan[wNFTContract][wNFTTokenId].createdUserAddress,
wNFTTokenId
);
_claimableServiceFee += payAmountForService;
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
CyanVaultV1 _cyanVaultV1 = CyanVaultV1(payable(_cyanVaultAddress));
// Admin already funded the plan, so Vault is transfering equal amount of ETH to admin.
_cyanVaultV1.lend(
msg.sender,
_paymentPlan[wNFTContract][wNFTTokenId].amount
);
_cyanVaultV1.earn{value: payAmountForCollateral + payAmountForInterest}(
payAmountForCollateral,
payAmountForInterest
);
emit ActivatedAdminFundedBNPL(wNFTContract, wNFTTokenId);
}
/**
* @notice Create PAWN payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
* @param amount Collateral amount
* @param interestRate Cyan interest rate
* @param signedBlockNum Signed block number
* @param term Term of payment plan in seconds
* @param totalNumberOfPayments Total number of payments required for completion
* @param signature Signature signed by Cyan signer
*/
function createPAWNPaymentPlan(
address wNFTContract,
uint256 wNFTTokenId,
uint256 amount,
uint256 interestRate,
uint256 signedBlockNum,
uint256 term,
uint8 totalNumberOfPayments,
bytes memory signature
) external nonReentrant {
verifySignature(
wNFTContract,
wNFTTokenId,
amount,
interestRate,
signedBlockNum,
term,
totalNumberOfPayments,
signature
);
require(
signedBlockNum <= block.number,
"Signed block number must be older"
);
require(signedBlockNum + 50 >= block.number, "Signature expired");
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments == 0,
"Payment plan already exists"
);
require(amount > 0, "Collateral amount is non-positive");
require(interestRate > 0, "Interest rate is non-positive");
require(term > 0, "Term is non-positive");
require(
totalNumberOfPayments > 0,
"Total number of payments is non-positive"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(
!_cyanWrappedNFTV1.exists(wNFTTokenId),
"Token is already wrapped"
);
_paymentPlan[wNFTContract][wNFTTokenId] = PaymentPlan(
amount, //amount
interestRate, //interestRate
block.timestamp + term, // createdDate
term, //term
msg.sender, // createdUserAddress
totalNumberOfPayments, // totalNumberOfPayments
0, // counterPaidPayments
PaymentPlanStatus.PAWN_ACTIVE // status
);
_cyanWrappedNFTV1.wrap(msg.sender, msg.sender, wNFTTokenId);
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
CyanVaultV1 _cyanVaultV1 = CyanVaultV1(payable(_cyanVaultAddress));
_cyanVaultV1.lend(msg.sender, amount);
emit CreatedPAWN(wNFTContract, wNFTTokenId, amount, interestRate);
}
/**
* @notice Liquidate defaulted payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
* @param estimatedTokenValue Estimated value of defaulted NFT
*/
function liquidate(
address wNFTContract,
uint256 wNFTTokenId,
uint256 estimatedTokenValue
) external nonReentrant onlyRole(CYAN_ROLE) {
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments >
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments,
"Total payment done"
);
(, , , , uint256 dueDate) = getNextPayment(wNFTContract, wNFTTokenId);
require(dueDate < block.timestamp, "Next payment is still due");
uint256 unpaidAmount = 0;
for (
;
// Until the last payment
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments <
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments;
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments++
) {
(uint256 payAmountForCollateral, , , , ) = getNextPayment(
wNFTContract,
wNFTTokenId
);
unpaidAmount += payAmountForCollateral;
}
require(unpaidAmount > 0, "Unpaid is non-positive");
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(
_cyanWrappedNFTV1.exists(wNFTTokenId),
"Wrapped token does not exist"
);
address lastOwner = _cyanWrappedNFTV1.ownerOf(wNFTTokenId);
_cyanWrappedNFTV1.unwrap(
wNFTTokenId,
/* isDefaulted = */
true
);
delete _paymentPlan[wNFTContract][wNFTTokenId];
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
require(_cyanVaultAddress != address(0), "Cyan vault has zero address");
CyanVaultV1 _cyanVaultV1 = CyanVaultV1(payable(_cyanVaultAddress));
_cyanVaultV1.nftDefaulted(unpaidAmount, estimatedTokenValue);
emit LiquidatedPaymentPlan(
wNFTContract,
wNFTTokenId,
estimatedTokenValue,
unpaidAmount,
lastOwner
);
}
/**
* @notice Make a payment for the payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function pay(address wNFTContract, uint256 wNFTTokenId)
external
payable
nonReentrant
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments >
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments,
"Total payment done"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_ACTIVE ||
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.PAWN_ACTIVE,
"Payment plan must be at ACTIVE stage"
);
(
uint256 payAmountForCollateral,
uint256 payAmountForInterest,
uint256 payAmountForService,
uint256 currentPayment,
uint256 dueDate
) = getNextPayment(wNFTContract, wNFTTokenId);
require(currentPayment == msg.value, "Wrong payment amount");
require(dueDate >= block.timestamp, "Payment due date is passed");
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(
_cyanWrappedNFTV1.exists(wNFTTokenId),
"Wrapped token does not exist"
);
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments++;
_claimableServiceFee += payAmountForService;
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
transferEarnedAmountToCyanVault(
_cyanVaultAddress,
payAmountForCollateral,
payAmountForInterest
);
if (
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments ==
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments
) {
address receiver = _cyanWrappedNFTV1.ownerOf(wNFTTokenId);
_cyanWrappedNFTV1.unwrap(
wNFTTokenId,
/* isDefaulted = */
false
);
delete _paymentPlan[wNFTContract][wNFTTokenId];
emit Completed(
wNFTContract,
wNFTTokenId,
msg.sender,
msg.value,
receiver
);
} else {
emit Paid(wNFTContract, wNFTTokenId, msg.sender, msg.value);
}
}
/**
* @notice Reject the payment plan
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function rejectBNPLPaymentPlan(address wNFTContract, uint256 wNFTTokenId)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments == 1,
"Payment done other than downpayment for this plan"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_CREATED,
"BNPL payment plan must be at CREATED stage"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(!_cyanWrappedNFTV1.exists(wNFTTokenId), "Wrapped token exists");
(, , , uint256 currentPayment, ) = getNextPayment(
wNFTContract,
wNFTTokenId
);
// Returning downpayment to created user address
payable(_paymentPlan[wNFTContract][wNFTTokenId].createdUserAddress)
.transfer(currentPayment);
delete _paymentPlan[wNFTContract][wNFTTokenId];
emit RejectedBNPL(wNFTContract, wNFTTokenId);
}
/**
* @notice Reject the payment plan after FUNDED
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
*/
function rejectBNPLPaymentPlanAfterFunded(
address wNFTContract,
uint256 wNFTTokenId
) external payable nonReentrant onlyRole(CYAN_ROLE) {
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].counterPaidPayments == 1,
"Payment done other than downpayment for this plan"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.BNPL_FUNDED,
"BNPL payment plan must be at FUNDED stage"
);
require(
_paymentPlan[wNFTContract][wNFTTokenId].amount == msg.value,
"Wrong fund return amount"
);
CyanWrappedNFTV1 _cyanWrappedNFTV1 = CyanWrappedNFTV1(wNFTContract);
require(!_cyanWrappedNFTV1.exists(wNFTTokenId), "Wrapped token exists");
(, , , uint256 currentPayment, ) = getNextPayment(
wNFTContract,
wNFTTokenId
);
// Returning downpayment to created user address
payable(_paymentPlan[wNFTContract][wNFTTokenId].createdUserAddress)
.transfer(currentPayment);
delete _paymentPlan[wNFTContract][wNFTTokenId];
// Returning funded amount back to Vault
address _cyanVaultAddress = _cyanWrappedNFTV1.getCyanVaultAddress();
transferEarnedAmountToCyanVault(_cyanVaultAddress, msg.value, 0);
emit RejectedBNPL(wNFTContract, wNFTTokenId);
}
/**
* @notice Calculate payments for given amount and interest rate
* @param amount amount of collateral
* @param interestRate interest rate
* @param numOfPayment Number of payments
* @return First payment amount for collateral
* @return Total payment amount for interest fee
* @return First payment amount for interest fee
* @return Total payment amount for service fee
* @return First payment amount for service fee
* @return First payment amount
*/
function calculateIndividualPayments(
uint256 amount,
uint256 interestRate,
uint8 numOfPayment
)
private
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
// Payment amount for collateral
uint256 payAmountForCollateral = amount / numOfPayment;
// Calculating interest fee, Note that interest rate is x100
uint256 interestFee = (amount * interestRate) / 10000;
// Payment amount for interest fee payment
uint256 payAmountForInterest = interestFee / numOfPayment;
// Calculating 2.5% service fee
uint256 serviceFee = amount / 40;
// Payment amount for service fee payment
uint256 payAmountForService = serviceFee / numOfPayment;
// First amount
uint256 currentPayment = payAmountForCollateral +
payAmountForInterest +
payAmountForService;
return (
payAmountForCollateral,
interestFee,
payAmountForInterest,
serviceFee,
payAmountForService,
currentPayment
);
}
/**
* @notice Return next payment info
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
* @return Next payment amount for collateral
* @return Next payment amount for interest fee
* @return Next payment amount for service fee
* @return Next payment amount
* @return Due date
*/
function getNextPayment(address wNFTContract, uint256 wNFTTokenId)
public
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
PaymentPlan memory plan = _paymentPlan[wNFTContract][wNFTTokenId];
(
uint256 payAmountForCollateral,
uint256 interestFee,
uint256 payAmountForInterest,
uint256 serviceFee,
uint256 payAmountForService,
uint256 currentPayment
) = calculateIndividualPayments(
plan.amount,
plan.interestRate,
plan.totalNumberOfPayments
);
if (plan.counterPaidPayments + 1 == plan.totalNumberOfPayments) {
// Last payment
payAmountForCollateral =
plan.amount -
(payAmountForCollateral * plan.counterPaidPayments);
payAmountForInterest =
interestFee -
(payAmountForInterest * plan.counterPaidPayments);
payAmountForService =
serviceFee -
(payAmountForService * plan.counterPaidPayments);
currentPayment =
payAmountForCollateral +
payAmountForInterest +
payAmountForService;
}
return (
payAmountForCollateral,
payAmountForInterest,
payAmountForService,
currentPayment,
plan.createdDate + plan.counterPaidPayments * plan.term
);
}
/**
* @notice Transfer earned amount to Cyan Vault
* @param cyanVaultAddress Original price of the token
* @param paidTokenPayment Paid token payment
* @param paidInterestFee Paid interest fee
*/
function transferEarnedAmountToCyanVault(
address cyanVaultAddress,
uint256 paidTokenPayment,
uint256 paidInterestFee
) private {
require(cyanVaultAddress != address(0), "Cyan vault has zero address");
CyanVaultV1 _cyanVaultV1 = CyanVaultV1(payable(cyanVaultAddress));
_cyanVaultV1.earn{value: paidTokenPayment + paidInterestFee}(
paidTokenPayment,
paidInterestFee
);
}
/**
* @notice Return expected payment plan for given price and interest rate
* @param amount Original price of the token
* @param interestRate Interest rate
* @param numOfPayment Number of payments
* @return Original price of the token
* @return Interest Fee
* @return Service Fee
* @return Downpayment amount
* @return Total payment amount
*/
function getExpectedPaymentPlan(
uint256 amount,
uint256 interestRate,
uint8 numOfPayment
)
external
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(
,
uint256 interestFee,
,
uint256 serviceFee,
,
uint256 currentPayment
) = calculateIndividualPayments(amount, interestRate, numOfPayment);
uint256 totalPayment = amount + interestFee + serviceFee;
return (amount, interestFee, serviceFee, currentPayment, totalPayment);
}
/**
* @notice Check if payment plan is pending
* @param wNFTContract Wrapped NFT contract address
* @param wNFTTokenId Wrapped NFT token ID
* @return PaymentPlanStatus
*/
function getPaymentPlanStatus(address wNFTContract, uint256 wNFTTokenId)
external
view
returns (PaymentPlanStatus)
{
require(
_paymentPlan[wNFTContract][wNFTTokenId].totalNumberOfPayments != 0,
"No payment plan found"
);
(, , , , uint256 dueDate) = getNextPayment(wNFTContract, wNFTTokenId);
bool isDefaulted = block.timestamp > dueDate;
if (isDefaulted) {
if (
_paymentPlan[wNFTContract][wNFTTokenId].status ==
PaymentPlanStatus.PAWN_ACTIVE
) {
return PaymentPlanStatus.PAWN_DEFAULTED;
}
return PaymentPlanStatus.BNPL_DEFAULTED;
}
return _paymentPlan[wNFTContract][wNFTTokenId].status;
}
/**
* @notice Getting claimable service fee amount
*/
function getClaimableServiceFee()
external
view
onlyRole(CYAN_ROLE)
returns (uint256)
{
return _claimableServiceFee;
}
/**
* @notice Claiming collected service fee amount
*/
function claimServiceFee()
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
{
payable(msg.sender).transfer(_claimableServiceFee);
_claimableServiceFee = 0;
}
function verifySignature(
address wNFTContract,
uint256 wNFTTokenId,
uint256 amount,
uint256 interestRate,
uint256 timestamp,
uint256 term,
uint8 totalNumberOfPayments,
bytes memory signature
) internal view {
bytes32 msgHash = keccak256(
abi.encodePacked(
wNFTContract,
wNFTTokenId,
amount,
interestRate,
timestamp,
term,
totalNumberOfPayments
)
);
bytes32 signedHash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)
);
require(
signedHash.recover(signature) == _cyanSigner,
"Invalid signature"
);
}
function updateCyanSignerAddress(address cyanSigner)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(cyanSigner != address(0), "Zero Cyan Signer address");
_cyanSigner = cyanSigner;
}
}
@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
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(IAccessControlUpgradeable).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 ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.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.
*/
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.
*/
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`.
*/
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.
*
* [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.
*/
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.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.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 IAccessControlUpgradeable {
/**
* @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-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
*/
modifier initializer() {
bool isTopLevelCall = _setInitializedVersion(1);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
* initialization step. This is essential to configure modules that are added through upgrades and that require
* initialization.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*/
modifier reinitializer(uint8 version) {
bool isTopLevelCall = _setInitializedVersion(version);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(version);
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*/
function _disableInitializers() internal virtual {
_setInitializedVersion(type(uint8).max);
}
function _setInitializedVersion(uint8 version) private returns (bool) {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
// of initializers, because in other contexts the contract may have been reentered.
if (_initializing) {
require(
version == 1 && !AddressUpgradeable.isContract(address(this)),
"Initializable: contract is already initialized"
);
return false;
} else {
require(_initialized < version, "Initializable: contract is already initialized");
_initialized = version;
return true;
}
}
}
@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.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 IERC20Upgradeable {
/**
* @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-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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));
}
}
/**
* @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(IERC20Upgradeable 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-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
function __ERC721Holder_init() internal onlyInitializing {
}
function __ERC721Holder_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @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);
}
}
@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {
/**
* @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/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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, _msgSender());
_;
}
/**
* @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 override returns (bool) {
return _roles[role].members[account];
}
/**
* @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 {
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 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.
*/
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.
*/
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`.
*/
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.
*
* [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.
*/
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.
*/
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/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/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - 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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, 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 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 v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @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);
}
@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/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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));
}
}
/**
* @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/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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
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 v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @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);
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
@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);
}
contracts/CyanVaultTokenV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract CyanVaultTokenV1 is AccessControl, ERC20 {
bytes32 public constant CYAN_VAULT_ROLE = keccak256("CYAN_VAULT_ROLE");
event BurnedAdminToken(uint256 amount);
constructor(
string memory _name,
string memory _symbol,
address cyanSuperAdmin
) ERC20(_name, _symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, cyanSuperAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function mint(address to, uint256 amount)
external
onlyRole(CYAN_VAULT_ROLE)
{
require(to != address(0), "Mint to the zero address");
_mint(to, amount);
}
function burn(address from, uint256 amount)
external
onlyRole(CYAN_VAULT_ROLE)
{
require(balanceOf(from) >= amount, "Balance not enough");
_burn(from, amount);
}
function burnAdminToken(uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(balanceOf(msg.sender) >= amount, "Balance not enough");
_burn(msg.sender, amount);
emit BurnedAdminToken(amount);
}
}
contracts/CyanVaultV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./CyanVaultTokenV1.sol";
import "./IStableSwapSTETH.sol";
contract CyanVaultV1 is
AccessControlUpgradeable,
ReentrancyGuardUpgradeable,
ERC721HolderUpgradeable,
PausableUpgradeable
{
using SafeERC20Upgradeable for IERC20Upgradeable;
bytes32 public constant CYAN_ROLE = keccak256("CYAN_ROLE");
bytes32 public constant CYAN_PAYMENT_PLAN_ROLE =
keccak256("CYAN_PAYMENT_PLAN_ROLE");
bytes32 public constant CYAN_BALANCER_ROLE =
keccak256("CYAN_BALANCER_ROLE");
event DepositETH(
address indexed from,
uint256 ethAmount,
uint256 tokenAmount
);
event Lend(address indexed to, uint256 amount);
event Earn(uint256 paymentAmount, uint256 profitAmount);
event NftDefaulted(uint256 unpaidAmount, uint256 estimatedPriceOfNFT);
event NftLiquidated(uint256 defaultedAssetsAmount, uint256 soldAmount);
event WithdrawETH(
address indexed from,
uint256 ethAmount,
uint256 tokenAmount
);
event GetDefaultedNFT(
address indexed to,
address indexed contractAddress,
uint256 indexed tokenId
);
event UpdatedDefaultedNFTAssetAmount(uint256 amount);
event UpdatedServiceFeePercent(uint256 from, uint256 to);
event UpdatedSafetyFundPercent(uint256 from, uint256 to);
event InitializedServiceFeePercent(uint256 to);
event InitializedSafetyFundPercent(uint256 to);
event ExchangedEthToStEth(uint256 ethAmount, uint256 receivedStEthAmount);
event ExchangedStEthToEth(uint256 stEthAmount, uint256 receivedEthAmount);
event ReceivedETH(uint256 amount, address indexed from);
event WithdrewERC20(address indexed token, address to, uint256 amount);
event CollectedServiceFee(uint256 collectedAmount, uint256 remainingAmount);
address public _cyanVaultTokenAddress;
CyanVaultTokenV1 private _cyanVaultTokenContract;
IERC20 private _stEthTokenContract;
IStableSwapSTETH private _stableSwapSTETHContract;
// Safety fund percent. (x100)
uint256 public _safetyFundPercent;
// Cyan service fee percent. (x100)
uint256 public _serviceFeePercent;
// Remaining amount of ETH
uint256 private REMAINING_AMOUNT;
// Total loaned amount
uint256 private LOANED_AMOUNT;
// Total defaulted NFT amount
uint256 private DEFAULTED_NFT_ASSET_AMOUNT;
// Cyan collected service fee
uint256 private COLLECTED_SERVICE_FEE_AMOUNT;
function initialize(
address cyanVaultTokenAddress,
address cyanPaymentPlanAddress,
address stEthTokenAddress,
address curveStableSwapStEthAddress,
address cyanSuperAdmin,
uint256 safetyFundPercent,
uint256 serviceFeePercent
) external initializer {
require(
cyanVaultTokenAddress != address(0),
"Cyan Vault Token address cannot be zero"
);
require(
safetyFundPercent <= 10000,
"Safety fund percent must be equal or less than 100 percent"
);
require(
serviceFeePercent <= 200,
"Service fee percent must not be greater than 2 percent"
);
__AccessControl_init();
__ReentrancyGuard_init();
__ERC721Holder_init();
__Pausable_init();
_cyanVaultTokenAddress = cyanVaultTokenAddress;
_cyanVaultTokenContract = CyanVaultTokenV1(_cyanVaultTokenAddress);
_safetyFundPercent = safetyFundPercent;
_serviceFeePercent = serviceFeePercent;
LOANED_AMOUNT = 0;
DEFAULTED_NFT_ASSET_AMOUNT = 0;
REMAINING_AMOUNT = 0;
_stEthTokenContract = IERC20(stEthTokenAddress);
_stableSwapSTETHContract = IStableSwapSTETH(
curveStableSwapStEthAddress
);
_setupRole(DEFAULT_ADMIN_ROLE, cyanSuperAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CYAN_PAYMENT_PLAN_ROLE, cyanPaymentPlanAddress);
emit InitializedServiceFeePercent(serviceFeePercent);
emit InitializedSafetyFundPercent(safetyFundPercent);
}
// User stakes ETH
function depositETH() external payable nonReentrant whenNotPaused {
require(msg.value > 0, "Must deposit more than 0 ETH");
// Cyan collecting service fee from deposits
uint256 cyanServiceFee = (msg.value * _serviceFeePercent) / 10000;
uint256 depositedAmount = msg.value - cyanServiceFee;
uint256 mintAmount = calculateTokenByETH(depositedAmount);
REMAINING_AMOUNT += depositedAmount;
COLLECTED_SERVICE_FEE_AMOUNT += cyanServiceFee;
_cyanVaultTokenContract.mint(msg.sender, mintAmount);
emit DepositETH(msg.sender, depositedAmount, mintAmount);
}
// Cyan lends money from Vault to do BNPL or PAWN
function lend(address to, uint256 amount)
external
nonReentrant
whenNotPaused
onlyRole(CYAN_PAYMENT_PLAN_ROLE)
{
require(to != address(0), "to address cannot be zero");
uint256 maxWithdrableAmount = getMaxWithdrawableAmount();
require(amount <= maxWithdrableAmount, "Not enough ETH in the Vault");
LOANED_AMOUNT += amount;
REMAINING_AMOUNT -= amount;
payable(to).transfer(amount);
emit Lend(to, amount);
}
// Cyan Payment Plan contract transfers paid amount back to Vault
function earn(uint256 amount, uint256 profit)
external
payable
nonReentrant
onlyRole(CYAN_PAYMENT_PLAN_ROLE)
{
require(msg.value == amount + profit, "Wrong tranfer amount");
REMAINING_AMOUNT += msg.value;
if (LOANED_AMOUNT >= amount) {
LOANED_AMOUNT -= amount;
} else {
LOANED_AMOUNT = 0;
}
emit Earn(amount, profit);
}
// When BNPL or PAWN plan defaults
function nftDefaulted(uint256 unpaidAmount, uint256 estimatedPriceOfNFT)
external
nonReentrant
onlyRole(CYAN_PAYMENT_PLAN_ROLE)
{
DEFAULTED_NFT_ASSET_AMOUNT += estimatedPriceOfNFT;
if (LOANED_AMOUNT >= unpaidAmount) {
LOANED_AMOUNT -= unpaidAmount;
} else {
LOANED_AMOUNT = 0;
}
emit NftDefaulted(unpaidAmount, estimatedPriceOfNFT);
}
// Liquidating defaulted BNPL or PAWN token and tranferred sold amount to Vault
function liquidateNFT(uint256 totalDefaultedNFTAmount)
external
payable
whenNotPaused
onlyRole(CYAN_ROLE)
{
REMAINING_AMOUNT += msg.value;
DEFAULTED_NFT_ASSET_AMOUNT = totalDefaultedNFTAmount;
emit NftLiquidated(msg.value, totalDefaultedNFTAmount);
}
// User unstakes tokenAmount of tokens and gets back ETH
function withdraw(uint256 amount) external nonReentrant whenNotPaused {
require(amount > 0, "Non-positive token amount");
uint256 balance = _cyanVaultTokenContract.balanceOf(msg.sender);
require(balance >= amount, "Check the token balance");
uint256 withdrawableTokenBalance = getWithdrawableBalance(msg.sender);
require(
amount <= withdrawableTokenBalance,
"Not enough active balance in Cyan Vault"
);
uint256 withdrawETHAmount = calculateETHByToken(amount);
REMAINING_AMOUNT -= withdrawETHAmount;
_cyanVaultTokenContract.burn(msg.sender, amount);
payable(msg.sender).transfer(withdrawETHAmount);
emit WithdrawETH(msg.sender, withdrawETHAmount, amount);
}
// Cyan updating total amount of defaulted NFT assets
function updateDefaultedNFTAssetAmount(uint256 amount)
external
whenNotPaused
onlyRole(CYAN_ROLE)
{
DEFAULTED_NFT_ASSET_AMOUNT = amount;
emit UpdatedDefaultedNFTAssetAmount(amount);
}
// Get defaulted NFT from Vault to Cyan Admin account
function getDefaultedNFT(address contractAddress, uint256 tokenId)
external
nonReentrant
whenNotPaused
onlyRole(CYAN_ROLE)
{
require(contractAddress != address(0), "Zero contract address");
IERC721 originalContract = IERC721(contractAddress);
require(
originalContract.ownerOf(tokenId) == address(this),
"Vault is not the owner of the token"
);
originalContract.safeTransferFrom(address(this), msg.sender, tokenId);
emit GetDefaultedNFT(msg.sender, contractAddress, tokenId);
}
function getWithdrawableBalance(address user)
public
view
returns (uint256)
{
uint256 tokenBalance = _cyanVaultTokenContract.balanceOf(user);
uint256 ethAmountForToken = calculateETHByToken(tokenBalance);
uint256 maxWithdrawableAmount = getMaxWithdrawableAmount();
if (ethAmountForToken <= maxWithdrawableAmount) {
return tokenBalance;
}
return calculateTokenByETH(maxWithdrawableAmount);
}
function getMaxWithdrawableAmount() public view returns (uint256) {
uint256 util = ((LOANED_AMOUNT + DEFAULTED_NFT_ASSET_AMOUNT) *
_safetyFundPercent) / 10000;
if (REMAINING_AMOUNT > util) {
return REMAINING_AMOUNT - util;
}
return 0;
}
function getCurrentAssetAmounts()
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
REMAINING_AMOUNT,
LOANED_AMOUNT,
DEFAULTED_NFT_ASSET_AMOUNT,
COLLECTED_SERVICE_FEE_AMOUNT,
_stEthTokenContract.balanceOf(address(this))
);
}
function calculateTokenByETH(uint256 amount) public view returns (uint256) {
(uint256 totalETH, uint256 totalToken) = getTotalEthAndToken();
if (totalETH == 0) return amount;
return (amount * totalToken) / totalETH;
}
function calculateETHByToken(uint256 amount) public view returns (uint256) {
(uint256 totalETH, uint256 totalToken) = getTotalEthAndToken();
if (totalToken == 0) return amount;
return (amount * totalETH) / totalToken;
}
function getTotalEthAndToken() private view returns (uint256, uint256) {
uint256 vaultStEthBalance = _stEthTokenContract.balanceOf(
address(this)
);
uint256 stEthInEth = _stableSwapSTETHContract.get_dy(
1,
0,
vaultStEthBalance
);
uint256 totalETH = REMAINING_AMOUNT +
LOANED_AMOUNT +
DEFAULTED_NFT_ASSET_AMOUNT +
stEthInEth;
uint256 totalToken = _cyanVaultTokenContract.totalSupply();
return (totalETH, totalToken);
}
function exchangeEthToStEth(uint256 ethAmount, uint256 minStEthAmount)
external
nonReentrant
onlyRole(CYAN_BALANCER_ROLE)
{
require(ethAmount > 0, "Exchanging ETH amount is zero");
require(
ethAmount <= REMAINING_AMOUNT,
"Cannot exchange more than REMAINING_AMOUNT"
);
// Exchanging ETH to stETH
REMAINING_AMOUNT -= ethAmount;
uint256 receivedStEthAmount = _stableSwapSTETHContract.exchange{
value: ethAmount
}(0, 1, ethAmount, minStEthAmount);
emit ExchangedEthToStEth(ethAmount, receivedStEthAmount);
}
function exchangeStEthToEth(uint256 stEthAmount, uint256 minEthAmount)
external
nonReentrant
onlyRole(CYAN_BALANCER_ROLE)
{
require(stEthAmount > 0, "Exchanging stETH amount is zero");
// Exchanging stETH to ETH
bool isApproved = _stEthTokenContract.approve(
address(_stableSwapSTETHContract),
stEthAmount
);
require(
isApproved,
"stETH approval to stableSwapSTETH contract failed"
);
uint256 receivedEthAmount = _stableSwapSTETHContract.exchange(
1,
0,
stEthAmount,
minEthAmount
);
emit ExchangedStEthToEth(stEthAmount, receivedEthAmount);
}
function updateSafetyFundPercent(uint256 safetyFundPercent)
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
safetyFundPercent <= 10000,
"Safety fund percent must be equal or less than 100 percent"
);
emit UpdatedSafetyFundPercent(_safetyFundPercent, safetyFundPercent);
_safetyFundPercent = safetyFundPercent;
}
function updateServiceFeePercent(uint256 serviceFeePercent)
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
serviceFeePercent <= 200,
"Service fee percent must not be greater than 2 percent"
);
emit UpdatedServiceFeePercent(_serviceFeePercent, serviceFeePercent);
_serviceFeePercent = serviceFeePercent;
}
function collectServiceFee(uint256 amount)
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
amount <= COLLECTED_SERVICE_FEE_AMOUNT,
"Not enough collected service fee"
);
COLLECTED_SERVICE_FEE_AMOUNT -= amount;
payable(msg.sender).transfer(amount);
emit CollectedServiceFee(amount, COLLECTED_SERVICE_FEE_AMOUNT);
}
function withdrawAirDroppedERC20(address contractAddress, uint256 amount)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
contractAddress != address(_stEthTokenContract),
"Cannot withdraw stETH"
);
IERC20Upgradeable erc20Contract = IERC20Upgradeable(contractAddress);
require(
erc20Contract.balanceOf(address(this)) >= amount,
"ERC20 balance not enough"
);
erc20Contract.safeTransfer(msg.sender, amount);
emit WithdrewERC20(contractAddress, msg.sender, amount);
}
function withdrawApprovedERC20(
address contractAddress,
address from,
uint256 amount
) external nonReentrant onlyRole(CYAN_ROLE) {
require(
contractAddress != address(_stEthTokenContract),
"Cannot withdraw stETH"
);
IERC20Upgradeable erc20Contract = IERC20Upgradeable(contractAddress);
require(
erc20Contract.allowance(from, address(this)) >= amount,
"ERC20 allowance not enough"
);
erc20Contract.safeTransferFrom(from, msg.sender, amount);
emit WithdrewERC20(contractAddress, msg.sender, amount);
}
receive() external payable {
REMAINING_AMOUNT += msg.value;
emit ReceivedETH(msg.value, msg.sender);
}
fallback() external payable {
REMAINING_AMOUNT += msg.value;
emit ReceivedETH(msg.value, msg.sender);
}
function pause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
function unpause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
}
contracts/CyanWrappedNFTV1.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract CyanWrappedNFTV1 is
AccessControl,
ERC721,
ReentrancyGuard,
ERC721Holder
{
using Strings for uint256;
using SafeERC20 for IERC20;
bytes32 public constant CYAN_ROLE = keccak256("CYAN_ROLE");
bytes32 public constant CYAN_PAYMENT_PLAN_ROLE =
keccak256("CYAN_PAYMENT_PLAN_ROLE");
string private baseURI;
string private baseExtension;
address private immutable originalNFT;
address private cyanVaultAddress;
ERC721 private immutable originalNFTContract;
event Wrap(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Unwrap(
address indexed to,
uint256 indexed tokenId,
bool indexed isDefaulted
);
event WithdrewERC20(address indexed token, address to, uint256 amount);
event WithdrewERC721(
address indexed collection,
address to,
uint256 indexed tokenId
);
constructor(
address _originalNFT,
address _cyanVaultAddress,
address cyanPaymentPlanContractAddress,
address cyanSuperAdmin,
string memory _name,
string memory _symbol,
string memory uri,
string memory extension
) ERC721(_name, _symbol) {
require(
_originalNFT != address(0),
"Original NFT address cannot be zero"
);
require(
_cyanVaultAddress != address(0),
"Cyan Vault address cannot be zero"
);
originalNFT = _originalNFT;
cyanVaultAddress = _cyanVaultAddress;
originalNFTContract = ERC721(_originalNFT);
baseURI = uri;
baseExtension = extension;
_setupRole(DEFAULT_ADMIN_ROLE, cyanSuperAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CYAN_PAYMENT_PLAN_ROLE, cyanPaymentPlanContractAddress);
}
function wrap(
address from,
address to,
uint256 tokenId
) external nonReentrant onlyRole(CYAN_PAYMENT_PLAN_ROLE) {
require(to != address(0), "Wrap to the zero address");
require(!_exists(tokenId), "Token already wrapped");
originalNFTContract.safeTransferFrom(from, address(this), tokenId);
_safeMint(to, tokenId);
emit Wrap(from, to, tokenId);
}
function unwrap(uint256 tokenId, bool isDefaulted)
external
nonReentrant
onlyRole(CYAN_PAYMENT_PLAN_ROLE)
{
require(_exists(tokenId), "Token is not wrapped");
address to;
if (isDefaulted) {
to = cyanVaultAddress;
} else {
to = ownerOf(tokenId);
}
_burn(tokenId);
originalNFTContract.safeTransferFrom(address(this), to, tokenId);
emit Unwrap(to, tokenId, isDefaulted);
}
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
function getOriginalNFTAddress() external view returns (address) {
return originalNFT;
}
function getCyanVaultAddress() external view returns (address) {
return cyanVaultAddress;
}
function updateCyanVaultAddress(address _cyanVaultAddress)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_cyanVaultAddress != address(0), "Zero Cyan Vault address");
cyanVaultAddress = _cyanVaultAddress;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function _baseExtension() internal view returns (string memory) {
return baseExtension;
}
function setBaseURI(string calldata newBaseURI)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
baseURI = newBaseURI;
}
function setBaseExtension(string calldata newBaseExtension)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
baseExtension = newBaseExtension;
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "Wrapped token does not exist");
string memory uri = _baseURI();
if (bytes(uri).length > 0) {
string memory extension = _baseExtension();
if (bytes(extension).length > 0) {
return
string(
abi.encodePacked(uri, tokenId.toString(), extension)
);
}
return string(abi.encodePacked(uri, tokenId.toString()));
}
return "";
}
function withdrawAirDroppedERC721(address contractAddress, uint256 tokenId)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
require(
contractAddress != address(this),
"Cannot withdraw own wrapped token"
);
require(
contractAddress != originalNFT,
"Cannot withdraw original NFT of the wrapper contract"
);
ERC721 erc721Contract = ERC721(contractAddress);
erc721Contract.safeTransferFrom(address(this), msg.sender, tokenId);
emit WithdrewERC721(contractAddress, msg.sender, tokenId);
}
function withdrawAirDroppedERC20(address contractAddress, uint256 amount)
external
nonReentrant
onlyRole(CYAN_ROLE)
{
IERC20 erc20Contract = IERC20(contractAddress);
require(
erc20Contract.balanceOf(address(this)) >= amount,
"ERC20 balance not enough"
);
erc20Contract.safeTransfer(msg.sender, amount);
emit WithdrewERC20(contractAddress, msg.sender, amount);
}
function withdrawApprovedERC20(
address contractAddress,
address from,
uint256 amount
) external nonReentrant onlyRole(CYAN_ROLE) {
IERC20 erc20Contract = IERC20(contractAddress);
require(
erc20Contract.allowance(from, address(this)) >= amount,
"ERC20 allowance not enough"
);
erc20Contract.safeTransferFrom(from, msg.sender, amount);
emit WithdrewERC20(contractAddress, msg.sender, amount);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
contracts/IStableSwapSTETH.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
interface IStableSwapSTETH {
/**
* @notice Perform an exchange between two coins
* @dev Index values can be found via the `coins` public getter method
* @param i Index value for the coin to send
* @param j Index valie of the coin to recieve
* @param dx Amount of `i` being exchanged
* @param min_dy Minimum amount of `j` to receive
* @return Actual amount of `j` received
*/
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external payable returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
}
Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 500,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.