文件 1 的 17:Address.sol
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 17:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
文件 3 的 17:ERC1155Holder.sol
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
文件 4 的 17:ERC1155Receiver.sol
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId
|| super.supportsInterface(interfaceId);
}
}
文件 5 的 17:ERC165.sol
pragma solidity ^0.8.0;
import "./IERC165.sol";
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
文件 6 的 17:ERC20.sol
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "../../utils/Context.sol";
contract ERC20 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
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");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
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);
}
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");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
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);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
文件 7 的 17:ERC721Holder.sol
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
contract ERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
文件 8 的 17:IERC1155.sol
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
interface IERC1155 is IERC165 {
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
文件 9 的 17:IERC1155Receiver.sol
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
interface IERC1155Receiver is IERC165 {
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
文件 10 的 17:IERC165.sol
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
文件 11 的 17:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 12 的 17:IERC721.sol
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
文件 13 的 17:IERC721Receiver.sol
pragma solidity ^0.8.0;
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
文件 14 的 17:IReNFT.sol
pragma solidity =0.8.6;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IResolver.sol";
interface IReNft is IERC721Receiver, IERC1155Receiver {
event Lent(
address indexed nftAddress,
uint256 indexed tokenId,
uint8 lentAmount,
uint256 lendingId,
address indexed lenderAddress,
uint8 maxRentDuration,
bytes4 dailyRentPrice,
bytes4 nftPrice,
bool isERC721,
IResolver.PaymentToken paymentToken
);
event Rented(
uint256 lendingId,
address indexed renterAddress,
uint8 rentDuration,
uint32 rentedAt
);
event Returned(uint256 indexed lendingId, uint32 returnedAt);
event CollateralClaimed(uint256 indexed lendingId, uint32 claimedAt);
event LendingStopped(uint256 indexed lendingId, uint32 stoppedAt);
function lend(
address[] memory _nft,
uint256[] memory _tokenId,
uint256[] memory _lendAmounts,
uint8[] memory _maxRentDuration,
bytes4[] memory _dailyRentPrice,
bytes4[] memory _nftPrice,
IResolver.PaymentToken[] memory _paymentToken
) external;
function rent(
address[] memory _nft,
uint256[] memory _tokenId,
uint256[] memory _lendingIds,
uint8[] memory _rentDurations
) external;
function returnIt(
address[] memory _nft,
uint256[] memory _tokenId,
uint256[] memory _lendingIds
) external;
function claimCollateral(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds
) external;
function stopLending(
address[] memory _nft,
uint256[] memory _tokenId,
uint256[] memory _lendingIds
) external;
}
文件 15 的 17:IResolver.sol
pragma solidity =0.8.6;
interface IResolver {
enum PaymentToken {SENTINEL, WETH, DAI, USDC, USDT, TUSD, RENT}
function getPaymentToken(uint8 _pt) external view returns (address);
function setPaymentToken(uint8 _pt, address _v) external;
}
文件 16 的 17:ReNFT.sol
pragma solidity =0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "./interfaces/IResolver.sol";
import "./interfaces/IReNFT.sol";
contract ReNFT is IReNft, ERC721Holder, ERC1155Receiver, ERC1155Holder {
using SafeERC20 for ERC20;
IResolver private resolver;
address private admin;
address payable private beneficiary;
uint256 private lendingId = 1;
bool public paused = false;
uint256 public rentFee = 0;
uint256 private constant SECONDS_IN_DAY = 86400;
struct Lending {
address payable lenderAddress;
uint8 maxRentDuration;
bytes4 dailyRentPrice;
bytes4 nftPrice;
uint8 lentAmount;
IResolver.PaymentToken paymentToken;
}
struct Renting {
address payable renterAddress;
uint8 rentDuration;
uint32 rentedAt;
}
struct LendingRenting {
Lending lending;
Renting renting;
}
mapping(bytes32 => LendingRenting) private lendingRenting;
struct CallData {
uint256 left;
uint256 right;
address[] nfts;
uint256[] tokenIds;
uint256[] lentAmounts;
uint8[] maxRentDurations;
bytes4[] dailyRentPrices;
bytes4[] nftPrices;
uint256[] lendingIds;
uint8[] rentDurations;
IResolver.PaymentToken[] paymentTokens;
}
modifier onlyAdmin {
require(msg.sender == admin, "ReNFT::not admin");
_;
}
modifier notPaused {
require(!paused, "ReNFT::paused");
_;
}
constructor(
address _resolver,
address payable _beneficiary,
address _admin
) {
ensureIsNotZeroAddr(_resolver);
ensureIsNotZeroAddr(_beneficiary);
ensureIsNotZeroAddr(_admin);
resolver = IResolver(_resolver);
beneficiary = _beneficiary;
admin = _admin;
}
function bundleCall(function(CallData memory) _handler, CallData memory _cd)
private
{
require(_cd.nfts.length > 0, "ReNFT::no nfts");
while (_cd.right != _cd.nfts.length) {
if (
(_cd.nfts[_cd.left] == _cd.nfts[_cd.right]) &&
(is1155(_cd.nfts[_cd.right]))
) {
_cd.right++;
} else {
_handler(_cd);
_cd.left = _cd.right;
_cd.right++;
}
}
_handler(_cd);
}
function lend(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendAmounts,
uint8[] memory _maxRentDurations,
bytes4[] memory _dailyRentPrices,
bytes4[] memory _nftPrices,
IResolver.PaymentToken[] memory _paymentTokens
) external override notPaused {
bundleCall(
handleLend,
createLendCallData(
_nfts,
_tokenIds,
_lendAmounts,
_maxRentDurations,
_dailyRentPrices,
_nftPrices,
_paymentTokens
)
);
}
function rent(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds,
uint8[] memory _rentDurations
) external override notPaused {
bundleCall(
handleRent,
createRentCallData(_nfts, _tokenIds, _lendingIds, _rentDurations)
);
}
function returnIt(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds
) external override notPaused {
bundleCall(
handleReturn,
createActionCallData(_nfts, _tokenIds, _lendingIds)
);
}
function stopLending(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds
) external override notPaused {
bundleCall(
handleStopLending,
createActionCallData(_nfts, _tokenIds, _lendingIds)
);
}
function claimCollateral(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds
) external override notPaused {
bundleCall(
handleClaimCollateral,
createActionCallData(_nfts, _tokenIds, _lendingIds)
);
}
function takeFee(uint256 _rent, IResolver.PaymentToken _paymentToken)
private
returns (uint256 fee)
{
fee = _rent * rentFee;
fee /= 10000;
uint8 paymentTokenIx = uint8(_paymentToken);
ensureTokenNotSentinel(paymentTokenIx);
ERC20 paymentToken = ERC20(resolver.getPaymentToken(paymentTokenIx));
paymentToken.safeTransfer(beneficiary, fee);
}
function distributePayments(
LendingRenting storage _lendingRenting,
uint256 _secondsSinceRentStart
) private {
uint8 paymentTokenIx = uint8(_lendingRenting.lending.paymentToken);
ensureTokenNotSentinel(paymentTokenIx);
address paymentToken = resolver.getPaymentToken(paymentTokenIx);
uint256 decimals = ERC20(paymentToken).decimals();
uint256 scale = 10**decimals;
uint256 nftPrice =
_lendingRenting.lending.lentAmount *
unpackPrice(_lendingRenting.lending.nftPrice, scale);
uint256 rentPrice =
unpackPrice(_lendingRenting.lending.dailyRentPrice, scale);
uint256 totalRenterPmtWoCollateral =
rentPrice * _lendingRenting.renting.rentDuration;
uint256 sendLenderAmt =
(_secondsSinceRentStart * rentPrice) / SECONDS_IN_DAY;
require(
totalRenterPmtWoCollateral > 0,
"ReNFT::total payment wo collateral is zero"
);
require(sendLenderAmt > 0, "ReNFT::lender payment is zero");
uint256 sendRenterAmt = totalRenterPmtWoCollateral - sendLenderAmt;
uint256 takenFee =
takeFee(sendLenderAmt, _lendingRenting.lending.paymentToken);
sendLenderAmt -= takenFee;
sendRenterAmt += nftPrice;
ERC20(paymentToken).safeTransfer(
_lendingRenting.lending.lenderAddress,
sendLenderAmt
);
ERC20(paymentToken).safeTransfer(
_lendingRenting.renting.renterAddress,
sendRenterAmt
);
}
function distributeClaimPayment(LendingRenting memory _lendingRenting)
private
{
uint8 paymentTokenIx = uint8(_lendingRenting.lending.paymentToken);
ensureTokenNotSentinel(paymentTokenIx);
ERC20 paymentToken = ERC20(resolver.getPaymentToken(paymentTokenIx));
uint256 decimals = ERC20(paymentToken).decimals();
uint256 scale = 10**decimals;
uint256 nftPrice =
_lendingRenting.lending.lentAmount *
unpackPrice(_lendingRenting.lending.nftPrice, scale);
uint256 rentPrice =
unpackPrice(_lendingRenting.lending.dailyRentPrice, scale);
uint256 maxRentPayment =
rentPrice * _lendingRenting.renting.rentDuration;
uint256 takenFee =
takeFee(maxRentPayment, IResolver.PaymentToken(paymentTokenIx));
uint256 finalAmt = maxRentPayment + nftPrice;
require(maxRentPayment > 0, "ReNFT::collateral plus rent is zero");
paymentToken.safeTransfer(
_lendingRenting.lending.lenderAddress,
finalAmt - takenFee
);
}
function safeTransfer(
CallData memory _cd,
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _lentAmounts
) private {
if (is721(_cd.nfts[_cd.left])) {
IERC721(_cd.nfts[_cd.left]).transferFrom(
_from,
_to,
_cd.tokenIds[_cd.left]
);
} else if (is1155(_cd.nfts[_cd.left])) {
IERC1155(_cd.nfts[_cd.left]).safeBatchTransferFrom(
_from,
_to,
_tokenIds,
_lentAmounts,
""
);
} else {
revert("ReNFT::unsupported token type");
}
}
function handleLend(CallData memory _cd) private {
for (uint256 i = _cd.left; i < _cd.right; i++) {
ensureIsLendable(_cd, i);
LendingRenting storage item =
lendingRenting[
keccak256(
abi.encodePacked(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
lendingId
)
)
];
ensureIsNull(item.lending);
ensureIsNull(item.renting);
bool nftIs721 = is721(_cd.nfts[i]);
item.lending = Lending({
lenderAddress: payable(msg.sender),
lentAmount: nftIs721 ? 1 : uint8(_cd.lentAmounts[i]),
maxRentDuration: _cd.maxRentDurations[i],
dailyRentPrice: _cd.dailyRentPrices[i],
nftPrice: _cd.nftPrices[i],
paymentToken: _cd.paymentTokens[i]
});
emit Lent(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
nftIs721 ? 1 : uint8(_cd.lentAmounts[i]),
lendingId,
msg.sender,
_cd.maxRentDurations[i],
_cd.dailyRentPrices[i],
_cd.nftPrices[i],
nftIs721,
_cd.paymentTokens[i]
);
lendingId++;
}
safeTransfer(
_cd,
msg.sender,
address(this),
sliceArr(_cd.tokenIds, _cd.left, _cd.right, 0),
sliceArr(_cd.lentAmounts, _cd.left, _cd.right, 0)
);
}
function handleRent(CallData memory _cd) private {
uint256[] memory lentAmounts = new uint256[](_cd.right - _cd.left);
for (uint256 i = _cd.left; i < _cd.right; i++) {
LendingRenting storage item =
lendingRenting[
keccak256(
abi.encodePacked(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
_cd.lendingIds[i]
)
)
];
ensureIsNotNull(item.lending);
ensureIsNull(item.renting);
ensureIsRentable(item.lending, _cd, i, msg.sender);
uint8 paymentTokenIx = uint8(item.lending.paymentToken);
ensureTokenNotSentinel(paymentTokenIx);
address paymentToken = resolver.getPaymentToken(paymentTokenIx);
uint256 decimals = ERC20(paymentToken).decimals();
{
uint256 scale = 10**decimals;
uint256 rentPrice =
_cd.rentDurations[i] *
unpackPrice(item.lending.dailyRentPrice, scale);
uint256 nftPrice =
item.lending.lentAmount *
unpackPrice(item.lending.nftPrice, scale);
require(rentPrice > 0, "ReNFT::rent price is zero");
require(nftPrice > 0, "ReNFT::nft price is zero");
ERC20(paymentToken).safeTransferFrom(
msg.sender,
address(this),
rentPrice + nftPrice
);
}
lentAmounts[i - _cd.left] = item.lending.lentAmount;
item.renting.renterAddress = payable(msg.sender);
item.renting.rentDuration = _cd.rentDurations[i];
item.renting.rentedAt = uint32(block.timestamp);
emit Rented(
_cd.lendingIds[i],
msg.sender,
_cd.rentDurations[i],
item.renting.rentedAt
);
}
safeTransfer(
_cd,
address(this),
msg.sender,
sliceArr(_cd.tokenIds, _cd.left, _cd.right, 0),
sliceArr(lentAmounts, _cd.left, _cd.right, _cd.left)
);
}
function handleReturn(CallData memory _cd) private {
uint256[] memory lentAmounts = new uint256[](_cd.right - _cd.left);
for (uint256 i = _cd.left; i < _cd.right; i++) {
LendingRenting storage item =
lendingRenting[
keccak256(
abi.encodePacked(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
_cd.lendingIds[i]
)
)
];
ensureIsNotNull(item.lending);
ensureIsReturnable(item.renting, msg.sender, block.timestamp);
uint256 secondsSinceRentStart =
block.timestamp - item.renting.rentedAt;
distributePayments(item, secondsSinceRentStart);
lentAmounts[i - _cd.left] = item.lending.lentAmount;
emit Returned(_cd.lendingIds[i], uint32(block.timestamp));
delete item.renting;
}
safeTransfer(
_cd,
msg.sender,
address(this),
sliceArr(_cd.tokenIds, _cd.left, _cd.right, 0),
sliceArr(lentAmounts, _cd.left, _cd.right, _cd.left)
);
}
function handleStopLending(CallData memory _cd) private {
uint256[] memory lentAmounts = new uint256[](_cd.right - _cd.left);
for (uint256 i = _cd.left; i < _cd.right; i++) {
LendingRenting storage item =
lendingRenting[
keccak256(
abi.encodePacked(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
_cd.lendingIds[i]
)
)
];
ensureIsNotNull(item.lending);
ensureIsNull(item.renting);
ensureIsStoppable(item.lending, msg.sender);
lentAmounts[i - _cd.left] = item.lending.lentAmount;
emit LendingStopped(_cd.lendingIds[i], uint32(block.timestamp));
delete item.lending;
}
safeTransfer(
_cd,
address(this),
msg.sender,
sliceArr(_cd.tokenIds, _cd.left, _cd.right, 0),
sliceArr(lentAmounts, _cd.left, _cd.right, _cd.left)
);
}
function handleClaimCollateral(CallData memory _cd) private {
for (uint256 i = _cd.left; i < _cd.right; i++) {
LendingRenting storage item =
lendingRenting[
keccak256(
abi.encodePacked(
_cd.nfts[_cd.left],
_cd.tokenIds[i],
_cd.lendingIds[i]
)
)
];
ensureIsNotNull(item.lending);
ensureIsNotNull(item.renting);
ensureIsClaimable(item.renting, block.timestamp);
distributeClaimPayment(item);
emit CollateralClaimed(_cd.lendingIds[i], uint32(block.timestamp));
delete item.lending;
delete item.renting;
}
}
function is721(address _nft) private view returns (bool) {
return IERC165(_nft).supportsInterface(type(IERC721).interfaceId);
}
function is1155(address _nft) private view returns (bool) {
return IERC165(_nft).supportsInterface(type(IERC1155).interfaceId);
}
function createLendCallData(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendAmounts,
uint8[] memory _maxRentDurations,
bytes4[] memory _dailyRentPrices,
bytes4[] memory _nftPrices,
IResolver.PaymentToken[] memory _paymentTokens
) private pure returns (CallData memory cd) {
cd = CallData({
left: 0,
right: 1,
nfts: _nfts,
tokenIds: _tokenIds,
lentAmounts: _lendAmounts,
lendingIds: new uint256[](0),
rentDurations: new uint8[](0),
maxRentDurations: _maxRentDurations,
dailyRentPrices: _dailyRentPrices,
nftPrices: _nftPrices,
paymentTokens: _paymentTokens
});
}
function createRentCallData(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds,
uint8[] memory _rentDurations
) private pure returns (CallData memory cd) {
cd = CallData({
left: 0,
right: 1,
nfts: _nfts,
tokenIds: _tokenIds,
lentAmounts: new uint256[](0),
lendingIds: _lendingIds,
rentDurations: _rentDurations,
maxRentDurations: new uint8[](0),
dailyRentPrices: new bytes4[](0),
nftPrices: new bytes4[](0),
paymentTokens: new IResolver.PaymentToken[](0)
});
}
function createActionCallData(
address[] memory _nfts,
uint256[] memory _tokenIds,
uint256[] memory _lendingIds
) private pure returns (CallData memory cd) {
cd = CallData({
left: 0,
right: 1,
nfts: _nfts,
tokenIds: _tokenIds,
lentAmounts: new uint256[](0),
lendingIds: _lendingIds,
rentDurations: new uint8[](0),
maxRentDurations: new uint8[](0),
dailyRentPrices: new bytes4[](0),
nftPrices: new bytes4[](0),
paymentTokens: new IResolver.PaymentToken[](0)
});
}
function unpackPrice(bytes4 _price, uint256 _scale)
private
pure
returns (uint256)
{
ensureIsUnpackablePrice(_price, _scale);
uint16 whole = uint16(bytes2(_price));
uint16 decimal = uint16(bytes2(_price << 16));
uint256 decimalScale = _scale / 10000;
if (whole > 9999) {
whole = 9999;
}
if (decimal > 9999) {
decimal = 9999;
}
uint256 w = whole * _scale;
uint256 d = decimal * decimalScale;
uint256 price = w + d;
return price;
}
function sliceArr(
uint256[] memory _arr,
uint256 _fromIx,
uint256 _toIx,
uint256 _arrOffset
) private pure returns (uint256[] memory r) {
r = new uint256[](_toIx - _fromIx);
for (uint256 i = _fromIx; i < _toIx; i++) {
r[i - _fromIx] = _arr[i - _arrOffset];
}
}
function ensureIsNotZeroAddr(address _addr) private pure {
require(_addr != address(0), "ReNFT::zero address");
}
function ensureIsZeroAddr(address _addr) private pure {
require(_addr == address(0), "ReNFT::not a zero address");
}
function ensureIsNull(Lending memory _lending) private pure {
ensureIsZeroAddr(_lending.lenderAddress);
require(_lending.maxRentDuration == 0, "ReNFT::duration not zero");
require(_lending.dailyRentPrice == 0, "ReNFT::rent price not zero");
require(_lending.nftPrice == 0, "ReNFT::nft price not zero");
}
function ensureIsNotNull(Lending memory _lending) private pure {
ensureIsNotZeroAddr(_lending.lenderAddress);
require(_lending.maxRentDuration != 0, "ReNFT::duration zero");
require(_lending.dailyRentPrice != 0, "ReNFT::rent price is zero");
require(_lending.nftPrice != 0, "ReNFT::nft price is zero");
}
function ensureIsNull(Renting memory _renting) private pure {
ensureIsZeroAddr(_renting.renterAddress);
require(_renting.rentDuration == 0, "ReNFT::duration not zero");
require(_renting.rentedAt == 0, "ReNFT::rented at not zero");
}
function ensureIsNotNull(Renting memory _renting) private pure {
ensureIsNotZeroAddr(_renting.renterAddress);
require(_renting.rentDuration != 0, "ReNFT::duration is zero");
require(_renting.rentedAt != 0, "ReNFT::rented at is zero");
}
function ensureIsLendable(CallData memory _cd, uint256 _i) private pure {
require(_cd.lentAmounts[_i] > 0, "ReNFT::lend amount is zero");
require(_cd.lentAmounts[_i] <= type(uint8).max, "ReNFT::not uint8");
require(_cd.maxRentDurations[_i] > 0, "ReNFT::duration is zero");
require(
_cd.maxRentDurations[_i] <= type(uint8).max,
"ReNFT::not uint8"
);
require(
uint32(_cd.dailyRentPrices[_i]) > 0,
"ReNFT::rent price is zero"
);
require(uint32(_cd.nftPrices[_i]) > 0, "ReNFT::nft price is zero");
}
function ensureIsRentable(
Lending memory _lending,
CallData memory _cd,
uint256 _i,
address _msgSender
) private pure {
require(
_msgSender != _lending.lenderAddress,
"ReNFT::cant rent own nft"
);
require(_cd.rentDurations[_i] <= type(uint8).max, "ReNFT::not uint8");
require(_cd.rentDurations[_i] > 0, "ReNFT::duration is zero");
require(
_cd.rentDurations[_i] <= _lending.maxRentDuration,
"ReNFT::rent duration exceeds allowed max"
);
}
function ensureIsReturnable(
Renting memory _renting,
address _msgSender,
uint256 _blockTimestamp
) private pure {
require(_renting.renterAddress == _msgSender, "ReNFT::not renter");
require(
!isPastReturnDate(_renting, _blockTimestamp),
"ReNFT::past return date"
);
}
function ensureIsStoppable(Lending memory _lending, address _msgSender)
private
pure
{
require(_lending.lenderAddress == _msgSender, "ReNFT::not lender");
}
function ensureIsClaimable(Renting memory _renting, uint256 _blockTimestamp)
private
pure
{
require(
isPastReturnDate(_renting, _blockTimestamp),
"ReNFT::return date not passed"
);
}
function ensureIsUnpackablePrice(bytes4 _price, uint256 _scale)
private
pure
{
require(uint32(_price) > 0, "ReNFT::invalid price");
require(_scale >= 10000, "ReNFT::invalid scale");
}
function ensureTokenNotSentinel(uint8 _paymentIx) private pure {
require(_paymentIx > 0, "ReNFT::token is sentinel");
}
function isPastReturnDate(Renting memory _renting, uint256 _now)
private
pure
returns (bool)
{
require(_now > _renting.rentedAt, "ReNFT::now before rented");
return
_now - _renting.rentedAt > _renting.rentDuration * SECONDS_IN_DAY;
}
function setRentFee(uint256 _rentFee) external onlyAdmin {
require(_rentFee < 10000, "ReNFT::fee exceeds 100pct");
rentFee = _rentFee;
}
function setBeneficiary(address payable _newBeneficiary)
external
onlyAdmin
{
beneficiary = _newBeneficiary;
}
function setPaused(bool _paused) external onlyAdmin {
paused = _paused;
}
}
文件 17 的 17:SafeERC20.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
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));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
{
"compilationTarget": {
"src/ReNFT.sol": "ReNFT"
},
"evmVersion": "berlin",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_resolver","type":"address"},{"internalType":"address payable","name":"_beneficiary","type":"address"},{"internalType":"address","name":"_admin","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"lendingId","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"claimedAt","type":"uint32"}],"name":"CollateralClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"lendingId","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"stoppedAt","type":"uint32"}],"name":"LendingStopped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"nftAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"lentAmount","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"lendingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"lenderAddress","type":"address"},{"indexed":false,"internalType":"uint8","name":"maxRentDuration","type":"uint8"},{"indexed":false,"internalType":"bytes4","name":"dailyRentPrice","type":"bytes4"},{"indexed":false,"internalType":"bytes4","name":"nftPrice","type":"bytes4"},{"indexed":false,"internalType":"bool","name":"isERC721","type":"bool"},{"indexed":false,"internalType":"enum IResolver.PaymentToken","name":"paymentToken","type":"uint8"}],"name":"Lent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"lendingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"renterAddress","type":"address"},{"indexed":false,"internalType":"uint8","name":"rentDuration","type":"uint8"},{"indexed":false,"internalType":"uint32","name":"rentedAt","type":"uint32"}],"name":"Rented","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"lendingId","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"returnedAt","type":"uint32"}],"name":"Returned","type":"event"},{"inputs":[{"internalType":"address[]","name":"_nfts","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"_lendingIds","type":"uint256[]"}],"name":"claimCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_nfts","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"_lendAmounts","type":"uint256[]"},{"internalType":"uint8[]","name":"_maxRentDurations","type":"uint8[]"},{"internalType":"bytes4[]","name":"_dailyRentPrices","type":"bytes4[]"},{"internalType":"bytes4[]","name":"_nftPrices","type":"bytes4[]"},{"internalType":"enum IResolver.PaymentToken[]","name":"_paymentTokens","type":"uint8[]"}],"name":"lend","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_nfts","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"_lendingIds","type":"uint256[]"},{"internalType":"uint8[]","name":"_rentDurations","type":"uint8[]"}],"name":"rent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rentFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_nfts","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"_lendingIds","type":"uint256[]"}],"name":"returnIt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_newBeneficiary","type":"address"}],"name":"setBeneficiary","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_paused","type":"bool"}],"name":"setPaused","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_rentFee","type":"uint256"}],"name":"setRentFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_nfts","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"_lendingIds","type":"uint256[]"}],"name":"stopLending","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]